From 4d1034af3323a868df31eaa0853a445aa764ff7f Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Mon, 17 Aug 2026 17:49:43 +0000 Subject: [PATCH 01/52] libutils: consolidated libfsigc++, libcoroutine and libq Merge the three separate cmake projects into a single libutils project that builds one static library, libutils.a. The public headers are merged into a single include root, so they keep their original include prefixes (coroutine.h, fsigc++/fsigc++.h, qapi/, qerror.h, qqueue.h) and no source file needed to change. Update the build system accordingly: libs2e/configure takes a single --with-libutils flag in place of --with-fsigc++, --with-libq and --with-libcoroutine, and all consumers use find_package(LIBUTILS). Note that libq and libcoroutine are now built without NDEBUG, which was already the case for libfsigc++ and for the rest of the codebase. Co-Authored-By: Claude Opus 5 (1M context) --- CLAUDE.md | 4 +- Makefile | 127 +++++------------- libcoroutine/CMakeLists.txt | 31 ----- libcoroutine/LIBCOROUTINEConfig.cmake.in | 10 -- libcoroutine/src/CMakeLists.txt | 6 - libcpu/CMakeLists.txt | 6 +- libfsigc++/FSIGCXXConfig.cmake.in | 27 ---- libfsigc++/LICENCE | 20 --- libfsigc++/src/CMakeLists.txt | 27 ---- libq/CMakeLists.txt | 29 ---- libq/COPYING.LIB | 1 - libq/LIBQConfig.cmake.in | 10 -- libq/src/CMakeLists.txt | 52 ------- libq/src/tests/CMakeLists.txt | 0 libs2e/CMakeLists.txt | 18 +-- libs2e/configure | 30 ++--- libs2e/src/CMakeLists.txt | 4 +- libs2ecore/CMakeLists.txt | 10 +- libs2eplugins/CMakeLists.txt | 10 +- libtcg/CMakeLists.txt | 6 +- {libfsigc++ => libutils}/CMakeLists.txt | 25 ++-- {libcoroutine => libutils}/COPYING.LIB | 0 libutils/LIBUTILSConfig.cmake.in | 10 ++ .../include/coroutine.h | 0 .../include/fsigc++/fsigc++.h | 0 .../include/qapi/dealloc-visitor.h | 0 {libq => libutils}/include/qapi/error.h | 0 .../include/qapi/forward-visitor.h | 0 {libq => libutils}/include/qapi/helpers.h | 0 .../include/qapi/opts-visitor.h | 0 .../include/qapi/qapi-builtin-types.h | 0 .../include/qapi/qapi-types-compat.h | 0 {libq => libutils}/include/qapi/qmp-event.h | 0 .../include/qapi/qmp/json-parser.h | 0 .../include/qapi/qmp/json-writer.h | 0 {libq => libutils}/include/qapi/qmp/qbool.h | 0 {libq => libutils}/include/qapi/qmp/qdict.h | 0 {libq => libutils}/include/qapi/qmp/qerror.h | 0 {libq => libutils}/include/qapi/qmp/qjson.h | 0 {libq => libutils}/include/qapi/qmp/qlist.h | 0 {libq => libutils}/include/qapi/qmp/qlit.h | 0 {libq => libutils}/include/qapi/qmp/qnull.h | 0 {libq => libutils}/include/qapi/qmp/qnum.h | 0 {libq => libutils}/include/qapi/qmp/qobject.h | 0 {libq => libutils}/include/qapi/qmp/qstring.h | 0 .../include/qapi/qobject-input-visitor.h | 0 .../include/qapi/qobject-output-visitor.h | 0 .../include/qapi/string-input-visitor.h | 0 .../include/qapi/string-output-visitor.h | 0 {libq => libutils}/include/qapi/util.h | 0 .../include/qapi/visitor-impl.h | 0 {libq => libutils}/include/qapi/visitor.h | 0 {libq => libutils}/include/qerror.h | 0 {libq => libutils}/include/qqueue.h | 0 libutils/src/CMakeLists.txt | 66 +++++++++ .../src/coroutine}/coroutine-int.h | 0 .../src/coroutine}/coroutine-ucontext.c | 0 .../src/coroutine}/coroutine.c | 0 .../src => libutils/src/fsigc++}/signals.cpp | 0 .../src => libutils/src/fsigc++}/test.cpp | 0 {libq/src => libutils/src/q}/cutils.c | 0 {libq/src => libutils/src/q}/cutils.h | 0 {libq/src => libutils/src/q}/error.c | 0 .../src/q}/qapi/qapi-forward-visitor.c | 0 {libq/src => libutils/src/q}/qapi/qapi-util.c | 0 .../src/q}/qapi/qapi-visit-core.c | 0 .../src/q}/qapi/qobject-input-visitor.c | 0 .../src/q}/qapi/qobject-output-visitor.c | 0 .../src/q}/qobject/json-lexer.c | 0 .../src/q}/qobject/json-parser-int.h | 0 .../src/q}/qobject/json-parser.c | 0 .../src/q}/qobject/json-streamer.c | 0 .../src/q}/qobject/json-writer.c | 0 {libq/src => libutils/src/q}/qobject/qbool.c | 0 {libq/src => libutils/src/q}/qobject/qdict.c | 0 {libq/src => libutils/src/q}/qobject/qjson.c | 0 {libq/src => libutils/src/q}/qobject/qlist.c | 0 {libq/src => libutils/src/q}/qobject/qlit.c | 0 {libq/src => libutils/src/q}/qobject/qnull.c | 0 {libq/src => libutils/src/q}/qobject/qnum.c | 0 .../src/q}/qobject/qobject-internal.h | 0 .../src => libutils/src/q}/qobject/qobject.c | 0 .../src => libutils/src/q}/qobject/qstring.c | 0 .../src/q}/tests/check-qdict.c | 0 .../src/q}/tests/check-qjson.c | 0 .../src/q}/tests/check-qlist.c | 0 .../src/q}/tests/check-qnull.c | 0 .../src => libutils/src/q}/tests/check-qnum.c | 0 .../src/q}/tests/check-qobject.c | 0 .../src/q}/tests/check-qstring.c | 0 {libq/src => libutils/src/q}/unicode.c | 0 {libq/src => libutils/src/q}/unicode.h | 0 tools/CMakeLists.txt | 12 +- 93 files changed, 151 insertions(+), 390 deletions(-) delete mode 100644 libcoroutine/CMakeLists.txt delete mode 100644 libcoroutine/LIBCOROUTINEConfig.cmake.in delete mode 100644 libcoroutine/src/CMakeLists.txt delete mode 100644 libfsigc++/FSIGCXXConfig.cmake.in delete mode 100644 libfsigc++/LICENCE delete mode 100644 libfsigc++/src/CMakeLists.txt delete mode 100644 libq/CMakeLists.txt delete mode 100644 libq/COPYING.LIB delete mode 100644 libq/LIBQConfig.cmake.in delete mode 100644 libq/src/CMakeLists.txt delete mode 100644 libq/src/tests/CMakeLists.txt rename {libfsigc++ => libutils}/CMakeLists.txt (75%) rename {libcoroutine => libutils}/COPYING.LIB (100%) create mode 100644 libutils/LIBUTILSConfig.cmake.in rename {libcoroutine => libutils}/include/coroutine.h (100%) rename {libfsigc++ => libutils}/include/fsigc++/fsigc++.h (100%) rename {libq => libutils}/include/qapi/dealloc-visitor.h (100%) rename {libq => libutils}/include/qapi/error.h (100%) rename {libq => libutils}/include/qapi/forward-visitor.h (100%) rename {libq => libutils}/include/qapi/helpers.h (100%) rename {libq => libutils}/include/qapi/opts-visitor.h (100%) rename {libq => libutils}/include/qapi/qapi-builtin-types.h (100%) rename {libq => libutils}/include/qapi/qapi-types-compat.h (100%) rename {libq => libutils}/include/qapi/qmp-event.h (100%) rename {libq => libutils}/include/qapi/qmp/json-parser.h (100%) rename {libq => libutils}/include/qapi/qmp/json-writer.h (100%) rename {libq => libutils}/include/qapi/qmp/qbool.h (100%) rename {libq => libutils}/include/qapi/qmp/qdict.h (100%) rename {libq => libutils}/include/qapi/qmp/qerror.h (100%) rename {libq => libutils}/include/qapi/qmp/qjson.h (100%) rename {libq => libutils}/include/qapi/qmp/qlist.h (100%) rename {libq => libutils}/include/qapi/qmp/qlit.h (100%) rename {libq => libutils}/include/qapi/qmp/qnull.h (100%) rename {libq => libutils}/include/qapi/qmp/qnum.h (100%) rename {libq => libutils}/include/qapi/qmp/qobject.h (100%) rename {libq => libutils}/include/qapi/qmp/qstring.h (100%) rename {libq => libutils}/include/qapi/qobject-input-visitor.h (100%) rename {libq => libutils}/include/qapi/qobject-output-visitor.h (100%) rename {libq => libutils}/include/qapi/string-input-visitor.h (100%) rename {libq => libutils}/include/qapi/string-output-visitor.h (100%) rename {libq => libutils}/include/qapi/util.h (100%) rename {libq => libutils}/include/qapi/visitor-impl.h (100%) rename {libq => libutils}/include/qapi/visitor.h (100%) rename {libq => libutils}/include/qerror.h (100%) rename {libq => libutils}/include/qqueue.h (100%) create mode 100644 libutils/src/CMakeLists.txt rename {libcoroutine/src => libutils/src/coroutine}/coroutine-int.h (100%) rename {libcoroutine/src => libutils/src/coroutine}/coroutine-ucontext.c (100%) rename {libcoroutine/src => libutils/src/coroutine}/coroutine.c (100%) rename {libfsigc++/src => libutils/src/fsigc++}/signals.cpp (100%) rename {libfsigc++/src => libutils/src/fsigc++}/test.cpp (100%) rename {libq/src => libutils/src/q}/cutils.c (100%) rename {libq/src => libutils/src/q}/cutils.h (100%) rename {libq/src => libutils/src/q}/error.c (100%) rename {libq/src => libutils/src/q}/qapi/qapi-forward-visitor.c (100%) rename {libq/src => libutils/src/q}/qapi/qapi-util.c (100%) rename {libq/src => libutils/src/q}/qapi/qapi-visit-core.c (100%) rename {libq/src => libutils/src/q}/qapi/qobject-input-visitor.c (100%) rename {libq/src => libutils/src/q}/qapi/qobject-output-visitor.c (100%) rename {libq/src => libutils/src/q}/qobject/json-lexer.c (100%) rename {libq/src => libutils/src/q}/qobject/json-parser-int.h (100%) rename {libq/src => libutils/src/q}/qobject/json-parser.c (100%) rename {libq/src => libutils/src/q}/qobject/json-streamer.c (100%) rename {libq/src => libutils/src/q}/qobject/json-writer.c (100%) rename {libq/src => libutils/src/q}/qobject/qbool.c (100%) rename {libq/src => libutils/src/q}/qobject/qdict.c (100%) rename {libq/src => libutils/src/q}/qobject/qjson.c (100%) rename {libq/src => libutils/src/q}/qobject/qlist.c (100%) rename {libq/src => libutils/src/q}/qobject/qlit.c (100%) rename {libq/src => libutils/src/q}/qobject/qnull.c (100%) rename {libq/src => libutils/src/q}/qobject/qnum.c (100%) rename {libq/src => libutils/src/q}/qobject/qobject-internal.h (100%) rename {libq/src => libutils/src/q}/qobject/qobject.c (100%) rename {libq/src => libutils/src/q}/qobject/qstring.c (100%) rename {libq/src => libutils/src/q}/tests/check-qdict.c (100%) rename {libq/src => libutils/src/q}/tests/check-qjson.c (100%) rename {libq/src => libutils/src/q}/tests/check-qlist.c (100%) rename {libq/src => libutils/src/q}/tests/check-qnull.c (100%) rename {libq/src => libutils/src/q}/tests/check-qnum.c (100%) rename {libq/src => libutils/src/q}/tests/check-qobject.c (100%) rename {libq/src => libutils/src/q}/tests/check-qstring.c (100%) rename {libq/src => libutils/src/q}/unicode.c (100%) rename {libq/src => libutils/src/q}/unicode.h (100%) diff --git a/CLAUDE.md b/CLAUDE.md index 3f63d2d39..a4a75d58a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,9 +13,7 @@ S2E is a symbolic execution platform. This repository builds `libs2e.so`, a shar - `libtcg/` - TCG (Tiny Code Generator) library - `klee/` - KLEE symbolic execution engine (fork) - `libvmi/` - Virtual machine introspection -- `libq/` - Utility library -- `libfsigc++/` - Signal/slot library -- `libcoroutine/` - Coroutine support +- `libutils/` - Utility library (QObject/QAPI, signal/slot, coroutines) - `guest/` - Guest-side tools and libraries - `tools/` - Offline analysis tools - `lua/` - Lua headers (for plugin configuration) diff --git a/Makefile b/Makefile index d80227e20..b656a8f33 100644 --- a/Makefile +++ b/Makefile @@ -134,9 +134,8 @@ list: ALWAYS: -$(KLEE_DIRS) libq-debug libq-release \ -libfsigc++-debug libfsigc++-release libvmi-debug libvmi-release \ -libcoroutine-release libcoroutine-debug libs2e-debug libs2e-release \ +$(KLEE_DIRS) libutils-debug libutils-release \ +libvmi-debug libvmi-release libs2e-debug libs2e-release \ tools-debug tools-release: mkdir -p $@ @@ -337,92 +336,34 @@ stamps/libvmi-release-install: stamps/libvmi-release-make $(MAKE) -C libvmi-release install touch $@ -############## -# libfsigc++ # -############## - -LIBFSIGCXX_COMMON_FLAGS = -DCMAKE_MODULE_PATH=$(S2E_SRC)/cmake \ - -DCMAKE_C_COMPILER=$(SYSTEM_CLANG_CC) \ - -DCMAKE_CXX_COMPILER=$(SYSTEM_CLANG_CXX) \ - -DCMAKE_C_FLAGS="$(CFLAGS_ARCH)" \ - -G "Unix Makefiles" - -stamps/libfsigc++-debug-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libfsigc++) - -stamps/libfsigc++-debug-configure: CONFIGURE_COMMAND = cmake $(LIBFSIGCXX_COMMON_FLAGS) \ - -DCMAKE_BUILD_TYPE=Debug \ - -DCMAKE_CXX_FLAGS="$(CXXFLAGS_DEBUG)" \ - $(S2E_SRC)/libfsigc++ - - -stamps/libfsigc++-release-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libfsigc++) - -stamps/libfsigc++-release-configure: CONFIGURE_COMMAND = cmake $(LIBFSIGCXX_COMMON_FLAGS) \ - -DCMAKE_BUILD_TYPE=$(RELEASE_BUILD_TYPE) \ - -DCMAKE_CXX_FLAGS="$(CXXFLAGS_RELEASE)" \ - $(S2E_SRC)/libfsigc++ - -stamps/libfsigc++-debug-make: stamps/libfsigc++-debug-configure $(call FIND_SOURCE,$(S2E_SRC)/libfsigc++) - -stamps/libfsigc++-release-make: stamps/libfsigc++-release-configure $(call FIND_SOURCE,$(S2E_SRC)/libfsigc++) - -######## -# libq # -######## - -LIBQ_COMMON_FLAGS = -DCMAKE_MODULE_PATH=$(S2E_SRC)/cmake \ - -DCMAKE_C_COMPILER=$(SYSTEM_CLANG_CC) \ - -DCMAKE_CXX_COMPILER=$(SYSTEM_CLANG_CXX) \ - -DCMAKE_C_FLAGS="$(CFLAGS_ARCH)" \ - -G "Unix Makefiles" - -stamps/libq-debug-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libq) - -stamps/libq-debug-configure: CONFIGURE_COMMAND = cmake $(LIBQ_COMMON_FLAGS) \ - -DCMAKE_BUILD_TYPE=Debug \ - -DCMAKE_CXX_FLAGS="$(CXXFLAGS_DEBUG)" \ - $(S2E_SRC)/libq - - -stamps/libq-release-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libq) - -stamps/libq-release-configure: CONFIGURE_COMMAND = cmake $(LIBQ_COMMON_FLAGS) \ - -DCMAKE_BUILD_TYPE=$(RELEASE_BUILD_TYPE) \ - -DCMAKE_CXX_FLAGS="$(CXXFLAGS_RELEASE)" \ - $(S2E_SRC)/libq - -stamps/libq-debug-make: stamps/libq-debug-configure $(call FIND_SOURCE,$(S2E_SRC)/libq) - -stamps/libq-release-make: stamps/libq-release-configure $(call FIND_SOURCE,$(S2E_SRC)/libq) - -################ -# libcoroutine # -################ +############ +# libutils # +############ -LIBCOROUTINE_COMMON_FLAGS = -DCMAKE_MODULE_PATH=$(S2E_SRC)/cmake \ - -DCMAKE_C_COMPILER=$(SYSTEM_CLANG_CC) \ - -DCMAKE_CXX_COMPILER=$(SYSTEM_CLANG_CXX) \ - -DCMAKE_C_FLAGS="$(CFLAGS_ARCH)" \ - -G "Unix Makefiles" +LIBUTILS_COMMON_FLAGS = -DCMAKE_MODULE_PATH=$(S2E_SRC)/cmake \ + -DCMAKE_C_COMPILER=$(SYSTEM_CLANG_CC) \ + -DCMAKE_CXX_COMPILER=$(SYSTEM_CLANG_CXX) \ + -DCMAKE_C_FLAGS="$(CFLAGS_ARCH)" \ + -G "Unix Makefiles" -stamps/libcoroutine-debug-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libcoroutine) +stamps/libutils-debug-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libutils) -stamps/libcoroutine-debug-configure: CONFIGURE_COMMAND = cmake $(LIBCOROUTINE_COMMON_FLAGS) \ - -DCMAKE_BUILD_TYPE=Debug \ - -DCMAKE_CXX_FLAGS="$(CXXFLAGS_DEBUG)" \ - $(S2E_SRC)/libcoroutine +stamps/libutils-debug-configure: CONFIGURE_COMMAND = cmake $(LIBUTILS_COMMON_FLAGS) \ + -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_CXX_FLAGS="$(CXXFLAGS_DEBUG)" \ + $(S2E_SRC)/libutils -stamps/libcoroutine-release-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libcoroutine) +stamps/libutils-release-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libutils) -stamps/libcoroutine-release-configure: CONFIGURE_COMMAND = cmake $(LIBCOROUTINE_COMMON_FLAGS) \ - -DCMAKE_BUILD_TYPE=$(RELEASE_BUILD_TYPE) \ - -DCMAKE_CXX_FLAGS="$(CXXFLAGS_RELEASE)" \ - $(S2E_SRC)/libcoroutine +stamps/libutils-release-configure: CONFIGURE_COMMAND = cmake $(LIBUTILS_COMMON_FLAGS) \ + -DCMAKE_BUILD_TYPE=$(RELEASE_BUILD_TYPE) \ + -DCMAKE_CXX_FLAGS="$(CXXFLAGS_RELEASE)" \ + $(S2E_SRC)/libutils -stamps/libcoroutine-debug-make: stamps/libcoroutine-debug-configure $(call FIND_SOURCE,$(S2E_SRC)/libcoroutine) +stamps/libutils-debug-make: stamps/libutils-debug-configure $(call FIND_SOURCE,$(S2E_SRC)/libutils) -stamps/libcoroutine-release-make: stamps/libcoroutine-release-configure $(call FIND_SOURCE,$(S2E_SRC)/libcoroutine) +stamps/libutils-release-make: stamps/libutils-release-configure $(call FIND_SOURCE,$(S2E_SRC)/libutils) ########## # libs2e # @@ -444,24 +385,19 @@ LIBS2E_CONFIGURE_FLAGS = --with-cc=$(SYSTEM_CLANG_CC) LIBS2E_DEBUG_FLAGS = --with-llvm=$(LLVM_PREFIX) \ --with-klee=$(S2E_BUILD)/klee-debug \ --with-libvmi=$(S2E_BUILD)/libvmi-debug \ - --with-fsigc++=$(S2E_BUILD)/libfsigc++-debug \ - --with-libq=$(S2E_BUILD)/libq-debug \ - --with-libcoroutine=$(S2E_BUILD)/libcoroutine-debug \ + --with-libutils=$(S2E_BUILD)/libutils-debug \ --with-cxxflags="$(CXXFLAGS_DEBUG)" \ --enable-debug LIBS2E_RELEASE_FLAGS = --with-llvm=$(LLVM_PREFIX) \ --with-klee=$(S2E_BUILD)/klee-release \ --with-libvmi=$(S2E_BUILD)/libvmi-release \ - --with-fsigc++=$(S2E_BUILD)/libfsigc++-release \ - --with-libq=$(S2E_BUILD)/libq-release \ - --with-libcoroutine=$(S2E_BUILD)/libcoroutine-release \ + --with-libutils=$(S2E_BUILD)/libutils-release \ --with-cxxflags="$(CXXFLAGS_RELEASE)" stamps/libs2e-debug-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libs2e) stamps/libs2e-debug-configure: stamps/lua-make stamps/libvmi-debug-install \ - stamps/klee-debug-make stamps/libfsigc++-debug-make \ - stamps/libq-debug-make stamps/libcoroutine-debug-make \ + stamps/klee-debug-make stamps/libutils-debug-make \ stamps/klee-coverage-make stamps/libs2e-debug-configure: CONFIGURE_COMMAND = $(S2E_SRC)/libs2e/configure \ $(LIBS2E_CONFIGURE_FLAGS) \ @@ -469,8 +405,7 @@ stamps/libs2e-debug-configure: CONFIGURE_COMMAND = $(S2E_SRC)/libs2e/configure stamps/libs2e-release-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libs2e) stamps/libs2e-release-configure: stamps/lua-make stamps/libvmi-release-install \ - stamps/klee-release-make stamps/libfsigc++-release-make \ - stamps/libq-release-make stamps/libcoroutine-release-make + stamps/klee-release-make stamps/libutils-release-make stamps/libs2e-release-configure: CONFIGURE_COMMAND = $(S2E_SRC)/libs2e/configure \ $(LIBS2E_CONFIGURE_FLAGS) \ @@ -551,20 +486,18 @@ TOOLS_CONFIGURE_FLAGS = -DCMAKE_INSTALL_PREFIX=$(S2E_PREFIX) \ -DS2EPLUGINS_SRC_DIR=$(S2E_SRC)/libs2eplugins/src \ -G "Unix Makefiles" -stamps/tools-debug-configure: stamps/libvmi-debug-make stamps/libfsigc++-debug-make stamps/libq-debug-make +stamps/tools-debug-configure: stamps/libvmi-debug-make stamps/libutils-debug-make stamps/tools-debug-configure: CONFIGURE_COMMAND = cmake $(TOOLS_CONFIGURE_FLAGS) \ -DVMI_DIR=$(S2E_BUILD)/libvmi-debug \ - -DFSIGCXX_DIR=$(S2E_BUILD)/libfsigc++-debug \ - -DLIBQ_DIR=$(S2E_BUILD)/libq-debug \ + -DLIBUTILS_DIR=$(S2E_BUILD)/libutils-debug \ -DCMAKE_BUILD_TYPE=Debug \ -DCMAKE_CXX_FLAGS="$(CXXFLAGS_DEBUG)" \ $(S2E_SRC)/tools -stamps/tools-release-configure: stamps/libvmi-release-make stamps/libfsigc++-release-make stamps/libq-release-make +stamps/tools-release-configure: stamps/libvmi-release-make stamps/libutils-release-make stamps/tools-release-configure: CONFIGURE_COMMAND = cmake $(TOOLS_CONFIGURE_FLAGS) \ -DVMI_DIR=$(S2E_BUILD)/libvmi-release \ - -DFSIGCXX_DIR=$(S2E_BUILD)/libfsigc++-release \ - -DLIBQ_DIR=$(S2E_BUILD)/libq-release \ + -DLIBUTILS_DIR=$(S2E_BUILD)/libutils-release \ -DCMAKE_BUILD_TYPE=$(RELEASE_BUILD_TYPE) \ -DCMAKE_CXX_FLAGS="$(CXXFLAGS_RELEASE)" \ $(S2E_SRC)/tools diff --git a/libcoroutine/CMakeLists.txt b/libcoroutine/CMakeLists.txt deleted file mode 100644 index 36b8f71ea..000000000 --- a/libcoroutine/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright 2016 - Cyberhaven -# This work is licensed under the terms of the GNU LGPL, version 2.1 or later. - -cmake_minimum_required(VERSION 3.10) - - -project(LIBCOROUTINE) -set(LIBCOROUTINE_VERSION_MAJOR 1) -set(LIBCOROUTINE_VERSION_MINOR 0) -set(LIBCOROUTINE_VERSION_PATCH 0) -set(LIBCOROUTINE_PACKAGE_VERSION - "${LIBCOROUTINE_VERSION_MAJOR}.${LIBCOROUTINE_VERSION_MINOR}.${LIBCOROUTINE_VERSION_PATCH}") - -include(CMakePackageConfigHelpers) -set(CMAKE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Version.cmake") -write_basic_package_version_file(${CMAKE_VERSION_FILE} - VERSION ${LIBCOROUTINE_PACKAGE_VERSION} - COMPATIBILITY AnyNewerVersion) - -set(CMAKE_CONFIG_FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake") -set(LIBCOROUTINE_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/include") -set(LIBCOROUTINE_LIBRARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/src") -configure_file(LIBCOROUTINEConfig.cmake.in ${CMAKE_CONFIG_FILE} @ONLY) - - -find_package(PkgConfig REQUIRED) -pkg_check_modules(GLIB_PKG glib-2.0) - -include_directories(${GLIB_PKG_INCLUDE_DIRS} ${LIBCOROUTINE_INCLUDE_DIR}) - -add_subdirectory(src) diff --git a/libcoroutine/LIBCOROUTINEConfig.cmake.in b/libcoroutine/LIBCOROUTINEConfig.cmake.in deleted file mode 100644 index 3753eea63..000000000 --- a/libcoroutine/LIBCOROUTINEConfig.cmake.in +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright 2017 - Cyberhaven -# This work is licensed under the terms of the GNU LGPL, version 2.1 or later. - -set(LIBCOROUTINE_VERSION_MAJOR @LIBCOROUTINE_VERSION_MAJOR@) -set(LIBCOROUTINE_VERSION_MINOR @LIBCOROUTINE_VERSION_MINOR@) -set(LIBCOROUTINE_VERSION_PATCH @LIBCOROUTINE_VERSION_PATCH@) -set(LIBCOROUTINE_PACKAGE_VERSION @LIBCOROUTINE_PACKAGE_VERSION@) - -set(LIBCOROUTINE_INCLUDE_DIR "@LIBCOROUTINE_INCLUDE_DIR@") -set(LIBCOROUTINE_LIBRARY_DIR "@LIBCOROUTINE_LIBRARY_DIR@") diff --git a/libcoroutine/src/CMakeLists.txt b/libcoroutine/src/CMakeLists.txt deleted file mode 100644 index 536ee012a..000000000 --- a/libcoroutine/src/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -# Copyright 2016 - Cyberhaven -# This work is licensed under the terms of the GNU LGPL, version 2.1 or later. - -add_library(coroutine coroutine.c coroutine-ucontext.c) - -set(CMAKE_C_FLAGS "-Wall -Werror -fPIC") diff --git a/libcpu/CMakeLists.txt b/libcpu/CMakeLists.txt index d978a16f4..aef9f2e44 100644 --- a/libcpu/CMakeLists.txt +++ b/libcpu/CMakeLists.txt @@ -26,8 +26,8 @@ pkg_check_modules(GLIB_PKG glib-2.0) pkg_check_modules(CAPSTONE REQUIRED capstone) -find_package(LIBQ REQUIRED) -message(STATUS "Found libq ${LIBQ_PACKAGE_VERSION}") +find_package(LIBUTILS REQUIRED) +message(STATUS "Found libutils ${LIBUTILS_PACKAGE_VERSION}") find_package(LIBTCG REQUIRED) message(STATUS "Found libtcg ${LIBTCG_PACKAGE_VERSION}") @@ -108,7 +108,7 @@ string (REGEX REPLACE "(^| )[/-]D *NDEBUG($| )" " " endforeach() include_directories(${GLIB_PKG_INCLUDE_DIRS} - ${LIBQ_INCLUDE_DIR} + ${LIBUTILS_INCLUDE_DIR} ${CAPSTONE_INCLUDE_DIRS} ${LIBTCG_INCLUDE_DIR} ${HOST_INCLUDE_DIR} diff --git a/libfsigc++/FSIGCXXConfig.cmake.in b/libfsigc++/FSIGCXXConfig.cmake.in deleted file mode 100644 index 6429a39ee..000000000 --- a/libfsigc++/FSIGCXXConfig.cmake.in +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) 2017 Cyberhaven -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -set(FSIGCXX_VERSION_MAJOR @FSIGCXX_VERSION_MAJOR@) -set(FSIGCXX_VERSION_MINOR @FSIGCXX_VERSION_MINOR@) -set(FSIGCXX_VERSION_PATCH @FSIGCXX_VERSION_PATCH@) -set(FSIGCXX_PACKAGE_VERSION @FSIGCXX_PACKAGE_VERSION@) - -set(FSIGCXX_INCLUDE_DIR "@FSIGCXX_INCLUDE_DIR@") -set(FSIGCXX_LIBRARY_DIR "@FSIGCXX_LIBRARY_DIR@") diff --git a/libfsigc++/LICENCE b/libfsigc++/LICENCE deleted file mode 100644 index 39291844a..000000000 --- a/libfsigc++/LICENCE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2017 Cyberhaven -Copyright (c) 2011 Dependable Systems Lab, EPFL - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/libfsigc++/src/CMakeLists.txt b/libfsigc++/src/CMakeLists.txt deleted file mode 100644 index 8f32cace5..000000000 --- a/libfsigc++/src/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) 2017 Cyberhaven -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -set(CMAKE_C_FLAGS "-Wall -Werror -fPIC") -set(CMAKE_CXX_FLAGS "-Wall -Werror -fPIC -std=c++20") - -add_library (fsigc++ signals.cpp) - -add_executable(sigtest test.cpp) -target_link_libraries(sigtest fsigc++) diff --git a/libq/CMakeLists.txt b/libq/CMakeLists.txt deleted file mode 100644 index 9acac3649..000000000 --- a/libq/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2016 - Cyberhaven -# This work is licensed under the terms of the GNU LGPL, version 2.1 or later. - -cmake_minimum_required(VERSION 3.10) - -project(LIBQ) -set(LIBQ_VERSION_MAJOR 1) -set(LIBQ_VERSION_MINOR 0) -set(LIBQ_VERSION_PATCH 0) -set(LIBQ_PACKAGE_VERSION - "${LIBQ_VERSION_MAJOR}.${LIBQ_VERSION_MINOR}.${LIBQ_VERSION_PATCH}") - -include(CMakePackageConfigHelpers) -set(CMAKE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Version.cmake") -write_basic_package_version_file(${CMAKE_VERSION_FILE} - VERSION ${LIBQ_PACKAGE_VERSION} - COMPATIBILITY AnyNewerVersion) - -set(CMAKE_CONFIG_FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake") -set(LIBQ_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/include") -set(LIBQ_LIBRARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/src") -configure_file(LIBQConfig.cmake.in ${CMAKE_CONFIG_FILE} @ONLY) - -find_package(PkgConfig REQUIRED) -pkg_check_modules(GLIB_PKG glib-2.0) - -include_directories(${GLIB_PKG_INCLUDE_DIRS} ${LIBQ_INCLUDE_DIR}) - -add_subdirectory(src) diff --git a/libq/COPYING.LIB b/libq/COPYING.LIB deleted file mode 100644 index d687356e1..000000000 --- a/libq/COPYING.LIB +++ /dev/null @@ -1 +0,0 @@ -This work is licensed under the terms of the GNU LGPL, version 2.1 or later. diff --git a/libq/LIBQConfig.cmake.in b/libq/LIBQConfig.cmake.in deleted file mode 100644 index 0624806b3..000000000 --- a/libq/LIBQConfig.cmake.in +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright 2017 - Cyberhaven -# This work is licensed under the terms of the GNU LGPL, version 2.1 or later. - -set(LIBQ_VERSION_MAJOR @LIBQ_VERSION_MAJOR@) -set(LIBQ_VERSION_MINOR @LIBQ_VERSION_MINOR@) -set(LIBQ_VERSION_PATCH @LIBQ_VERSION_PATCH@) -set(LIBQ_PACKAGE_VERSION @LIBQ_PACKAGE_VERSION@) - -set(LIBQ_INCLUDE_DIR "@LIBQ_INCLUDE_DIR@") -set(LIBQ_LIBRARY_DIR "@LIBQ_LIBRARY_DIR@") diff --git a/libq/src/CMakeLists.txt b/libq/src/CMakeLists.txt deleted file mode 100644 index c871d42fd..000000000 --- a/libq/src/CMakeLists.txt +++ /dev/null @@ -1,52 +0,0 @@ -# Copyright 2016 - Cyberhaven -# This work is licensed under the terms of the GNU LGPL, version 2.1 or later. - -add_library ( - q - qobject/json-lexer.c - qobject/json-parser-int.h - qobject/json-parser.c - qobject/json-streamer.c - qobject/json-writer.c - qobject/qbool.c - qobject/qdict.c - qobject/qjson.c - qobject/qlist.c - qobject/qlit.c - qobject/qnull.c - qobject/qnum.c - qobject/qobject.c - qobject/qstring.c - qapi/qobject-output-visitor.c - qapi/qobject-input-visitor.c - qapi/qapi-forward-visitor.c - qapi/qapi-visit-core.c - qapi/qapi-util.c - error.c - unicode.c - cutils.c -) - -add_executable (check-qdict tests/check-qdict.c) -target_link_libraries(check-qdict q glib-2.0) - -add_executable (check-qjson tests/check-qjson.c) -target_link_libraries(check-qjson q glib-2.0) - -add_executable (check-qlist tests/check-qlist.c) -target_link_libraries(check-qlist q glib-2.0) - -add_executable (check-qnull tests/check-qnull.c) -target_link_libraries(check-qnull q glib-2.0) - -add_executable (check-qnum tests/check-qnum.c) -target_link_libraries(check-qnum q glib-2.0) - -add_executable (check-qobject tests/check-qobject.c) -target_link_libraries(check-qobject q glib-2.0) - -add_executable (check-qstring tests/check-qstring.c) -target_link_libraries(check-qstring q glib-2.0) - - -set(CMAKE_C_FLAGS "-Wall -Werror -Wno-initializer-overrides -fPIC") diff --git a/libq/src/tests/CMakeLists.txt b/libq/src/tests/CMakeLists.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/libs2e/CMakeLists.txt b/libs2e/CMakeLists.txt index 93cefad05..983d79666 100644 --- a/libs2e/CMakeLists.txt +++ b/libs2e/CMakeLists.txt @@ -71,8 +71,8 @@ endforeach() find_package(KLEE REQUIRED) message(STATUS "Found klee ${KLEE_PACKAGE_VERSION}") -find_package(LIBQ REQUIRED) -message(STATUS "Found libq ${LIBQ_PACKAGE_VERSION}") +find_package(LIBUTILS REQUIRED) +message(STATUS "Found libutils ${LIBUTILS_PACKAGE_VERSION}") find_package(LIBCPU REQUIRED) message(STATUS "Found libcpu ${LIBCPU_PACKAGE_VERSION}") @@ -80,15 +80,9 @@ message(STATUS "Found libcpu ${LIBCPU_PACKAGE_VERSION}") find_package(LIBTCG REQUIRED) message(STATUS "Found libtcg ${LIBTCG_PACKAGE_VERSION}") -find_package(FSIGCXX REQUIRED) -message(STATUS "Found fsigc++ ${FSIGCXX_PACKAGE_VERSION}") - find_package(VMI REQUIRED) message(STATUS "Found libvmi ${VMI_PACKAGE_VERSION}") -find_package(LIBCOROUTINE REQUIRED) -message(STATUS "Found libcoroutine ${LIBCOROUTINE_PACKAGE_VERSION}") - if(WITH_TARGET MATCHES "s2e") # TODO: look at libcpu compile options to figure this out find_package(LIBS2ECORE REQUIRED) @@ -117,20 +111,16 @@ endforeach() include_directories(${GLIB_PKG_INCLUDE_DIRS} ${LIBTCG_INCLUDE_DIR} ${LIBCPU_INCLUDE_DIR} - ${FSIGCXX_INCLUDE_DIR} - ${LIBQ_INCLUDE_DIR} - ${LIBCOROUTINE_INCLUDE_DIR} + ${LIBUTILS_INCLUDE_DIR} ${VMI_INCLUDE_DIR}) link_directories(${GLIB_PKG_LIBRARY_DIRS} ${LIBTCG_LIBRARY_DIR} ${LIBCPU_LIBRARY_DIR} - ${LIBQ_LIBRARY_DIR} + ${LIBUTILS_LIBRARY_DIR} ${KLEE_LIBRARY_DIR} ${LUA_DIR} ${Z3_DIR} - ${FSIGCXX_LIBRARY_DIR} - ${LIBCOROUTINE_LIBRARY_DIR} ${LIBS2ECORE_LIBRARY_DIR} ${LIBS2EPLUGINS_LIBRARY_DIR} ${VMI_LIBRARY_DIR}) diff --git a/libs2e/configure b/libs2e/configure index 286a56f53..b6abc6c3d 100755 --- a/libs2e/configure +++ b/libs2e/configure @@ -32,10 +32,8 @@ echo " --with-cxxflags=FLAGS C++ compiler flags" echo " --with-llvm=PATH LLVM binaries path (PATH/bin/llvm-config must exist)" echo " --with-klee=PATH KLEE binaries path" echo " --with-libvmi=PATH libvmi build directory" -echo " --with-fsigc++=PATH fsigc++ build directory" -echo " --with-libq=PATH libq build directory" +echo " --with-libutils=PATH libutils build directory" echo " --with-liblua=PATH Path to lua binaries" -echo " --with-libcoroutine=PATH libcoroutine build directory" echo " --with-libtcg-src=PATH Path to libtcg source" echo " --with-libcpu-src=PATH Path to libcpu source" echo " --with-libs2ecore-src=PATH Path to libs2ecore source" @@ -96,16 +94,8 @@ for opt do Z3_LIBDIR="$optarg" ;; - --with-fsigc++*) - FSIGCXX_DIR="$optarg" - ;; - - --with-libq=*) - LIBQ_DIR="$optarg" - ;; - - --with-libcoroutine=*) - LIBCOROUTINE_DIR="$optarg" + --with-libutils=*) + LIBUTILS_DIR="$optarg" ;; --with-libtcg-src=*) @@ -236,7 +226,7 @@ rm -rf libtcg && mkdir -p libtcg && cd libtcg cmake -DCMAKE_C_COMPILER="$CC" -DCMAKE_CXX_COMPILER="$CXX" \ -DCMAKE_C_FLAGS="$CFLAGS" -DCMAKE_CXX_FLAGS="$CXXFLAGS" \ -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_GUEST="$target" \ - -DLIBQ_DIR=$LIBQ_DIR \ + -DLIBUTILS_DIR=$LIBUTILS_DIR \ "$LIBTCG_SRC" if [ $? -ne 0 ]; then >&2 echo "Failed to configure libtcg" @@ -254,7 +244,7 @@ cmake -DCMAKE_C_COMPILER="$CC" -DCMAKE_CXX_COMPILER="$CXX" \ -DHOST_INCLUDE_DIR="$(cd $(pwd)/../../ && echo $(pwd))" \ -DTARGET_INCLUDE_DIR="$(cd $(pwd)/../ && echo $(pwd))" \ -DS2EGUEST_INCLUDE_DIR=$S2EGUEST_INCDIR \ - -DLIBQ_DIR=$LIBQ_DIR \ + -DLIBUTILS_DIR=$LIBUTILS_DIR \ -DWITH_TARGET="$target" \ -DCONFIG_DATE="$(date)" \ -DCONFIG_LIBCPU_DATADIR="$BUILD_DIR/$target" \ @@ -278,8 +268,7 @@ cmake -DCMAKE_C_COMPILER="$CC" -DCMAKE_CXX_COMPILER="$CXX" \ -DLIBTCG_DIR="$(pwd)/../libtcg" \ -DLIBCPU_DIR="$(pwd)/../libcpu" \ -DKLEE_DIR="$KLEE_ROOT" \ - -DFSIGCXX_DIR="$FSIGCXX_DIR" \ - -DLIBQ_DIR="$LIBQ_DIR" \ + -DLIBUTILS_DIR="$LIBUTILS_DIR" \ -DLUA_DIR="$LIBLUA_LIB" \ "$LIBS2ECORE_SRC" @@ -302,8 +291,7 @@ cmake -DCMAKE_C_COMPILER="$CC" -DCMAKE_CXX_COMPILER="$CXX" \ -DLIBS2ECORE_DIR="$(pwd)/../libs2ecore" \ -DKLEE_DIR="$KLEE_ROOT" \ -DVMI_DIR="$LIBVMI_DIR" \ - -DFSIGCXX_DIR="$FSIGCXX_DIR" \ - -DLIBQ_DIR=$LIBQ_DIR \ + -DLIBUTILS_DIR=$LIBUTILS_DIR \ -DLUA_DIR=$LIBLUA_LIB \ -DS2EGUEST_INCLUDE_DIR=$S2EGUEST_INCDIR \ "$LIBS2EPLUGINS_SRC" @@ -330,12 +318,10 @@ cmake -DCMAKE_C_COMPILER="$CC" -DCMAKE_CXX_COMPILER="$CXX" \ -DCMAKE_PREFIX_PATH="$PREFIX" \ -DLIBTCG_DIR="$(pwd)/../libtcg" \ -DLIBCPU_DIR="$(pwd)/../libcpu" \ - -DLIBQ_DIR="$LIBQ_DIR" \ - -DLIBCOROUTINE_DIR="$LIBCOROUTINE_DIR" \ + -DLIBUTILS_DIR="$LIBUTILS_DIR" \ -DKLEE_DIR="$KLEE_ROOT" \ -DVMI_DIR="$LIBVMI_DIR" \ -DLUA_DIR="$LIBLUA_LIB" \ - -DFSIGCXX_DIR="$FSIGCXX_DIR" \ -DZ3_DIR="$Z3_LIBDIR" \ -DWITH_TARGET="$target" \ $S2E_CMAKE_ARGS \ diff --git a/libs2e/src/CMakeLists.txt b/libs2e/src/CMakeLists.txt index 7d953ebc4..8e484cbf1 100644 --- a/libs2e/src/CMakeLists.txt +++ b/libs2e/src/CMakeLists.txt @@ -66,9 +66,9 @@ if(WITH_TARGET MATCHES "s2e") boost_regex) endif() -set(LIBS ${LIBS} ${LIBCOROUTINE_LIBRARY_DIR}/libcoroutine.a ${FSIGCXX_LIBRARY_DIR}/libfsigc++.a ${LIBQ_LIBRARY_DIR}/libq.a ${CAPSTONE_LIBRARIES} pthread glib-2.0 bsd dl) +set(LIBS ${LIBS} ${LIBUTILS_LIBRARY_DIR}/libutils.a ${CAPSTONE_LIBRARIES} pthread glib-2.0 bsd dl) -target_link_libraries(tests2e PUBLIC ${LIBCOROUTINE_LIBRARY_DIR}/libcoroutine.a pthread glib-2.0) +target_link_libraries(tests2e PUBLIC ${LIBUTILS_LIBRARY_DIR}/libutils.a pthread glib-2.0) target_link_libraries(s2e ${LIBS}) diff --git a/libs2ecore/CMakeLists.txt b/libs2ecore/CMakeLists.txt index 71c3016c7..b5dd07eb0 100644 --- a/libs2ecore/CMakeLists.txt +++ b/libs2ecore/CMakeLists.txt @@ -62,8 +62,8 @@ llvm_map_components_to_libnames(LLVM_LIBS core) ################## -find_package(LIBQ REQUIRED) -message(STATUS "Found libq ${LIBQ_PACKAGE_VERSION}") +find_package(LIBUTILS REQUIRED) +message(STATUS "Found libutils ${LIBUTILS_PACKAGE_VERSION}") find_package(LIBCPU REQUIRED) message(STATUS "Found libcpu ${LIBCPU_PACKAGE_VERSION}") @@ -71,17 +71,13 @@ message(STATUS "Found libcpu ${LIBCPU_PACKAGE_VERSION}") find_package(LIBTCG REQUIRED) message(STATUS "Found libtcg ${LIBTCG_PACKAGE_VERSION}") -find_package(FSIGCXX REQUIRED) -message(STATUS "Found fsigc++ ${FSIGCXX_PACKAGE_VERSION}") - find_package(KLEE REQUIRED) message(STATUS "Found klee ${KLEE_PACKAGE_VERSION}") include_directories(${GLIB_PKG_INCLUDE_DIRS} - ${LIBQ_INCLUDE_DIR} + ${LIBUTILS_INCLUDE_DIR} ${LIBTCG_INCLUDE_DIR} ${LIBCPU_INCLUDE_DIR} - ${FSIGCXX_INCLUDE_DIR} ${LIBS2ECORE_INCLUDE_DIR} ${KLEE_INCLUDE_DIR} ${LUA_DIR} diff --git a/libs2eplugins/CMakeLists.txt b/libs2eplugins/CMakeLists.txt index a960fc39c..f6d0edb3f 100644 --- a/libs2eplugins/CMakeLists.txt +++ b/libs2eplugins/CMakeLists.txt @@ -78,8 +78,8 @@ llvm_map_components_to_libnames(LLVM_LIBS core) include(FindProtobuf) find_package(Protobuf REQUIRED) -find_package(LIBQ REQUIRED) -message(STATUS "Found libq ${LIBQ_PACKAGE_VERSION}") +find_package(LIBUTILS REQUIRED) +message(STATUS "Found libutils ${LIBUTILS_PACKAGE_VERSION}") find_package(LIBCPU REQUIRED) message(STATUS "Found libcpu ${LIBCPU_PACKAGE_VERSION}") @@ -87,9 +87,6 @@ message(STATUS "Found libcpu ${LIBCPU_PACKAGE_VERSION}") find_package(LIBTCG REQUIRED) message(STATUS "Found libtcg ${LIBTCG_PACKAGE_VERSION}") -find_package(FSIGCXX REQUIRED) -message(STATUS "Found fsigc++ ${FSIGCXX_PACKAGE_VERSION}") - find_package(VMI REQUIRED) message(STATUS "Found libvmi ${VMI_PACKAGE_VERSION}") @@ -100,13 +97,12 @@ find_package(KLEE REQUIRED) message(STATUS "Found klee ${KLEE_PACKAGE_VERSION}") include_directories(${GLIB_PKG_INCLUDE_DIRS} - ${LIBQ_INCLUDE_DIR} + ${LIBUTILS_INCLUDE_DIR} ${LIBTCG_INCLUDE_DIR} ${LIBCPU_INCLUDE_DIR} ${VMI_INCLUDE_DIR} ${LIBS2ECORE_INCLUDE_DIR} ${LIBS2EPLUGINS_INCLUDE_DIR} - ${FSIGCXX_INCLUDE_DIR} ${KLEE_INCLUDE_DIR} ${LUA_DIR} ${S2EGUEST_INCLUDE_DIR}) diff --git a/libtcg/CMakeLists.txt b/libtcg/CMakeLists.txt index f1569376a..9a8df8c73 100644 --- a/libtcg/CMakeLists.txt +++ b/libtcg/CMakeLists.txt @@ -41,8 +41,8 @@ configure_file(LIBTCGConfig.cmake.in ${CMAKE_CONFIG_FILE} @ONLY) find_package(PkgConfig REQUIRED) pkg_check_modules(GLIB_PKG glib-2.0) -find_package(LIBQ REQUIRED) -message(STATUS "Found libq ${LIBQ_PACKAGE_VERSION}") +find_package(LIBUTILS REQUIRED) +message(STATUS "Found libutils ${LIBUTILS_PACKAGE_VERSION}") ##### LLVM ##### if (POLICY CMP0075) @@ -89,5 +89,5 @@ if(WITH_GUEST MATCHES "s2e") endif() endif() -include_directories(${GLIB_PKG_INCLUDE_DIRS} ${LIBTCG_INCLUDE_DIR} ${LIBQ_INCLUDE_DIR}) +include_directories(${GLIB_PKG_INCLUDE_DIRS} ${LIBTCG_INCLUDE_DIR} ${LIBUTILS_INCLUDE_DIR}) add_subdirectory(src) diff --git a/libfsigc++/CMakeLists.txt b/libutils/CMakeLists.txt similarity index 75% rename from libfsigc++/CMakeLists.txt rename to libutils/CMakeLists.txt index 68f120f2b..866df83f4 100644 --- a/libfsigc++/CMakeLists.txt +++ b/libutils/CMakeLists.txt @@ -20,23 +20,23 @@ cmake_minimum_required(VERSION 3.10) -project(FSIGCXX) -set(FSIGCXX_VERSION_MAJOR 1) -set(FSIGCXX_VERSION_MINOR 0) -set(FSIGCXX_VERSION_PATCH 0) -set(FSIGCXX_PACKAGE_VERSION - "${FSIGCXX_VERSION_MAJOR}.${FSIGCXX_VERSION_MINOR}.${FSIGCXX_VERSION_PATCH}") +project(LIBUTILS) +set(LIBUTILS_VERSION_MAJOR 1) +set(LIBUTILS_VERSION_MINOR 0) +set(LIBUTILS_VERSION_PATCH 0) +set(LIBUTILS_PACKAGE_VERSION + "${LIBUTILS_VERSION_MAJOR}.${LIBUTILS_VERSION_MINOR}.${LIBUTILS_VERSION_PATCH}") include(CMakePackageConfigHelpers) set(CMAKE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Version.cmake") write_basic_package_version_file(${CMAKE_VERSION_FILE} - VERSION ${FSIGCXX_PACKAGE_VERSION} + VERSION ${LIBUTILS_PACKAGE_VERSION} COMPATIBILITY AnyNewerVersion) set(CMAKE_CONFIG_FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake") -set(FSIGCXX_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/include") -set(FSIGCXX_LIBRARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/src") -configure_file(FSIGCXXConfig.cmake.in ${CMAKE_CONFIG_FILE} @ONLY) +set(LIBUTILS_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/include") +set(LIBUTILS_LIBRARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/src") +configure_file(LIBUTILSConfig.cmake.in ${CMAKE_CONFIG_FILE} @ONLY) # We want to remove NDEBUG from all builds foreach (flags_var_to_scrub @@ -50,6 +50,9 @@ string (REGEX REPLACE "(^| )[/-]D *NDEBUG($| )" " " "${flags_var_to_scrub}" "${${flags_var_to_scrub}}") endforeach() -include_directories(${FSIGCXX_INCLUDE_DIR}) +find_package(PkgConfig REQUIRED) +pkg_check_modules(GLIB_PKG glib-2.0) + +include_directories(${GLIB_PKG_INCLUDE_DIRS} ${LIBUTILS_INCLUDE_DIR}) add_subdirectory(src) diff --git a/libcoroutine/COPYING.LIB b/libutils/COPYING.LIB similarity index 100% rename from libcoroutine/COPYING.LIB rename to libutils/COPYING.LIB diff --git a/libutils/LIBUTILSConfig.cmake.in b/libutils/LIBUTILSConfig.cmake.in new file mode 100644 index 000000000..f36d93682 --- /dev/null +++ b/libutils/LIBUTILSConfig.cmake.in @@ -0,0 +1,10 @@ +# Copyright 2017 - Cyberhaven +# This work is licensed under the terms of the GNU LGPL, version 2.1 or later. + +set(LIBUTILS_VERSION_MAJOR @LIBUTILS_VERSION_MAJOR@) +set(LIBUTILS_VERSION_MINOR @LIBUTILS_VERSION_MINOR@) +set(LIBUTILS_VERSION_PATCH @LIBUTILS_VERSION_PATCH@) +set(LIBUTILS_PACKAGE_VERSION @LIBUTILS_PACKAGE_VERSION@) + +set(LIBUTILS_INCLUDE_DIR "@LIBUTILS_INCLUDE_DIR@") +set(LIBUTILS_LIBRARY_DIR "@LIBUTILS_LIBRARY_DIR@") diff --git a/libcoroutine/include/coroutine.h b/libutils/include/coroutine.h similarity index 100% rename from libcoroutine/include/coroutine.h rename to libutils/include/coroutine.h diff --git a/libfsigc++/include/fsigc++/fsigc++.h b/libutils/include/fsigc++/fsigc++.h similarity index 100% rename from libfsigc++/include/fsigc++/fsigc++.h rename to libutils/include/fsigc++/fsigc++.h diff --git a/libq/include/qapi/dealloc-visitor.h b/libutils/include/qapi/dealloc-visitor.h similarity index 100% rename from libq/include/qapi/dealloc-visitor.h rename to libutils/include/qapi/dealloc-visitor.h diff --git a/libq/include/qapi/error.h b/libutils/include/qapi/error.h similarity index 100% rename from libq/include/qapi/error.h rename to libutils/include/qapi/error.h diff --git a/libq/include/qapi/forward-visitor.h b/libutils/include/qapi/forward-visitor.h similarity index 100% rename from libq/include/qapi/forward-visitor.h rename to libutils/include/qapi/forward-visitor.h diff --git a/libq/include/qapi/helpers.h b/libutils/include/qapi/helpers.h similarity index 100% rename from libq/include/qapi/helpers.h rename to libutils/include/qapi/helpers.h diff --git a/libq/include/qapi/opts-visitor.h b/libutils/include/qapi/opts-visitor.h similarity index 100% rename from libq/include/qapi/opts-visitor.h rename to libutils/include/qapi/opts-visitor.h diff --git a/libq/include/qapi/qapi-builtin-types.h b/libutils/include/qapi/qapi-builtin-types.h similarity index 100% rename from libq/include/qapi/qapi-builtin-types.h rename to libutils/include/qapi/qapi-builtin-types.h diff --git a/libq/include/qapi/qapi-types-compat.h b/libutils/include/qapi/qapi-types-compat.h similarity index 100% rename from libq/include/qapi/qapi-types-compat.h rename to libutils/include/qapi/qapi-types-compat.h diff --git a/libq/include/qapi/qmp-event.h b/libutils/include/qapi/qmp-event.h similarity index 100% rename from libq/include/qapi/qmp-event.h rename to libutils/include/qapi/qmp-event.h diff --git a/libq/include/qapi/qmp/json-parser.h b/libutils/include/qapi/qmp/json-parser.h similarity index 100% rename from libq/include/qapi/qmp/json-parser.h rename to libutils/include/qapi/qmp/json-parser.h diff --git a/libq/include/qapi/qmp/json-writer.h b/libutils/include/qapi/qmp/json-writer.h similarity index 100% rename from libq/include/qapi/qmp/json-writer.h rename to libutils/include/qapi/qmp/json-writer.h diff --git a/libq/include/qapi/qmp/qbool.h b/libutils/include/qapi/qmp/qbool.h similarity index 100% rename from libq/include/qapi/qmp/qbool.h rename to libutils/include/qapi/qmp/qbool.h diff --git a/libq/include/qapi/qmp/qdict.h b/libutils/include/qapi/qmp/qdict.h similarity index 100% rename from libq/include/qapi/qmp/qdict.h rename to libutils/include/qapi/qmp/qdict.h diff --git a/libq/include/qapi/qmp/qerror.h b/libutils/include/qapi/qmp/qerror.h similarity index 100% rename from libq/include/qapi/qmp/qerror.h rename to libutils/include/qapi/qmp/qerror.h diff --git a/libq/include/qapi/qmp/qjson.h b/libutils/include/qapi/qmp/qjson.h similarity index 100% rename from libq/include/qapi/qmp/qjson.h rename to libutils/include/qapi/qmp/qjson.h diff --git a/libq/include/qapi/qmp/qlist.h b/libutils/include/qapi/qmp/qlist.h similarity index 100% rename from libq/include/qapi/qmp/qlist.h rename to libutils/include/qapi/qmp/qlist.h diff --git a/libq/include/qapi/qmp/qlit.h b/libutils/include/qapi/qmp/qlit.h similarity index 100% rename from libq/include/qapi/qmp/qlit.h rename to libutils/include/qapi/qmp/qlit.h diff --git a/libq/include/qapi/qmp/qnull.h b/libutils/include/qapi/qmp/qnull.h similarity index 100% rename from libq/include/qapi/qmp/qnull.h rename to libutils/include/qapi/qmp/qnull.h diff --git a/libq/include/qapi/qmp/qnum.h b/libutils/include/qapi/qmp/qnum.h similarity index 100% rename from libq/include/qapi/qmp/qnum.h rename to libutils/include/qapi/qmp/qnum.h diff --git a/libq/include/qapi/qmp/qobject.h b/libutils/include/qapi/qmp/qobject.h similarity index 100% rename from libq/include/qapi/qmp/qobject.h rename to libutils/include/qapi/qmp/qobject.h diff --git a/libq/include/qapi/qmp/qstring.h b/libutils/include/qapi/qmp/qstring.h similarity index 100% rename from libq/include/qapi/qmp/qstring.h rename to libutils/include/qapi/qmp/qstring.h diff --git a/libq/include/qapi/qobject-input-visitor.h b/libutils/include/qapi/qobject-input-visitor.h similarity index 100% rename from libq/include/qapi/qobject-input-visitor.h rename to libutils/include/qapi/qobject-input-visitor.h diff --git a/libq/include/qapi/qobject-output-visitor.h b/libutils/include/qapi/qobject-output-visitor.h similarity index 100% rename from libq/include/qapi/qobject-output-visitor.h rename to libutils/include/qapi/qobject-output-visitor.h diff --git a/libq/include/qapi/string-input-visitor.h b/libutils/include/qapi/string-input-visitor.h similarity index 100% rename from libq/include/qapi/string-input-visitor.h rename to libutils/include/qapi/string-input-visitor.h diff --git a/libq/include/qapi/string-output-visitor.h b/libutils/include/qapi/string-output-visitor.h similarity index 100% rename from libq/include/qapi/string-output-visitor.h rename to libutils/include/qapi/string-output-visitor.h diff --git a/libq/include/qapi/util.h b/libutils/include/qapi/util.h similarity index 100% rename from libq/include/qapi/util.h rename to libutils/include/qapi/util.h diff --git a/libq/include/qapi/visitor-impl.h b/libutils/include/qapi/visitor-impl.h similarity index 100% rename from libq/include/qapi/visitor-impl.h rename to libutils/include/qapi/visitor-impl.h diff --git a/libq/include/qapi/visitor.h b/libutils/include/qapi/visitor.h similarity index 100% rename from libq/include/qapi/visitor.h rename to libutils/include/qapi/visitor.h diff --git a/libq/include/qerror.h b/libutils/include/qerror.h similarity index 100% rename from libq/include/qerror.h rename to libutils/include/qerror.h diff --git a/libq/include/qqueue.h b/libutils/include/qqueue.h similarity index 100% rename from libq/include/qqueue.h rename to libutils/include/qqueue.h diff --git a/libutils/src/CMakeLists.txt b/libutils/src/CMakeLists.txt new file mode 100644 index 000000000..416cc7ac3 --- /dev/null +++ b/libutils/src/CMakeLists.txt @@ -0,0 +1,66 @@ +# Copyright (c) 2017 Cyberhaven +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror -Wno-initializer-overrides -fPIC") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -fPIC -std=c++20") + +add_library ( + utils + + coroutine/coroutine.c + coroutine/coroutine-ucontext.c + + fsigc++/signals.cpp + + q/qobject/json-lexer.c + q/qobject/json-parser-int.h + q/qobject/json-parser.c + q/qobject/json-streamer.c + q/qobject/json-writer.c + q/qobject/qbool.c + q/qobject/qdict.c + q/qobject/qjson.c + q/qobject/qlist.c + q/qobject/qlit.c + q/qobject/qnull.c + q/qobject/qnum.c + q/qobject/qobject.c + q/qobject/qstring.c + q/qapi/qobject-output-visitor.c + q/qapi/qobject-input-visitor.c + q/qapi/qapi-forward-visitor.c + q/qapi/qapi-visit-core.c + q/qapi/qapi-util.c + q/error.c + q/unicode.c + q/cutils.c +) + +########## +# Tests # +########## + +add_executable(sigtest fsigc++/test.cpp) +target_link_libraries(sigtest utils) + +foreach(test qdict qjson qlist qnull qnum qobject qstring) + add_executable(check-${test} q/tests/check-${test}.c) + target_link_libraries(check-${test} utils glib-2.0) +endforeach() diff --git a/libcoroutine/src/coroutine-int.h b/libutils/src/coroutine/coroutine-int.h similarity index 100% rename from libcoroutine/src/coroutine-int.h rename to libutils/src/coroutine/coroutine-int.h diff --git a/libcoroutine/src/coroutine-ucontext.c b/libutils/src/coroutine/coroutine-ucontext.c similarity index 100% rename from libcoroutine/src/coroutine-ucontext.c rename to libutils/src/coroutine/coroutine-ucontext.c diff --git a/libcoroutine/src/coroutine.c b/libutils/src/coroutine/coroutine.c similarity index 100% rename from libcoroutine/src/coroutine.c rename to libutils/src/coroutine/coroutine.c diff --git a/libfsigc++/src/signals.cpp b/libutils/src/fsigc++/signals.cpp similarity index 100% rename from libfsigc++/src/signals.cpp rename to libutils/src/fsigc++/signals.cpp diff --git a/libfsigc++/src/test.cpp b/libutils/src/fsigc++/test.cpp similarity index 100% rename from libfsigc++/src/test.cpp rename to libutils/src/fsigc++/test.cpp diff --git a/libq/src/cutils.c b/libutils/src/q/cutils.c similarity index 100% rename from libq/src/cutils.c rename to libutils/src/q/cutils.c diff --git a/libq/src/cutils.h b/libutils/src/q/cutils.h similarity index 100% rename from libq/src/cutils.h rename to libutils/src/q/cutils.h diff --git a/libq/src/error.c b/libutils/src/q/error.c similarity index 100% rename from libq/src/error.c rename to libutils/src/q/error.c diff --git a/libq/src/qapi/qapi-forward-visitor.c b/libutils/src/q/qapi/qapi-forward-visitor.c similarity index 100% rename from libq/src/qapi/qapi-forward-visitor.c rename to libutils/src/q/qapi/qapi-forward-visitor.c diff --git a/libq/src/qapi/qapi-util.c b/libutils/src/q/qapi/qapi-util.c similarity index 100% rename from libq/src/qapi/qapi-util.c rename to libutils/src/q/qapi/qapi-util.c diff --git a/libq/src/qapi/qapi-visit-core.c b/libutils/src/q/qapi/qapi-visit-core.c similarity index 100% rename from libq/src/qapi/qapi-visit-core.c rename to libutils/src/q/qapi/qapi-visit-core.c diff --git a/libq/src/qapi/qobject-input-visitor.c b/libutils/src/q/qapi/qobject-input-visitor.c similarity index 100% rename from libq/src/qapi/qobject-input-visitor.c rename to libutils/src/q/qapi/qobject-input-visitor.c diff --git a/libq/src/qapi/qobject-output-visitor.c b/libutils/src/q/qapi/qobject-output-visitor.c similarity index 100% rename from libq/src/qapi/qobject-output-visitor.c rename to libutils/src/q/qapi/qobject-output-visitor.c diff --git a/libq/src/qobject/json-lexer.c b/libutils/src/q/qobject/json-lexer.c similarity index 100% rename from libq/src/qobject/json-lexer.c rename to libutils/src/q/qobject/json-lexer.c diff --git a/libq/src/qobject/json-parser-int.h b/libutils/src/q/qobject/json-parser-int.h similarity index 100% rename from libq/src/qobject/json-parser-int.h rename to libutils/src/q/qobject/json-parser-int.h diff --git a/libq/src/qobject/json-parser.c b/libutils/src/q/qobject/json-parser.c similarity index 100% rename from libq/src/qobject/json-parser.c rename to libutils/src/q/qobject/json-parser.c diff --git a/libq/src/qobject/json-streamer.c b/libutils/src/q/qobject/json-streamer.c similarity index 100% rename from libq/src/qobject/json-streamer.c rename to libutils/src/q/qobject/json-streamer.c diff --git a/libq/src/qobject/json-writer.c b/libutils/src/q/qobject/json-writer.c similarity index 100% rename from libq/src/qobject/json-writer.c rename to libutils/src/q/qobject/json-writer.c diff --git a/libq/src/qobject/qbool.c b/libutils/src/q/qobject/qbool.c similarity index 100% rename from libq/src/qobject/qbool.c rename to libutils/src/q/qobject/qbool.c diff --git a/libq/src/qobject/qdict.c b/libutils/src/q/qobject/qdict.c similarity index 100% rename from libq/src/qobject/qdict.c rename to libutils/src/q/qobject/qdict.c diff --git a/libq/src/qobject/qjson.c b/libutils/src/q/qobject/qjson.c similarity index 100% rename from libq/src/qobject/qjson.c rename to libutils/src/q/qobject/qjson.c diff --git a/libq/src/qobject/qlist.c b/libutils/src/q/qobject/qlist.c similarity index 100% rename from libq/src/qobject/qlist.c rename to libutils/src/q/qobject/qlist.c diff --git a/libq/src/qobject/qlit.c b/libutils/src/q/qobject/qlit.c similarity index 100% rename from libq/src/qobject/qlit.c rename to libutils/src/q/qobject/qlit.c diff --git a/libq/src/qobject/qnull.c b/libutils/src/q/qobject/qnull.c similarity index 100% rename from libq/src/qobject/qnull.c rename to libutils/src/q/qobject/qnull.c diff --git a/libq/src/qobject/qnum.c b/libutils/src/q/qobject/qnum.c similarity index 100% rename from libq/src/qobject/qnum.c rename to libutils/src/q/qobject/qnum.c diff --git a/libq/src/qobject/qobject-internal.h b/libutils/src/q/qobject/qobject-internal.h similarity index 100% rename from libq/src/qobject/qobject-internal.h rename to libutils/src/q/qobject/qobject-internal.h diff --git a/libq/src/qobject/qobject.c b/libutils/src/q/qobject/qobject.c similarity index 100% rename from libq/src/qobject/qobject.c rename to libutils/src/q/qobject/qobject.c diff --git a/libq/src/qobject/qstring.c b/libutils/src/q/qobject/qstring.c similarity index 100% rename from libq/src/qobject/qstring.c rename to libutils/src/q/qobject/qstring.c diff --git a/libq/src/tests/check-qdict.c b/libutils/src/q/tests/check-qdict.c similarity index 100% rename from libq/src/tests/check-qdict.c rename to libutils/src/q/tests/check-qdict.c diff --git a/libq/src/tests/check-qjson.c b/libutils/src/q/tests/check-qjson.c similarity index 100% rename from libq/src/tests/check-qjson.c rename to libutils/src/q/tests/check-qjson.c diff --git a/libq/src/tests/check-qlist.c b/libutils/src/q/tests/check-qlist.c similarity index 100% rename from libq/src/tests/check-qlist.c rename to libutils/src/q/tests/check-qlist.c diff --git a/libq/src/tests/check-qnull.c b/libutils/src/q/tests/check-qnull.c similarity index 100% rename from libq/src/tests/check-qnull.c rename to libutils/src/q/tests/check-qnull.c diff --git a/libq/src/tests/check-qnum.c b/libutils/src/q/tests/check-qnum.c similarity index 100% rename from libq/src/tests/check-qnum.c rename to libutils/src/q/tests/check-qnum.c diff --git a/libq/src/tests/check-qobject.c b/libutils/src/q/tests/check-qobject.c similarity index 100% rename from libq/src/tests/check-qobject.c rename to libutils/src/q/tests/check-qobject.c diff --git a/libq/src/tests/check-qstring.c b/libutils/src/q/tests/check-qstring.c similarity index 100% rename from libq/src/tests/check-qstring.c rename to libutils/src/q/tests/check-qstring.c diff --git a/libq/src/unicode.c b/libutils/src/q/unicode.c similarity index 100% rename from libq/src/unicode.c rename to libutils/src/q/unicode.c diff --git a/libq/src/unicode.h b/libutils/src/q/unicode.h similarity index 100% rename from libq/src/unicode.h rename to libutils/src/q/unicode.h diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 8bd2f8334..334d7e75f 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -56,11 +56,8 @@ message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}") find_package(VMI REQUIRED) message(STATUS "Found VMI ${VMI_PACKAGE_VERSION}") -find_package(FSIGCXX REQUIRED) -message(STATUS "Found fsigc++ ${FSIGCXX_PACKAGE_VERSION}") - -find_package(LIBQ REQUIRED) -message(STATUS "Found libq ${LIBQ_PACKAGE_VERSION}") +find_package(LIBUTILS REQUIRED) +message(STATUS "Found libutils ${LIBUTILS_PACKAGE_VERSION}") if(LIBCPU_SRC_DIR) message(STATUS "libcpu source directory: ${LIBCPU_SRC_DIR}") @@ -91,13 +88,12 @@ include_directories("include" ${LIBCPU_SRC_DIR} ${S2EPLUGINS_SRC_DIR} ${VMI_INCLUDE_DIR} - ${LIBQ_INCLUDE_DIR} - ${FSIGCXX_INCLUDE_DIR} + ${LIBUTILS_INCLUDE_DIR} ${PROTOBUF_INCLUDE_DIRS}) include_directories(SYSTEM ${LLVM_INCLUDE_DIRS}) -link_directories(${VMI_LIBRARY_DIR} ${FSIGCXX_LIBRARY_DIR} ${LIBQ_LIBRARY_DIR}) +link_directories(${VMI_LIBRARY_DIR} ${LIBUTILS_LIBRARY_DIR}) llvm_map_components_to_libnames(LLVM_LIBS core debuginfodwarf From 85b813ebdb33a951f4f7d2edb84819926a7be629 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Tue, 18 Aug 2026 15:12:58 +0000 Subject: [PATCH 02/52] libtcg: added tooling to upgrade from qemu releases libtcg is a de-QEMU-ified fork of TCG that has been reformatted with the S2E clang-format style, so upstream patches never apply directly: every line differs because of reformatting alone. Normalizing the upstream file first, by running it through clang-format with the S2E style, reduces the difference against its libtcg counterpart to the genuine S2E delta. For src/tcg.c that is the difference between a 6800-line diff and a 79-line one, which makes the upgrade an ordinary three-way merge. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- libtcg/scripts/upgrade/.gitignore | 1 + libtcg/scripts/upgrade/BASELINE | 1 + libtcg/scripts/upgrade/README.md | 51 +++++++++++++ libtcg/scripts/upgrade/mapping.tsv | 107 ++++++++++++++++++++++++++ libtcg/scripts/upgrade/merge.sh | 113 ++++++++++++++++++++++++++++ libtcg/scripts/upgrade/normalize.sh | 29 +++++++ 6 files changed, 302 insertions(+) create mode 100644 libtcg/scripts/upgrade/.gitignore create mode 100644 libtcg/scripts/upgrade/BASELINE create mode 100644 libtcg/scripts/upgrade/README.md create mode 100644 libtcg/scripts/upgrade/mapping.tsv create mode 100755 libtcg/scripts/upgrade/merge.sh create mode 100755 libtcg/scripts/upgrade/normalize.sh diff --git a/libtcg/scripts/upgrade/.gitignore b/libtcg/scripts/upgrade/.gitignore new file mode 100644 index 000000000..89f9ac04a --- /dev/null +++ b/libtcg/scripts/upgrade/.gitignore @@ -0,0 +1 @@ +out/ diff --git a/libtcg/scripts/upgrade/BASELINE b/libtcg/scripts/upgrade/BASELINE new file mode 100644 index 000000000..a933a5dd7 --- /dev/null +++ b/libtcg/scripts/upgrade/BASELINE @@ -0,0 +1 @@ +v11.1.0 diff --git a/libtcg/scripts/upgrade/README.md b/libtcg/scripts/upgrade/README.md new file mode 100644 index 000000000..c08edced3 --- /dev/null +++ b/libtcg/scripts/upgrade/README.md @@ -0,0 +1,51 @@ +# Upgrading libtcg to a new QEMU release + +libtcg is a fork of QEMU's TCG that has been de-QEMU-ified (headers moved out of +`qemu/`, `exec/` and `accel/tcg/` into `tcg/utils/`, `tcg/exec/` and +`tcg/accel/`) and reformatted with the S2E `.clang-format` style. A plain +`git cherry-pick` or `patch` against upstream therefore never applies: every +line differs because of reformatting alone. + +The trick that makes upgrades tractable is to *normalize the formatting first*. +Running an upstream file through `clang-format` with the S2E style reduces the +difference against its libtcg counterpart to the genuine S2E delta. For +`src/tcg.c` that is the difference between a 6800-line diff and a 79-line one. + +The upgrade is then an ordinary three-way merge: + + base = clang-formatted upstream file at the OLD tag + theirs = clang-formatted upstream file at the NEW tag + ours = the current libtcg file + + git merge-file ours base theirs + +## Files + +- `mapping.tsv` — libtcg path -> upstream QEMU path, one pair per line, tab + separated. Only files that track upstream are listed; S2E-original files + (`tcg-s2e.c`, `tcg-llvm.cpp`, `tb.h`, `tlb.h`, ...) are deliberately absent. +- `BASELINE` — the QEMU tag `mapping.tsv` paths and the current tree correspond + to. Update it (and any renamed paths in `mapping.tsv`) once an upgrade lands. +- `normalize.sh` — extract one file from a QEMU tag and clang-format it. +- `merge.sh` — normalize every mapped file at both tags and three-way merge. + +## Running an upgrade + + export QEMU_SRC=~/qemu + ./merge.sh v10.2.0 v11.1.0 # writes into ./out, reports conflicts + ./merge.sh v10.2.0 v11.1.0 --apply # same, but writes back into the tree + +`merge.sh` follows upstream renames automatically (via `git diff -M`) and +reports files that were deleted upstream or added since the old tag, both of +which need a human decision. + +Not every libtcg file tracks upstream closely. Several utility files +(`utils/osdep.h`, `utils/cutils.c`, `utils/log.c`, `utils/bitmap.h`) are heavily +reduced S2E-specific subsets, and the `fpu/` tree still sits at QEMU v8.1.0. +These are listed in `mapping.tsv` for reference but normally want a manual look +rather than a mechanical merge. + +## After merging + +Re-run `run-clang-format.sh` from the S2E source root so the tree stays +normalized for the next upgrade. diff --git a/libtcg/scripts/upgrade/mapping.tsv b/libtcg/scripts/upgrade/mapping.tsv new file mode 100644 index 000000000..c2610f244 --- /dev/null +++ b/libtcg/scripts/upgrade/mapping.tsv @@ -0,0 +1,107 @@ +# libtcg path upstream QEMU path, as of the tag recorded in BASELINE. +# +# Only files that track upstream appear here. S2E-original files +# (tcg-s2e.c, tcg-llvm.cpp, tcg/tb.h, tcg/tlb.h, tcg/regs.h, tcg/cpu.h, +# tcg/helper.h, tcg/ops_sse_header.h, utils/cache.h, utils/mutex.h, +# utils/spinlock.h, utils/rounding.h, tcg/qemu-plugin.h) are deliberately +# absent: they have no upstream counterpart to merge from. +# +# --- TCG core ----------------------------------------------------------- +include/tcg/tcg.h include/tcg/tcg.h +include/tcg/tcg-op.h include/tcg/tcg-op.h +include/tcg/tcg-op-mem.h include/tcg/tcg-op-mem.h +include/tcg/tcg-op-common.h include/tcg/tcg-op-common.h +include/tcg/tcg-opc.h include/tcg/tcg-opc.h +include/tcg/tcg-cond.h include/tcg/tcg-cond.h +include/tcg/tcg-mo.h include/tcg/tcg-mo.h +include/tcg/tcg-has.h tcg/tcg-has.h +include/tcg/tcg-internal.h tcg/tcg-internal.h +include/tcg/tcg-ldst.h include/tcg/tcg-ldst.h +include/tcg/tcg-temp-internal.h include/tcg/tcg-temp-internal.h +include/tcg/tcg-gvec-desc.h include/tcg/tcg-gvec-desc.h +include/tcg/tcg-memop.h include/exec/memop.h +include/tcg/tcg-memopidx.h include/exec/memopidx.h +include/tcg/helper-info.h include/tcg/helper-info.h +include/tcg/insn-start-words.h include/tcg/insn-start-words.h +include/tcg/target-reg-bits.h include/tcg/target-reg-bits.h +include/tcg/perf.h include/tcg/perf.h +src/tcg.c tcg/tcg.c +src/tcg-common.c tcg/tcg-common.c +src/tcg-op.c tcg/tcg-op.c +src/tcg-op-ldst.c tcg/tcg-op-ldst.c +src/tcg-op-vec.c tcg/tcg-op-vec.c +src/tcg-op-gvec.c tcg/tcg-op-gvec.c +src/tcg-op-gvec.h include/tcg/tcg-op-gvec.h +src/tcg-op-gvec-common.h include/tcg/tcg-op-gvec-common.h +src/optimize.c tcg/optimize.c +src/region.c tcg/region.c +# --- x86_64 backend ----------------------------------------------------- +include/tcg/x86_64/tcg-target.h tcg/x86_64/tcg-target.h +include/tcg/x86_64/tcg-target-has.h tcg/x86_64/tcg-target-has.h +include/tcg/x86_64/tcg-target-mo.h tcg/x86_64/tcg-target-mo.h +include/tcg/x86_64/tcg-target-opc.h.inc tcg/x86_64/tcg-target-opc.h.inc +src/x86_64/tcg-target.c.inc tcg/x86_64/tcg-target.c.inc +src/x86_64/tcg-target-con-set.h tcg/x86_64/tcg-target-con-set.h +src/x86_64/tcg-target-con-str.h tcg/x86_64/tcg-target-con-str.h +# --- accel/tcg and exec glue -------------------------------------------- +include/tcg/accel/getpc.h include/accel/tcg/getpc.h +include/tcg/accel/tcg-runtime.h accel/tcg/tcg-runtime.h +include/tcg/exec/helper-gen.h include/exec/helper-gen.h +include/tcg/exec/helper-gen.h.inc include/exec/helper-gen.h.inc +include/tcg/exec/helper-gen-common.h include/exec/helper-gen-common.h +include/tcg/exec/helper-head.h.inc include/exec/helper-head.h.inc +include/tcg/exec/helper-info.c.inc include/exec/helper-info.c.inc +include/tcg/exec/helper-proto.h include/exec/helper-proto.h +include/tcg/exec/helper-proto.h.inc include/exec/helper-proto.h.inc +include/tcg/exec/helper-proto-common.h include/exec/helper-proto-common.h +include/tcg/exec/plugin-gen.h include/exec/plugin-gen.h +src/tcg-rt/tcg-runtime.c accel/tcg/tcg-runtime.c +src/tcg-rt/tcg-runtime-gvec.c accel/tcg/tcg-runtime-gvec.c +src/atomic_common.c.inc accel/tcg/atomic_common.c.inc +src/atomic_template.h accel/tcg/atomic_template.h +# --- host support ------------------------------------------------------- +include/tcg/utils/host/x86_64/cpuinfo.h host/include/x86_64/host/cpuinfo.h +include/tcg/utils/host/x86_64/atomic128-ldst.h host/include/x86_64/host/atomic128-ldst.h.inc +include/tcg/utils/host/generic/atomic128-cas.h host/include/generic/host/atomic128-cas.h.inc +include/tcg/utils/host/generic/atomic128-ldst.h host/include/generic/host/atomic128-ldst.h.inc +include/tcg/utils/host/generic/load-extract-al16-al8.h host/include/generic/host/load-extract-al16-al8.h.inc +include/tcg/utils/host/generic/store-insert-al16.h host/include/generic/host/store-insert-al16.h.inc +src/utils/cpuinfo-i386.c util/cpuinfo-i386.c +# --- utilities ---------------------------------------------------------- +# Still at QEMU v8.1.0; upgrade deliberately lags the TCG core. +include/tcg/utils/atomic.h include/qemu/atomic.h +include/tcg/utils/atomic128.h include/qemu/atomic128.h +include/tcg/utils/bitops.h include/qemu/bitops.h +include/tcg/utils/bswap.h include/qemu/bswap.h +include/tcg/utils/cpuid.h include/qemu/cpuid.h +include/tcg/utils/debug-assert.h include/tcg/debug-assert.h +include/tcg/utils/host-utils.h include/qemu/host-utils.h +include/tcg/utils/int128.h include/qemu/int128.h +include/tcg/utils/interval-tree.h include/qemu/interval-tree.h +include/tcg/utils/memalign.h include/qemu/memalign.h +include/tcg/utils/qtree.h include/qemu/qtree.h +include/tcg/utils/units.h include/qemu/units.h +src/utils/host-utils.c util/host-utils.c +src/utils/interval-tree.c util/interval-tree.c +src/utils/memalign.c util/memalign.c +src/utils/qtree.c util/qtree.c +src/elf.h include/elf.h +# Heavily reduced S2E-specific subsets: merge by hand, not mechanically. +include/tcg/utils/bitmap.h include/qemu/bitmap.h +include/tcg/utils/cutils.h include/qemu/cutils.h +include/tcg/utils/log.h include/qemu/log.h +include/tcg/utils/osdep.h include/qemu/osdep.h +src/utils/cutils.c util/cutils.c +src/utils/log.c util/log.c +src/utils/osdep.c util/osdep.c +# --- fpu ---------------------------------------------------------------- +# Still at QEMU v8.1.0. Upgrading softfloat changes float semantics that +# KLEE interprets symbolically via softfloat.bc; treat as a separate task. +include/fpu/softfloat.h include/fpu/softfloat.h +include/fpu/softfloat-types.h include/fpu/softfloat-types.h +include/fpu/softfloat-macros.h include/fpu/softfloat-macros.h +include/fpu/softfloat-helpers.h include/fpu/softfloat-helpers.h +src/fpu/softfloat.c fpu/softfloat.c +src/fpu/softfloat-parts.c.inc fpu/softfloat-parts.c.inc +src/fpu/softfloat-parts-addsub.c.inc fpu/softfloat-parts-addsub.c.inc +src/fpu/softfloat-specialize.c.inc fpu/softfloat-specialize.c.inc diff --git a/libtcg/scripts/upgrade/merge.sh b/libtcg/scripts/upgrade/merge.sh new file mode 100755 index 000000000..9a9f9c041 --- /dev/null +++ b/libtcg/scripts/upgrade/merge.sh @@ -0,0 +1,113 @@ +#!/bin/bash +# +# Three-way merge every upstream-tracking libtcg file from one QEMU tag to +# another. See README.md for the rationale. +# +# Usage: QEMU_SRC=~/qemu ./merge.sh [--apply] +# +set -e + +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +LIBTCG=$(cd "${HERE}/../.." && pwd) +QEMU_SRC=${QEMU_SRC:-${HOME}/qemu} +OUT=${OUT:-${HERE}/out} + +OLD=$1 +NEW=$2 +APPLY=$3 + +if [ -z "${OLD}" ] || [ -z "${NEW}" ]; then + echo "Usage: QEMU_SRC=/path/to/qemu $0 [--apply]" >&2 + exit 1 +fi + +rm -rf "${OUT}" +mkdir -p "${OUT}/base" "${OUT}/new" "${OUT}/merged" + +clean=0 +conflicted=0 + +# mapping.tsv records upstream paths as of the newest release libtcg tracks, so +# a path may need resolving in either direction depending on which end of the +# upgrade we are looking at. +resolve_new_path() { + local path=$1 + if git -C "${QEMU_SRC}" cat-file -e "${NEW}:${path}" 2>/dev/null; then + echo "${path}" + return 0 + fi + git -C "${QEMU_SRC}" diff --diff-filter=R -M --name-status "${OLD}" "${NEW}" | + awk -v old="${path}" -F'\t' '$2 == old { print $3; exit }' +} + +resolve_old_path() { + local path=$1 + if git -C "${QEMU_SRC}" cat-file -e "${OLD}:${path}" 2>/dev/null; then + echo "${path}" + return 0 + fi + git -C "${QEMU_SRC}" diff --diff-filter=R -M --name-status "${OLD}" "${NEW}" | + awk -v new="${path}" -F'\t' '$3 == new { print $2; exit }' +} + +printf '%-56s %9s %9s %s\n' FILE S2E UPSTREAM STATUS + +while IFS=$'\t' read -r lf qf; do + case "${lf}" in '' | '#'*) continue ;; esac + + name=$(basename "${lf}") + mkdir -p "${OUT}/base/$(dirname "${lf}")" "${OUT}/new/$(dirname "${lf}")" \ + "${OUT}/merged/$(dirname "${lf}")" + + oqf=$(resolve_old_path "${qf}") + if [ -z "${oqf}" ]; then + printf '%-56s %9s %9s %s\n' "${lf}" - - "ABSENT-AT-${OLD} (${qf})" + continue + fi + QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${OLD}" "${oqf}" "${name}" > "${OUT}/base/${lf}" + + nqf=$(resolve_new_path "${oqf}") + if [ -z "${nqf}" ]; then + printf '%-56s %9s %9s %s\n' "${lf}" - - "REMOVED-IN-${NEW} (${qf})" + continue + fi + QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${NEW}" "${nqf}" "${name}" > "${OUT}/new/${lf}" + + s2e=$(diff "${OUT}/base/${lf}" "${LIBTCG}/${lf}" | grep -c '^[<>]' || true) + up=$(diff "${OUT}/base/${lf}" "${OUT}/new/${lf}" | grep -c '^[<>]' || true) + + status=ok + [ "${oqf}" != "${nqf}" ] && status="renamed ${oqf} -> ${nqf}" + + cp "${LIBTCG}/${lf}" "${OUT}/merged/${lf}" + if git merge-file -L libtcg -L "qemu ${OLD}" -L "qemu ${NEW}" \ + "${OUT}/merged/${lf}" "${OUT}/base/${lf}" "${OUT}/new/${lf}" > /dev/null 2>&1; then + clean=$((clean + 1)) + else + n=$(grep -c '^<<<<<<<' "${OUT}/merged/${lf}" || true) + status="CONFLICT (${n})" + conflicted=$((conflicted + 1)) + fi + + [ "${up}" = "0" ] && continue + printf '%-56s %9s %9s %s\n' "${lf}" "${s2e}" "${up}" "${status}" +done < "${HERE}/mapping.tsv" + +echo +echo "clean: ${clean} conflicted: ${conflicted} output: ${OUT}/merged" + +# Files that appeared upstream since the old tag may need to be imported by +# hand; there is no way to guess their libtcg name. +echo +echo "Added upstream between ${OLD} and ${NEW} (review for import):" +git -C "${QEMU_SRC}" diff --diff-filter=A --name-only "${OLD}" "${NEW}" -- \ + tcg/ include/tcg/ accel/tcg/ include/accel/ | sed 's/^/ /' + +if [ "${APPLY}" = "--apply" ]; then + echo + echo "Applying merged files into ${LIBTCG}" + (cd "${OUT}/merged" && find . -type f -print0) | + while IFS= read -r -d '' f; do + cp "${OUT}/merged/${f#./}" "${LIBTCG}/${f#./}" + done +fi diff --git a/libtcg/scripts/upgrade/normalize.sh b/libtcg/scripts/upgrade/normalize.sh new file mode 100755 index 000000000..ad51d5248 --- /dev/null +++ b/libtcg/scripts/upgrade/normalize.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# +# Extract one file from a QEMU tag and reformat it with the S2E style, so that +# it can be compared or merged against its libtcg counterpart. +# +# Usage: QEMU_SRC=~/qemu ./normalize.sh v11.1.0 tcg/tcg.c [assumed-filename] +# +set -e + +QEMU_SRC=${QEMU_SRC:-${HOME}/qemu} +CLANG_FORMAT=${CLANG_FORMAT:-clang-format-19} +STYLE_FILE=${STYLE_FILE:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)/.clang-format} + +TAG=$1 +FILE=$2 +NAME=${3:-$(basename "${FILE}")} + +if [ -z "${TAG}" ] || [ -z "${FILE}" ]; then + echo "Usage: QEMU_SRC=/path/to/qemu $0 [assumed-filename]" >&2 + exit 1 +fi + +if [ ! -f "${STYLE_FILE}" ]; then + echo "Cannot find .clang-format at ${STYLE_FILE}" >&2 + exit 1 +fi + +git -C "${QEMU_SRC}" show "${TAG}:${FILE}" | + "${CLANG_FORMAT}" -style="file:${STYLE_FILE}" --assume-filename="${NAME}" From 88749728e3384437b5f079232e8ea372027fe441 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Tue, 18 Aug 2026 15:13:17 +0000 Subject: [PATCH 03/52] libtcg: upgraded to qemu 11.1 Merged the TCG core from qemu v10.2.0 to v11.1.0 using the normalize and three-way merge workflow from scripts/upgrade. The S2E patches are preserved: the per-context qemu_ld_helpers and qemu_st_helpers tables, the CONFIG_SYMBEX_MP se_addend TLB hit path, and tcg_target_force_tb_exit. The dominant upstream change is the removal of 32-bit host support, hence the i386 to x86_64 rename, the now target-independent target-reg-bits.h with TCG_TARGET_REG_BITS unconditionally 64, and the folding of the i386 cpuinfo header into x86_64. Memory operations moved out of tcg-op.h into the new tcg-op-mem.h; the S2E tcg_gen_qemu_ld8u style wrappers stay behind in tcg-op.h. The four sadd/ssub saturate helpers are pulled into host-utils.h because the new tcg-runtime-gvec.c needs them. Two latent bugs are fixed along the way: - tcg-gvec-desc.h was missed by the upgrade to 10.2 and still had the old descriptor encoding, while simd_desc() in tcg-op-gvec.c already wrote the new one. In particular simd_desc() encodes oprsz as 2 to mean "matches maxsz", which the stale simd_oprsz() decoded as 24. - The atomic helpers in atomic_common.c.inc declared their address argument as target_ulong while the DEF_HELPER prototypes say i64. Harmless on x86_64, wrong for the i386 guest. Also removed tcg-pool.c.inc, tcg-ldst.c.inc and tcg-target.opc.h, which were unreferenced leftovers from earlier upgrades. fpu/softfloat and most of utils/ remain at qemu v8.1.0 and are not part of this upgrade. Upgrading softfloat changes float semantics that KLEE interprets symbolically via softfloat.bc, so it wants to be a separate change. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- libtcg/CMakeLists.txt | 2 - libtcg/include/tcg/accel/getpc.h | 2 + libtcg/include/tcg/accel/tcg-runtime.h | 17 - libtcg/include/tcg/helper-info.h | 2 +- libtcg/include/tcg/i386/tcg-target.opc.h | 38 - ...cg-target-reg-bits.h => target-reg-bits.h} | 8 +- libtcg/include/tcg/tcg-gvec-desc.h | 41 +- libtcg/include/tcg/tcg-has.h | 7 +- libtcg/include/tcg/tcg-internal.h | 30 +- libtcg/include/tcg/tcg-memop.h | 4 + libtcg/include/tcg/tcg-op-common.h | 9 + libtcg/include/tcg/tcg-op-mem.h | 124 +++ libtcg/include/tcg/tcg-op.h | 115 +- libtcg/include/tcg/tcg-opc.h | 11 +- libtcg/include/tcg/tcg.h | 40 +- libtcg/include/tcg/utils/host-utils.h | 56 + libtcg/include/tcg/utils/host/i386/cpuinfo.h | 41 - .../include/tcg/utils/host/x86_64/cpuinfo.h | 42 +- libtcg/include/tcg/utils/units.h | 2 +- .../tcg/{i386 => x86_64}/tcg-target-has.h | 7 +- .../tcg/{i386 => x86_64}/tcg-target-mo.h | 0 .../tcg/{i386 => x86_64}/tcg-target-opc.h.inc | 0 .../include/tcg/{i386 => x86_64}/tcg-target.h | 9 - libtcg/src/CMakeLists.txt | 7 +- libtcg/src/atomic_common.c.inc | 28 +- libtcg/src/atomic_template.h | 4 +- libtcg/src/optimize.c | 674 ++++++------ libtcg/src/region.c | 12 - libtcg/src/tcg-ldst.c.inc | 61 -- libtcg/src/tcg-op-gvec.c | 121 +-- libtcg/src/tcg-op-gvec.h | 28 +- libtcg/src/tcg-op-ldst.c | 184 ++-- libtcg/src/tcg-op-vec.c | 14 +- libtcg/src/tcg-op.c | 980 ++++-------------- libtcg/src/tcg-pool.c.inc | 144 --- libtcg/src/tcg-rt/tcg-runtime-gvec.c | 20 +- libtcg/src/tcg-rt/tcg-runtime.c | 12 - libtcg/src/tcg.c | 394 +------ .../src/{i386 => x86_64}/tcg-target-con-set.h | 0 .../src/{i386 => x86_64}/tcg-target-con-str.h | 0 libtcg/src/{i386 => x86_64}/tcg-target.c.inc | 530 ++-------- 41 files changed, 1085 insertions(+), 2735 deletions(-) delete mode 100644 libtcg/include/tcg/i386/tcg-target.opc.h rename libtcg/include/tcg/{i386/tcg-target-reg-bits.h => target-reg-bits.h} (71%) create mode 100644 libtcg/include/tcg/tcg-op-mem.h delete mode 100644 libtcg/include/tcg/utils/host/i386/cpuinfo.h rename libtcg/include/tcg/{i386 => x86_64}/tcg-target-has.h (91%) rename libtcg/include/tcg/{i386 => x86_64}/tcg-target-mo.h (100%) rename libtcg/include/tcg/{i386 => x86_64}/tcg-target-opc.h.inc (100%) rename libtcg/include/tcg/{i386 => x86_64}/tcg-target.h (89%) delete mode 100644 libtcg/src/tcg-ldst.c.inc delete mode 100644 libtcg/src/tcg-pool.c.inc rename libtcg/src/{i386 => x86_64}/tcg-target-con-set.h (100%) rename libtcg/src/{i386 => x86_64}/tcg-target-con-str.h (100%) rename libtcg/src/{i386 => x86_64}/tcg-target.c.inc (88%) diff --git a/libtcg/CMakeLists.txt b/libtcg/CMakeLists.txt index 9a8df8c73..de60e5062 100644 --- a/libtcg/CMakeLists.txt +++ b/libtcg/CMakeLists.txt @@ -73,10 +73,8 @@ message(STATUS "WITH_GUEST: ${WITH_GUEST}") if(WITH_GUEST MATCHES "i386") set(TARGET_LONG_BITS "32") - set(TARGET_INSN_START_EXTRA_WORDS "1") elseif(WITH_GUEST MATCHES "x86_64") set(TARGET_LONG_BITS "64") - set(TARGET_INSN_START_EXTRA_WORDS "1") set(TARGET_X86_64 "1") else() message(FATAL_ERROR "Incorrect target ${WITH_GUEST}") diff --git a/libtcg/include/tcg/accel/getpc.h b/libtcg/include/tcg/accel/getpc.h index 35e9c1c7a..d9f050148 100644 --- a/libtcg/include/tcg/accel/getpc.h +++ b/libtcg/include/tcg/accel/getpc.h @@ -8,6 +8,8 @@ #ifndef ACCEL_TCG_GETPC_H #define ACCEL_TCG_GETPC_H +/* Upstream guards this header on CONFIG_TCG; libtcg is TCG by construction. */ + /* GETPC is the true target of the return instruction that we'll execute. */ #ifdef CONFIG_TCG_INTERPRETER extern __thread uintptr_t tci_tb_ptr; diff --git a/libtcg/include/tcg/accel/tcg-runtime.h b/libtcg/include/tcg/accel/tcg-runtime.h index d53cd1db2..2176c2ac1 100644 --- a/libtcg/include/tcg/accel/tcg-runtime.h +++ b/libtcg/include/tcg/accel/tcg-runtime.h @@ -8,10 +8,6 @@ DEF_HELPER_FLAGS_2(rem_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64) DEF_HELPER_FLAGS_2(divu_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64) DEF_HELPER_FLAGS_2(remu_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64) -DEF_HELPER_FLAGS_2(shl_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64) -DEF_HELPER_FLAGS_2(shr_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64) -DEF_HELPER_FLAGS_2(sar_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64) - DEF_HELPER_FLAGS_2(mulsh_i64, TCG_CALL_NO_RWG_SE, s64, s64, s64) DEF_HELPER_FLAGS_2(muluh_i64, TCG_CALL_NO_RWG_SE, i64, i64, i64) @@ -47,10 +43,8 @@ DEF_HELPER_FLAGS_5(atomic_cmpxchgw_be, TCG_CALL_NO_WG, i32, env, i64, i32, i32, DEF_HELPER_FLAGS_5(atomic_cmpxchgw_le, TCG_CALL_NO_WG, i32, env, i64, i32, i32, i32) DEF_HELPER_FLAGS_5(atomic_cmpxchgl_be, TCG_CALL_NO_WG, i32, env, i64, i32, i32, i32) DEF_HELPER_FLAGS_5(atomic_cmpxchgl_le, TCG_CALL_NO_WG, i32, env, i64, i32, i32, i32) -#ifdef CONFIG_ATOMIC64 DEF_HELPER_FLAGS_5(atomic_cmpxchgq_be, TCG_CALL_NO_WG, i64, env, i64, i64, i64, i32) DEF_HELPER_FLAGS_5(atomic_cmpxchgq_le, TCG_CALL_NO_WG, i64, env, i64, i64, i64, i32) -#endif #if HAVE_CMPXCHG128 DEF_HELPER_FLAGS_5(atomic_cmpxchgo_be, TCG_CALL_NO_WG, i128, env, i64, i128, i128, i32) DEF_HELPER_FLAGS_5(atomic_cmpxchgo_le, TCG_CALL_NO_WG, i128, env, i64, i128, i128, i32) @@ -62,9 +56,6 @@ DEF_HELPER_FLAGS_4(atomic_fetch_oro_be, TCG_CALL_NO_WG, i128, env, i64, i128, i3 DEF_HELPER_FLAGS_4(atomic_fetch_oro_le, TCG_CALL_NO_WG, i128, env, i64, i128, i32) #endif -DEF_HELPER_FLAGS_5(nonatomic_cmpxchgo, TCG_CALL_NO_WG, i128, env, i64, i128, i128, i32) - -#ifdef CONFIG_ATOMIC64 #define GEN_ATOMIC_HELPERS(NAME) \ DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), b), TCG_CALL_NO_WG, i32, env, i64, i32, i32) \ DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), w_le), TCG_CALL_NO_WG, i32, env, i64, i32, i32) \ @@ -73,14 +64,6 @@ DEF_HELPER_FLAGS_5(nonatomic_cmpxchgo, TCG_CALL_NO_WG, i128, env, i64, i128, i12 DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), l_be), TCG_CALL_NO_WG, i32, env, i64, i32, i32) \ DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), q_le), TCG_CALL_NO_WG, i64, env, i64, i64, i32) \ DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), q_be), TCG_CALL_NO_WG, i64, env, i64, i64, i32) -#else -#define GEN_ATOMIC_HELPERS(NAME) \ - DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), b), TCG_CALL_NO_WG, i32, env, i64, i32, i32) \ - DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), w_le), TCG_CALL_NO_WG, i32, env, i64, i32, i32) \ - DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), w_be), TCG_CALL_NO_WG, i32, env, i64, i32, i32) \ - DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), l_le), TCG_CALL_NO_WG, i32, env, i64, i32, i32) \ - DEF_HELPER_FLAGS_4(glue(glue(atomic_, NAME), l_be), TCG_CALL_NO_WG, i32, env, i64, i32, i32) -#endif /* CONFIG_ATOMIC64 */ GEN_ATOMIC_HELPERS(fetch_add) GEN_ATOMIC_HELPERS(fetch_and) diff --git a/libtcg/include/tcg/helper-info.h b/libtcg/include/tcg/helper-info.h index 7016eb875..3bd7aa7a4 100644 --- a/libtcg/include/tcg/helper-info.h +++ b/libtcg/include/tcg/helper-info.h @@ -26,7 +26,7 @@ #include #pragma GCC diagnostic pop #endif -#include "i386/tcg-target-reg-bits.h" +#include #define MAX_CALL_IARGS 7 diff --git a/libtcg/include/tcg/i386/tcg-target.opc.h b/libtcg/include/tcg/i386/tcg-target.opc.h deleted file mode 100644 index b5f403e35..000000000 --- a/libtcg/include/tcg/i386/tcg-target.opc.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2019 Linaro - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * Target-specific opcodes for host vector expansion. These will be - * emitted by tcg_expand_vec_op. For those familiar with GCC internals, - * consider these to be UNSPEC with names. - */ - -DEF(x86_shufps_vec, 1, 2, 1, IMPLVEC) -DEF(x86_vpblendvb_vec, 1, 3, 0, IMPLVEC) -DEF(x86_blend_vec, 1, 2, 1, IMPLVEC) -DEF(x86_packss_vec, 1, 2, 0, IMPLVEC) -DEF(x86_packus_vec, 1, 2, 0, IMPLVEC) -DEF(x86_psrldq_vec, 1, 1, 1, IMPLVEC) -DEF(x86_vperm2i128_vec, 1, 2, 1, IMPLVEC) -DEF(x86_punpckl_vec, 1, 2, 0, IMPLVEC) -DEF(x86_punpckh_vec, 1, 2, 0, IMPLVEC) -DEF(x86_vpshldi_vec, 1, 2, 1, IMPLVEC) -DEF(x86_vpshldv_vec, 1, 3, 0, IMPLVEC) -DEF(x86_vpshrdv_vec, 1, 3, 0, IMPLVEC) diff --git a/libtcg/include/tcg/i386/tcg-target-reg-bits.h b/libtcg/include/tcg/target-reg-bits.h similarity index 71% rename from libtcg/include/tcg/i386/tcg-target-reg-bits.h rename to libtcg/include/tcg/target-reg-bits.h index c48cdf0b8..c0a231528 100644 --- a/libtcg/include/tcg/i386/tcg-target-reg-bits.h +++ b/libtcg/include/tcg/target-reg-bits.h @@ -7,10 +7,10 @@ #ifndef TCG_TARGET_REG_BITS_H #define TCG_TARGET_REG_BITS_H -#ifdef __x86_64__ +/* + * We only support 64-bit hosts now. + * Retain the identifier for documentation. + */ #define TCG_TARGET_REG_BITS 64 -#else -#define TCG_TARGET_REG_BITS 32 -#endif #endif diff --git a/libtcg/include/tcg/tcg-gvec-desc.h b/libtcg/include/tcg/tcg-gvec-desc.h index 6e6da65aa..439690381 100644 --- a/libtcg/include/tcg/tcg-gvec-desc.h +++ b/libtcg/include/tcg/tcg-gvec-desc.h @@ -17,35 +17,48 @@ * License along with this library; if not, see . */ -/* ??? These bit widths are set for ARM SVE, maxing out at 256 byte vectors. */ - #ifndef TCG_GVEC_DEC_H #define TCG_GVEC_DEC_H +#include + #ifdef __cplusplus extern "C" { #endif -#define SIMD_OPRSZ_SHIFT 0 -#define SIMD_OPRSZ_BITS 5 +/* + * This configuration allows MAXSZ to represent 2048 bytes, and + * OPRSZ to match MAXSZ, or represent the smaller values 8, 16, or 32. + * + * Encode this with: + * 0, 1, 3 -> 8, 16, 32 + * 2 -> maxsz + * + * This steals the input that would otherwise map to 24 to match maxsz. + */ +#define SIMD_MAXSZ_SHIFT 0 +#define SIMD_MAXSZ_BITS 8 -#define SIMD_MAXSZ_SHIFT (SIMD_OPRSZ_SHIFT + SIMD_OPRSZ_BITS) -#define SIMD_MAXSZ_BITS 5 +#define SIMD_OPRSZ_SHIFT (SIMD_MAXSZ_SHIFT + SIMD_MAXSZ_BITS) +#define SIMD_OPRSZ_BITS 2 -#define SIMD_DATA_SHIFT (SIMD_MAXSZ_SHIFT + SIMD_MAXSZ_BITS) +#define SIMD_DATA_SHIFT (SIMD_OPRSZ_SHIFT + SIMD_OPRSZ_BITS) #define SIMD_DATA_BITS (32 - SIMD_DATA_SHIFT) /* Create a descriptor from components. */ uint32_t simd_desc(uint32_t oprsz, uint32_t maxsz, int32_t data); -/* Extract the operation size from a descriptor. */ -static inline intptr_t simd_oprsz(uint32_t desc) { - return (extract32(desc, SIMD_OPRSZ_SHIFT, SIMD_OPRSZ_BITS) + 1) * 8; -} - /* Extract the max vector size from a descriptor. */ static inline intptr_t simd_maxsz(uint32_t desc) { - return (extract32(desc, SIMD_MAXSZ_SHIFT, SIMD_MAXSZ_BITS) + 1) * 8; + return extract32(desc, SIMD_MAXSZ_SHIFT, SIMD_MAXSZ_BITS) * 8 + 8; +} + +/* Extract the operation size from a descriptor. */ +static inline intptr_t simd_oprsz(uint32_t desc) { + uint32_t f = extract32(desc, SIMD_OPRSZ_SHIFT, SIMD_OPRSZ_BITS); + intptr_t o = f * 8 + 8; + intptr_t m = simd_maxsz(desc); + return f == 2 ? m : o; } /* Extract the operation-specific data from a descriptor. */ @@ -57,4 +70,4 @@ static inline int32_t simd_data(uint32_t desc) { } #endif -#endif \ No newline at end of file +#endif diff --git a/libtcg/include/tcg/tcg-has.h b/libtcg/include/tcg/tcg-has.h index 37aed6cc3..6a0fa89c1 100644 --- a/libtcg/include/tcg/tcg-has.h +++ b/libtcg/include/tcg/tcg-has.h @@ -7,12 +7,7 @@ #ifndef TCG_HAS_H #define TCG_HAS_H -#include "i386/tcg-target-has.h" - -#if TCG_TARGET_REG_BITS == 32 -/* Turn some undef macros into false macros. */ -#define TCG_TARGET_HAS_extr_i64_i32 0 -#endif +#include "x86_64/tcg-target-has.h" #if !defined(TCG_TARGET_HAS_v64) && !defined(TCG_TARGET_HAS_v128) && !defined(TCG_TARGET_HAS_v256) #define TCG_TARGET_MAYBE_vec 0 diff --git a/libtcg/include/tcg/tcg-internal.h b/libtcg/include/tcg/tcg-internal.h index 03d88a725..8c1f9c7cc 100644 --- a/libtcg/include/tcg/tcg-internal.h +++ b/libtcg/include/tcg/tcg-internal.h @@ -38,6 +38,12 @@ extern TCGContext **tcg_ctxs; extern unsigned int tcg_cur_ctxs; extern unsigned int tcg_max_ctxs; +#ifdef CONFIG_USER_ONLY +#define tcg_use_softmmu false +#else +#define tcg_use_softmmu true +#endif + void tcg_region_init(size_t tb_size, int splitwx, unsigned max_threads); bool tcg_region_alloc(TCGContext *s); void tcg_region_initial_alloc(TCGContext *s); @@ -55,27 +61,12 @@ static inline unsigned tcg_call_flags(TCGOp *op) { return tcg_call_info(op)->flags; } -#if TCG_TARGET_REG_BITS == 32 -static inline TCGv_i32 TCGV_LOW(TCGv_i64 t) { - return temp_tcgv_i32(tcgv_i64_temp(t) + HOST_BIG_ENDIAN); -} -static inline TCGv_i32 TCGV_HIGH(TCGv_i64 t) { - return temp_tcgv_i32(tcgv_i64_temp(t) + !HOST_BIG_ENDIAN); -} -#else -TCGv_i32 TCGV_LOW(TCGv_i64) QEMU_ERROR("32-bit code path is reachable"); -TCGv_i32 TCGV_HIGH(TCGv_i64) QEMU_ERROR("32-bit code path is reachable"); -#endif - static inline TCGv_i64 TCGV128_LOW(TCGv_i128 t) { - /* For 32-bit, offset by 2, which may then have TCGV_{LOW,HIGH} applied. */ - int o = HOST_BIG_ENDIAN ? 64 / TCG_TARGET_REG_BITS : 0; - return temp_tcgv_i64(tcgv_i128_temp(t) + o); + return temp_tcgv_i64(tcgv_i128_temp(t) + HOST_BIG_ENDIAN); } static inline TCGv_i64 TCGV128_HIGH(TCGv_i128 t) { - int o = HOST_BIG_ENDIAN ? 0 : 64 / TCG_TARGET_REG_BITS; - return temp_tcgv_i64(tcgv_i128_temp(t) + o); + return temp_tcgv_i64(tcgv_i128_temp(t) + !HOST_BIG_ENDIAN); } bool tcg_target_has_memory_bswap(MemOp memop); @@ -104,6 +95,11 @@ void vec_gen_6(TCGOpcode opc, TCGType type, unsigned vece, TCGArg r, TCGArg a, T TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *op, TCGOpcode, TCGType, unsigned nargs); TCGOp *tcg_op_insert_after(TCGContext *s, TCGOp *op, TCGOpcode, TCGType, unsigned nargs); +/* + * For a binary opcode OP, return true if the second input operand allows IMM. + */ +bool tcg_op_imm_match(TCGOpcode op, TCGType type, tcg_target_ulong imm); + #ifdef __cplusplus } #endif diff --git a/libtcg/include/tcg/tcg-memop.h b/libtcg/include/tcg/tcg-memop.h index bf2d8ef37..0d9c7aca4 100644 --- a/libtcg/include/tcg/tcg-memop.h +++ b/libtcg/include/tcg/tcg-memop.h @@ -40,11 +40,13 @@ typedef enum MemOp { MO_BE = MO_BSWAP, #endif #ifdef COMPILING_PER_TARGET +#ifndef TARGET_NOT_USING_LEGACY_NATIVE_ENDIAN_API #if TARGET_BIG_ENDIAN MO_TE = MO_BE, #else MO_TE = MO_LE, #endif +#endif #endif /* @@ -154,6 +156,7 @@ typedef enum MemOp { MO_BESQ = MO_BE | MO_SQ, #ifdef COMPILING_PER_TARGET +#ifndef TARGET_NOT_USING_LEGACY_NATIVE_ENDIAN_API MO_TEUW = MO_TE | MO_UW, MO_TEUL = MO_TE | MO_UL, MO_TEUQ = MO_TE | MO_UQ, @@ -161,6 +164,7 @@ typedef enum MemOp { MO_TESW = MO_TE | MO_SW, MO_TESL = MO_TE | MO_SL, MO_TESQ = MO_TE | MO_SQ, +#endif #endif MO_SSIZE = MO_SIZE | MO_SIGN, diff --git a/libtcg/include/tcg/tcg-op-common.h b/libtcg/include/tcg/tcg-op-common.h index 514f0d8c6..a97efc185 100644 --- a/libtcg/include/tcg/tcg-op-common.h +++ b/libtcg/include/tcg/tcg-op-common.h @@ -22,6 +22,8 @@ TCGv_vaddr tcg_constant_vaddr(uintptr_t val); TCGv_vec tcg_constant_vec(TCGType type, unsigned vece, int64_t val); TCGv_vec tcg_constant_vec_matching(TCGv_vec match, unsigned vece, int64_t val); +TCGv_i128 tcg_zero_i128(void); + TCGv_i32 tcg_temp_new_i32(void); TCGv_i64 tcg_temp_new_i64(void); TCGv_ptr tcg_temp_new_ptr(void); @@ -34,6 +36,12 @@ TCGv_i64 tcg_global_mem_new_i64(TCGv_ptr reg, intptr_t off, const char *name); TCGv_ptr tcg_global_mem_new_ptr(TCGv_ptr reg, intptr_t off, const char *name); /* Generic ops. */ +static inline void tcg_gen_insn_start(uint64_t pc, uint64_t a1, uint64_t a2) { + TCGOp *op = tcg_emit_op(INDEX_op_insn_start, INSN_START_WORDS); + tcg_set_insn_start_param(op, 0, pc); + tcg_set_insn_start_param(op, 1, a1); + tcg_set_insn_start_param(op, 2, a2); +} void gen_set_label(TCGLabel *l); void tcg_gen_br(TCGLabel *l); @@ -221,6 +229,7 @@ void tcg_gen_movcond_i64(TCGCond cond, TCGv_i64 ret, TCGv_i64 c1, TCGv_i64 c2, T void tcg_gen_add2_i64(TCGv_i64 rl, TCGv_i64 rh, TCGv_i64 al, TCGv_i64 ah, TCGv_i64 bl, TCGv_i64 bh); void tcg_gen_sub2_i64(TCGv_i64 rl, TCGv_i64 rh, TCGv_i64 al, TCGv_i64 ah, TCGv_i64 bl, TCGv_i64 bh); void tcg_gen_addcio_i64(TCGv_i64 r, TCGv_i64 co, TCGv_i64 a, TCGv_i64 b, TCGv_i64 ci); +void tcg_gen_addN_i64(int n, TCGv_i64 *r, TCGv_i64 *a, TCGv_i64 *b); void tcg_gen_mulu2_i64(TCGv_i64 rl, TCGv_i64 rh, TCGv_i64 arg1, TCGv_i64 arg2); void tcg_gen_muls2_i64(TCGv_i64 rl, TCGv_i64 rh, TCGv_i64 arg1, TCGv_i64 arg2); void tcg_gen_mulsu2_i64(TCGv_i64 rl, TCGv_i64 rh, TCGv_i64 arg1, TCGv_i64 arg2); diff --git a/libtcg/include/tcg/tcg-op-mem.h b/libtcg/include/tcg/tcg-op-mem.h new file mode 100644 index 000000000..9c5ae05d3 --- /dev/null +++ b/libtcg/include/tcg/tcg-op-mem.h @@ -0,0 +1,124 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Target dependent memory related functions. + * + * Copyright (c) 2008 Fabrice Bellard + */ + +#ifndef TCG_TCG_OP_MEM_H +#define TCG_TCG_OP_MEM_H + +#ifndef TCG_ADDRESS_BITS +#error TCG_ADDRESS_BITS must be defined +#endif + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if TCG_ADDRESS_BITS == 32 +typedef TCGv_i32 TCGv_va; +#define TCG_TYPE_VA TCG_TYPE_I32 +#define tcgv_va_temp tcgv_i32_temp +#define tcgv_va_temp_new tcg_temp_new_i32 +#elif TCG_ADDRESS_BITS == 64 +typedef TCGv_i64 TCGv_va; +#define TCG_TYPE_VA TCG_TYPE_I64 +#define tcgv_va_temp tcgv_i64_temp +#define tcgv_va_temp_new tcg_temp_new_i64 +#else +#error +#endif + +static inline void tcg_gen_qemu_ld_i32(TCGv_i32 v, TCGv_va a, TCGArg i, MemOp m) { + tcg_gen_qemu_ld_i32_chk(v, tcgv_va_temp(a), i, m, TCG_TYPE_VA); +} + +static inline void tcg_gen_qemu_st_i32(TCGv_i32 v, TCGv_va a, TCGArg i, MemOp m) { + tcg_gen_qemu_st_i32_chk(v, tcgv_va_temp(a), i, m, TCG_TYPE_VA); +} + +static inline void tcg_gen_qemu_ld_i64(TCGv_i64 v, TCGv_va a, TCGArg i, MemOp m) { + tcg_gen_qemu_ld_i64_chk(v, tcgv_va_temp(a), i, m, TCG_TYPE_VA); +} + +static inline void tcg_gen_qemu_st_i64(TCGv_i64 v, TCGv_va a, TCGArg i, MemOp m) { + tcg_gen_qemu_st_i64_chk(v, tcgv_va_temp(a), i, m, TCG_TYPE_VA); +} + +static inline void tcg_gen_qemu_ld_i128(TCGv_i128 v, TCGv_va a, TCGArg i, MemOp m) { + tcg_gen_qemu_ld_i128_chk(v, tcgv_va_temp(a), i, m, TCG_TYPE_VA); +} + +static inline void tcg_gen_qemu_st_i128(TCGv_i128 v, TCGv_va a, TCGArg i, MemOp m) { + tcg_gen_qemu_st_i128_chk(v, tcgv_va_temp(a), i, m, TCG_TYPE_VA); +} + +#define DEF_ATOMIC2(N, S) \ + static inline void N##_##S(TCGv_##S r, TCGv_va a, TCGv_##S v, TCGArg i, MemOp m) { \ + N##_##S##_chk(r, tcgv_va_temp(a), v, i, m, TCG_TYPE_VA); \ + } + +#define DEF_ATOMIC3(N, S) \ + static inline void N##_##S(TCGv_##S r, TCGv_va a, TCGv_##S o, TCGv_##S n, TCGArg i, MemOp m) { \ + N##_##S##_chk(r, tcgv_va_temp(a), o, n, i, m, TCG_TYPE_VA); \ + } + +DEF_ATOMIC3(tcg_gen_atomic_cmpxchg, i32) +DEF_ATOMIC3(tcg_gen_atomic_cmpxchg, i64) +DEF_ATOMIC3(tcg_gen_atomic_cmpxchg, i128) + +DEF_ATOMIC3(tcg_gen_nonatomic_cmpxchg, i32) +DEF_ATOMIC3(tcg_gen_nonatomic_cmpxchg, i64) +DEF_ATOMIC3(tcg_gen_nonatomic_cmpxchg, i128) + +DEF_ATOMIC2(tcg_gen_atomic_xchg, i32) +DEF_ATOMIC2(tcg_gen_atomic_xchg, i64) +DEF_ATOMIC2(tcg_gen_atomic_xchg, i128) + +DEF_ATOMIC2(tcg_gen_atomic_fetch_add, i32) +DEF_ATOMIC2(tcg_gen_atomic_fetch_add, i64) +DEF_ATOMIC2(tcg_gen_atomic_fetch_and, i32) +DEF_ATOMIC2(tcg_gen_atomic_fetch_and, i64) +DEF_ATOMIC2(tcg_gen_atomic_fetch_and, i128) +DEF_ATOMIC2(tcg_gen_atomic_fetch_or, i32) +DEF_ATOMIC2(tcg_gen_atomic_fetch_or, i64) +DEF_ATOMIC2(tcg_gen_atomic_fetch_or, i128) +DEF_ATOMIC2(tcg_gen_atomic_fetch_xor, i32) +DEF_ATOMIC2(tcg_gen_atomic_fetch_xor, i64) +DEF_ATOMIC2(tcg_gen_atomic_fetch_smin, i32) +DEF_ATOMIC2(tcg_gen_atomic_fetch_smin, i64) +DEF_ATOMIC2(tcg_gen_atomic_fetch_umin, i32) +DEF_ATOMIC2(tcg_gen_atomic_fetch_umin, i64) +DEF_ATOMIC2(tcg_gen_atomic_fetch_smax, i32) +DEF_ATOMIC2(tcg_gen_atomic_fetch_smax, i64) +DEF_ATOMIC2(tcg_gen_atomic_fetch_umax, i32) +DEF_ATOMIC2(tcg_gen_atomic_fetch_umax, i64) + +DEF_ATOMIC2(tcg_gen_atomic_add_fetch, i32) +DEF_ATOMIC2(tcg_gen_atomic_add_fetch, i64) +DEF_ATOMIC2(tcg_gen_atomic_and_fetch, i32) +DEF_ATOMIC2(tcg_gen_atomic_and_fetch, i64) +DEF_ATOMIC2(tcg_gen_atomic_or_fetch, i32) +DEF_ATOMIC2(tcg_gen_atomic_or_fetch, i64) +DEF_ATOMIC2(tcg_gen_atomic_xor_fetch, i32) +DEF_ATOMIC2(tcg_gen_atomic_xor_fetch, i64) +DEF_ATOMIC2(tcg_gen_atomic_smin_fetch, i32) +DEF_ATOMIC2(tcg_gen_atomic_smin_fetch, i64) +DEF_ATOMIC2(tcg_gen_atomic_umin_fetch, i32) +DEF_ATOMIC2(tcg_gen_atomic_umin_fetch, i64) +DEF_ATOMIC2(tcg_gen_atomic_smax_fetch, i32) +DEF_ATOMIC2(tcg_gen_atomic_smax_fetch, i64) +DEF_ATOMIC2(tcg_gen_atomic_umax_fetch, i32) +DEF_ATOMIC2(tcg_gen_atomic_umax_fetch, i64) + +#undef DEF_ATOMIC2 +#undef DEF_ATOMIC3 + +#ifdef __cplusplus +} +#endif + +#endif /* TCG_TCG_OP_MEM_H */ diff --git a/libtcg/include/tcg/tcg-op.h b/libtcg/include/tcg/tcg-op.h index c1bc187af..aad79fff9 100644 --- a/libtcg/include/tcg/tcg-op.h +++ b/libtcg/include/tcg/tcg-op.h @@ -8,12 +8,15 @@ #ifndef TCG_TCG_OP_H #define TCG_TCG_OP_H -#include "tcg/tcg-op-common.h" +#include #ifndef TARGET_LONG_BITS #error must include QEMU headers #endif +#define TCG_ADDRESS_BITS TARGET_LONG_BITS +#include + #if TARGET_LONG_BITS == 32 #define TCG_TYPE_TL TCG_TYPE_I32 #elif TARGET_LONG_BITS == 64 @@ -30,31 +33,6 @@ extern "C" { #error Mismatch with insn-start-words.h #endif -#if TARGET_INSN_START_EXTRA_WORDS == 0 -static inline void tcg_gen_insn_start(target_ulong pc) { - TCGOp *op = tcg_emit_op(INDEX_op_insn_start, INSN_START_WORDS * 64 / TCG_TARGET_REG_BITS); - tcg_set_insn_start_param(op, 0, pc); - tcg_set_insn_start_param(op, 1, 0); - tcg_set_insn_start_param(op, 2, 0); -} -#elif TARGET_INSN_START_EXTRA_WORDS == 1 -static inline void tcg_gen_insn_start(target_ulong pc, target_ulong a1) { - TCGOp *op = tcg_emit_op(INDEX_op_insn_start, INSN_START_WORDS * 64 / TCG_TARGET_REG_BITS); - tcg_set_insn_start_param(op, 0, pc); - tcg_set_insn_start_param(op, 1, a1); - tcg_set_insn_start_param(op, 2, 0); -} -#elif TARGET_INSN_START_EXTRA_WORDS == 2 -static inline void tcg_gen_insn_start(target_ulong pc, target_ulong a1, target_ulong a2) { - TCGOp *op = tcg_emit_op(INDEX_op_insn_start, INSN_START_WORDS * 64 / TCG_TARGET_REG_BITS); - tcg_set_insn_start_param(op, 0, pc); - tcg_set_insn_start_param(op, 1, a1); - tcg_set_insn_start_param(op, 2, a2); -} -#else -#error Unhandled TARGET_INSN_START_EXTRA_WORDS value -#endif - #if TARGET_LONG_BITS == 32 typedef TCGv_i32 TCGv; #define tcg_temp_new() tcg_temp_new_i32() @@ -73,30 +51,6 @@ typedef TCGv_i64 TCGv; #error Unhandled TARGET_LONG_BITS value #endif -static inline void tcg_gen_qemu_ld_i32(TCGv_i32 v, TCGv a, TCGArg i, MemOp m) { - tcg_gen_qemu_ld_i32_chk(v, tcgv_tl_temp(a), i, m, TCG_TYPE_TL); -} - -static inline void tcg_gen_qemu_st_i32(TCGv_i32 v, TCGv a, TCGArg i, MemOp m) { - tcg_gen_qemu_st_i32_chk(v, tcgv_tl_temp(a), i, m, TCG_TYPE_TL); -} - -static inline void tcg_gen_qemu_ld_i64(TCGv_i64 v, TCGv a, TCGArg i, MemOp m) { - tcg_gen_qemu_ld_i64_chk(v, tcgv_tl_temp(a), i, m, TCG_TYPE_TL); -} - -static inline void tcg_gen_qemu_st_i64(TCGv_i64 v, TCGv a, TCGArg i, MemOp m) { - tcg_gen_qemu_st_i64_chk(v, tcgv_tl_temp(a), i, m, TCG_TYPE_TL); -} - -static inline void tcg_gen_qemu_ld_i128(TCGv_i128 v, TCGv a, TCGArg i, MemOp m) { - tcg_gen_qemu_ld_i128_chk(v, tcgv_tl_temp(a), i, m, TCG_TYPE_TL); -} - -static inline void tcg_gen_qemu_st_i128(TCGv_i128 v, TCGv a, TCGArg i, MemOp m) { - tcg_gen_qemu_st_i128_chk(v, tcgv_tl_temp(a), i, m, TCG_TYPE_TL); -} - static inline void tcg_gen_qemu_ld8u(TCGv ret, TCGv addr, int mem_index) { tcg_gen_qemu_ld_tl(ret, addr, mem_index, MO_UB); } @@ -141,67 +95,6 @@ static inline void tcg_gen_qemu_st64(TCGv_i64 arg, TCGv addr, int mem_index) { tcg_gen_qemu_st_i64(arg, addr, mem_index, MO_TEUQ); } -#define DEF_ATOMIC2(N, S) \ - static inline void N##_##S(TCGv_##S r, TCGv a, TCGv_##S v, TCGArg i, MemOp m) { \ - N##_##S##_chk(r, tcgv_tl_temp(a), v, i, m, TCG_TYPE_TL); \ - } - -#define DEF_ATOMIC3(N, S) \ - static inline void N##_##S(TCGv_##S r, TCGv a, TCGv_##S o, TCGv_##S n, TCGArg i, MemOp m) { \ - N##_##S##_chk(r, tcgv_tl_temp(a), o, n, i, m, TCG_TYPE_TL); \ - } - -DEF_ATOMIC3(tcg_gen_atomic_cmpxchg, i32) -DEF_ATOMIC3(tcg_gen_atomic_cmpxchg, i64) -DEF_ATOMIC3(tcg_gen_atomic_cmpxchg, i128) - -DEF_ATOMIC3(tcg_gen_nonatomic_cmpxchg, i32) -DEF_ATOMIC3(tcg_gen_nonatomic_cmpxchg, i64) -DEF_ATOMIC3(tcg_gen_nonatomic_cmpxchg, i128) - -DEF_ATOMIC2(tcg_gen_atomic_xchg, i32) -DEF_ATOMIC2(tcg_gen_atomic_xchg, i64) -DEF_ATOMIC2(tcg_gen_atomic_xchg, i128) - -DEF_ATOMIC2(tcg_gen_atomic_fetch_add, i32) -DEF_ATOMIC2(tcg_gen_atomic_fetch_add, i64) -DEF_ATOMIC2(tcg_gen_atomic_fetch_and, i32) -DEF_ATOMIC2(tcg_gen_atomic_fetch_and, i64) -DEF_ATOMIC2(tcg_gen_atomic_fetch_and, i128) -DEF_ATOMIC2(tcg_gen_atomic_fetch_or, i32) -DEF_ATOMIC2(tcg_gen_atomic_fetch_or, i64) -DEF_ATOMIC2(tcg_gen_atomic_fetch_or, i128) -DEF_ATOMIC2(tcg_gen_atomic_fetch_xor, i32) -DEF_ATOMIC2(tcg_gen_atomic_fetch_xor, i64) -DEF_ATOMIC2(tcg_gen_atomic_fetch_smin, i32) -DEF_ATOMIC2(tcg_gen_atomic_fetch_smin, i64) -DEF_ATOMIC2(tcg_gen_atomic_fetch_umin, i32) -DEF_ATOMIC2(tcg_gen_atomic_fetch_umin, i64) -DEF_ATOMIC2(tcg_gen_atomic_fetch_smax, i32) -DEF_ATOMIC2(tcg_gen_atomic_fetch_smax, i64) -DEF_ATOMIC2(tcg_gen_atomic_fetch_umax, i32) -DEF_ATOMIC2(tcg_gen_atomic_fetch_umax, i64) - -DEF_ATOMIC2(tcg_gen_atomic_add_fetch, i32) -DEF_ATOMIC2(tcg_gen_atomic_add_fetch, i64) -DEF_ATOMIC2(tcg_gen_atomic_and_fetch, i32) -DEF_ATOMIC2(tcg_gen_atomic_and_fetch, i64) -DEF_ATOMIC2(tcg_gen_atomic_or_fetch, i32) -DEF_ATOMIC2(tcg_gen_atomic_or_fetch, i64) -DEF_ATOMIC2(tcg_gen_atomic_xor_fetch, i32) -DEF_ATOMIC2(tcg_gen_atomic_xor_fetch, i64) -DEF_ATOMIC2(tcg_gen_atomic_smin_fetch, i32) -DEF_ATOMIC2(tcg_gen_atomic_smin_fetch, i64) -DEF_ATOMIC2(tcg_gen_atomic_umin_fetch, i32) -DEF_ATOMIC2(tcg_gen_atomic_umin_fetch, i64) -DEF_ATOMIC2(tcg_gen_atomic_smax_fetch, i32) -DEF_ATOMIC2(tcg_gen_atomic_smax_fetch, i64) -DEF_ATOMIC2(tcg_gen_atomic_umax_fetch, i32) -DEF_ATOMIC2(tcg_gen_atomic_umax_fetch, i64) - -#undef DEF_ATOMIC2 -#undef DEF_ATOMIC3 - #if TARGET_LONG_BITS == 64 #define tcg_gen_movi_tl tcg_gen_movi_i64 #define tcg_gen_mov_tl tcg_gen_mov_i64 diff --git a/libtcg/include/tcg/tcg-opc.h b/libtcg/include/tcg/tcg-opc.h index e7589ceb6..a7d747377 100644 --- a/libtcg/include/tcg/tcg-opc.h +++ b/libtcg/include/tcg/tcg-opc.h @@ -103,18 +103,13 @@ DEF(subb1o, 1, 2, 0, TCG_OPF_INT | TCG_OPF_CARRY_OUT) DEF(subbi, 1, 2, 0, TCG_OPF_INT | TCG_OPF_CARRY_IN) DEF(subbio, 1, 2, 0, TCG_OPF_INT | TCG_OPF_CARRY_IN | TCG_OPF_CARRY_OUT) -DEF(brcond2_i32, 0, 4, 2, TCG_OPF_BB_END | TCG_OPF_COND_BRANCH) -DEF(setcond2_i32, 1, 4, 1, 0) - /* size changing ops */ DEF(ext_i32_i64, 1, 1, 0, 0) DEF(extu_i32_i64, 1, 1, 0, 0) DEF(extrl_i64_i32, 1, 1, 0, 0) DEF(extrh_i64_i32, 1, 1, 0, 0) -#define DATA64_ARGS (TCG_TARGET_REG_BITS == 64 ? 1 : 2) - -DEF(insn_start, 0, 0, DATA64_ARGS *INSN_START_WORDS, TCG_OPF_NOT_PRESENT) +DEF(insn_start, 0, 0, INSN_START_WORDS, TCG_OPF_NOT_PRESENT) DEF(exit_tb, 0, 0, 1, TCG_OPF_BB_EXIT | TCG_OPF_BB_END | TCG_OPF_NOT_PRESENT) DEF(goto_tb, 0, 0, 1, TCG_OPF_BB_EXIT | TCG_OPF_BB_END | TCG_OPF_NOT_PRESENT) @@ -133,7 +128,6 @@ DEF(qemu_st2, 0, 3, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT DEF(mov_vec, 1, 1, 0, TCG_OPF_VECTOR | TCG_OPF_NOT_PRESENT) DEF(dup_vec, 1, 1, 0, TCG_OPF_VECTOR) -DEF(dup2_vec, 1, 2, 0, TCG_OPF_VECTOR) DEF(ld_vec, 1, 1, 1, TCG_OPF_VECTOR) DEF(st_vec, 0, 2, 1, TCG_OPF_VECTOR) @@ -186,7 +180,6 @@ DEF(cmpsel_vec, 1, 4, 1, TCG_OPF_VECTOR) DEF(last_generic, 0, 0, 0, TCG_OPF_NOT_PRESENT) -#include "i386/tcg-target-opc.h.inc" +#include "x86_64/tcg-target-opc.h.inc" -#undef DATA64_ARGS #undef DEF diff --git a/libtcg/include/tcg/tcg.h b/libtcg/include/tcg/tcg.h index 3e7a112fd..c5088e7b6 100644 --- a/libtcg/include/tcg/tcg.h +++ b/libtcg/include/tcg/tcg.h @@ -50,10 +50,10 @@ extern "C" { #include #include -#include -#include #include +#include #include +#include #include "tcg-mo.h" #define TARGET_PAGE_BITS 12 @@ -142,19 +142,10 @@ static inline bool qemu_log_in_addr_range(uint64_t addr) { #define CPU_TEMP_BUF_NLONGS 128 #define TCG_STATIC_FRAME_SIZE (CPU_TEMP_BUF_NLONGS * sizeof(long)) -#if TCG_TARGET_REG_BITS == 32 -typedef int32_t tcg_target_long; -typedef uint32_t tcg_target_ulong; -#define TCG_PRIlx PRIx32 -#define TCG_PRIld PRId32 -#elif TCG_TARGET_REG_BITS == 64 typedef int64_t tcg_target_long; typedef uint64_t tcg_target_ulong; #define TCG_PRIlx PRIx64 #define TCG_PRIld PRId64 -#else -#error unsupported -#endif #if TCG_TARGET_NB_REGS <= 32 typedef uint32_t TCGRegSet; @@ -245,12 +236,8 @@ typedef enum TCGType { /* Number of different types (integer not enum) */ #define TCG_TYPE_COUNT (TCG_TYPE_V256 + 1) -/* An alias for the size of the host register. */ -#if TCG_TARGET_REG_BITS == 32 - TCG_TYPE_REG = TCG_TYPE_I32, -#else + /* An alias for the size of the host register. */ TCG_TYPE_REG = TCG_TYPE_I64, -#endif /* An alias for the size of the native pointer. */ #if UINTPTR_MAX == UINT32_MAX @@ -607,15 +594,9 @@ static inline bool temp_readonly(TCGTemp *ts) { return ts->kind >= TEMP_FIXED; } -#ifdef CONFIG_USER_ONLY -extern bool tcg_use_softmmu; -#else -#define tcg_use_softmmu true -#endif - extern __thread TCGContext *tcg_ctx; extern const void *tcg_code_gen_epilogue; -extern uintptr_t tcg_splitwx_diff; +extern ptrdiff_t tcg_splitwx_diff; extern TCGv_env tcg_env; bool in_code_gen_buffer(const void *p); @@ -730,21 +711,12 @@ static inline void tcg_set_insn_param(TCGOp *op, unsigned arg, TCGArg v) { static inline uint64_t tcg_get_insn_start_param(TCGOp *op, unsigned arg) { tcg_debug_assert(arg < INSN_START_WORDS); - if (TCG_TARGET_REG_BITS == 64) { - return tcg_get_insn_param(op, arg); - } else { - return deposit64(tcg_get_insn_param(op, arg * 2), 32, 32, tcg_get_insn_param(op, arg * 2 + 1)); - } + return tcg_get_insn_param(op, arg); } static inline void tcg_set_insn_start_param(TCGOp *op, unsigned arg, uint64_t v) { tcg_debug_assert(arg < INSN_START_WORDS); - if (TCG_TARGET_REG_BITS == 64) { - tcg_set_insn_param(op, arg, v); - } else { - tcg_set_insn_param(op, arg * 2, v); - tcg_set_insn_param(op, arg * 2 + 1, v >> 32); - } + tcg_set_insn_param(op, arg, v); } /* The last op that was emitted. */ diff --git a/libtcg/include/tcg/utils/host-utils.h b/libtcg/include/tcg/utils/host-utils.h index 2ef05b6b3..a3f0a5e7e 100644 --- a/libtcg/include/tcg/utils/host-utils.h +++ b/libtcg/include/tcg/utils/host-utils.h @@ -525,6 +525,62 @@ static inline bool umul64_overflow(uint64_t x, uint64_t y, uint64_t *ret) { return __builtin_mul_overflow(x, y, ret); } +/** + * sadd32_saturate - addition with saturation + * @x, @y: addends + * + * Computes @x + @y, and saturates rathern than truncating the result. + */ +static inline int32_t sadd32_saturate(int32_t x, int32_t y) { + int32_t ret; + if (sadd32_overflow(x, y, &ret)) { + ret = y < 0 ? INT32_MIN : INT32_MAX; + } + return ret; +} + +/** + * sadd64_saturate - addition with saturation + * @x, @y: addends + * + * Computes @x + @y, and saturates rathern than truncating the result. + */ +static inline int64_t sadd64_saturate(int64_t x, int64_t y) { + int64_t ret; + if (sadd64_overflow(x, y, &ret)) { + ret = y < 0 ? INT64_MIN : INT64_MAX; + } + return ret; +} + +/** + * ssub32_saturate - subtraction with saturation + * @x, @y: addends + * + * Computes @x + @y, and saturates rathern than truncating the result. + */ +static inline bool ssub32_saturate(int32_t x, int32_t y) { + int32_t ret; + if (ssub32_overflow(x, y, &ret)) { + ret = x < 0 ? INT32_MAX : INT32_MIN; + } + return ret; +} + +/** + * ssub64_saturate - subtraction with saturation + * @x, @y: addends + * + * Computes @x + @y, and saturates rathern than truncating the result. + */ +static inline bool ssub64_saturate(int64_t x, int64_t y) { + int64_t ret; + if (ssub64_overflow(x, y, &ret)) { + ret = x < 0 ? INT64_MAX : INT64_MIN; + } + return ret; +} + /* * Unsigned 128x64 multiplication. * Returns true if the result got truncated to 128 bits. diff --git a/libtcg/include/tcg/utils/host/i386/cpuinfo.h b/libtcg/include/tcg/utils/host/i386/cpuinfo.h deleted file mode 100644 index 27e2867f2..000000000 --- a/libtcg/include/tcg/utils/host/i386/cpuinfo.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SPDX-License-Identifier: GPL-2.0-or-later - * Host specific cpu identification for x86. - */ - -#ifndef HOST_CPUINFO_H -#define HOST_CPUINFO_H - -/* Digested version of */ - -#define CPUINFO_ALWAYS (1u << 0) /* so cpuinfo is nonzero */ -#define CPUINFO_OSXSAVE (1u << 1) -#define CPUINFO_MOVBE (1u << 2) -#define CPUINFO_LZCNT (1u << 3) -#define CPUINFO_POPCNT (1u << 4) -#define CPUINFO_BMI1 (1u << 5) -#define CPUINFO_BMI2 (1u << 6) -#define CPUINFO_SSE2 (1u << 7) -#define CPUINFO_AVX1 (1u << 9) -#define CPUINFO_AVX2 (1u << 10) -#define CPUINFO_AVX512F (1u << 11) -#define CPUINFO_AVX512VL (1u << 12) -#define CPUINFO_AVX512BW (1u << 13) -#define CPUINFO_AVX512DQ (1u << 14) -#define CPUINFO_AVX512VBMI2 (1u << 15) -#define CPUINFO_ATOMIC_VMOVDQA (1u << 16) -#define CPUINFO_ATOMIC_VMOVDQU (1u << 17) -#define CPUINFO_AES (1u << 18) -#define CPUINFO_PCLMUL (1u << 19) -#define CPUINFO_GFNI (1u << 20) - -/* Initialized with a constructor. */ -extern unsigned cpuinfo; - -/* - * We cannot rely on constructor ordering, so other constructors must - * use the function interface rather than the variable above. - */ -unsigned cpuinfo_init(void); - -#endif /* HOST_CPUINFO_H */ diff --git a/libtcg/include/tcg/utils/host/x86_64/cpuinfo.h b/libtcg/include/tcg/utils/host/x86_64/cpuinfo.h index d8a760a63..27e2867f2 100644 --- a/libtcg/include/tcg/utils/host/x86_64/cpuinfo.h +++ b/libtcg/include/tcg/utils/host/x86_64/cpuinfo.h @@ -1 +1,41 @@ -#include "../i386/cpuinfo.h" +/* + * SPDX-License-Identifier: GPL-2.0-or-later + * Host specific cpu identification for x86. + */ + +#ifndef HOST_CPUINFO_H +#define HOST_CPUINFO_H + +/* Digested version of */ + +#define CPUINFO_ALWAYS (1u << 0) /* so cpuinfo is nonzero */ +#define CPUINFO_OSXSAVE (1u << 1) +#define CPUINFO_MOVBE (1u << 2) +#define CPUINFO_LZCNT (1u << 3) +#define CPUINFO_POPCNT (1u << 4) +#define CPUINFO_BMI1 (1u << 5) +#define CPUINFO_BMI2 (1u << 6) +#define CPUINFO_SSE2 (1u << 7) +#define CPUINFO_AVX1 (1u << 9) +#define CPUINFO_AVX2 (1u << 10) +#define CPUINFO_AVX512F (1u << 11) +#define CPUINFO_AVX512VL (1u << 12) +#define CPUINFO_AVX512BW (1u << 13) +#define CPUINFO_AVX512DQ (1u << 14) +#define CPUINFO_AVX512VBMI2 (1u << 15) +#define CPUINFO_ATOMIC_VMOVDQA (1u << 16) +#define CPUINFO_ATOMIC_VMOVDQU (1u << 17) +#define CPUINFO_AES (1u << 18) +#define CPUINFO_PCLMUL (1u << 19) +#define CPUINFO_GFNI (1u << 20) + +/* Initialized with a constructor. */ +extern unsigned cpuinfo; + +/* + * We cannot rely on constructor ordering, so other constructors must + * use the function interface rather than the variable above. + */ +unsigned cpuinfo_init(void); + +#endif /* HOST_CPUINFO_H */ diff --git a/libtcg/include/tcg/utils/units.h b/libtcg/include/tcg/utils/units.h index 170cae516..1bb37f8e9 100644 --- a/libtcg/include/tcg/utils/units.h +++ b/libtcg/include/tcg/utils/units.h @@ -2,7 +2,7 @@ * IEC binary prefixes definitions * * Copyright (C) 2015 Nikunj A Dadhania, IBM Corporation - * Copyright (C) 2018 Philippe Mathieu-Daudé + * Copyright (C) 2018 Philippe Mathieu-Daudé * * SPDX-License-Identifier: GPL-2.0-or-later */ diff --git a/libtcg/include/tcg/i386/tcg-target-has.h b/libtcg/include/tcg/x86_64/tcg-target-has.h similarity index 91% rename from libtcg/include/tcg/i386/tcg-target-has.h rename to libtcg/include/tcg/x86_64/tcg-target-has.h index 51da8a323..d76dc50c4 100644 --- a/libtcg/include/tcg/i386/tcg-target-has.h +++ b/libtcg/include/tcg/x86_64/tcg-target-has.h @@ -25,12 +25,10 @@ #define have_avx512vbmi2 ((cpuinfo & CPUINFO_AVX512VBMI2) && have_avx512vl) /* optional instructions */ -#if TCG_TARGET_REG_BITS == 64 /* Keep 32-bit values zero-extended in a register. */ #define TCG_TARGET_HAS_extr_i64_i32 1 -#endif -#define TCG_TARGET_HAS_qemu_ldst_i128 (TCG_TARGET_REG_BITS == 64 && (cpuinfo & CPUINFO_ATOMIC_VMOVDQA)) +#define TCG_TARGET_HAS_qemu_ldst_i128 (cpuinfo & CPUINFO_ATOMIC_VMOVDQA) #define TCG_TARGET_HAS_tst 1 @@ -60,8 +58,7 @@ #define TCG_TARGET_HAS_cmpsel_vec 1 #define TCG_TARGET_HAS_tst_vec have_avx512bw -#define TCG_TARGET_deposit_valid(type, ofs, len) \ - (((ofs) == 0 && ((len) == 8 || (len) == 16)) || (TCG_TARGET_REG_BITS == 32 && (ofs) == 8 && (len) == 8)) +#define TCG_TARGET_deposit_valid(type, ofs, len) ((ofs) == 0 && ((len) == 8 || (len) == 16)) /* * Check for the possibility of low byte/word extraction, high-byte extraction diff --git a/libtcg/include/tcg/i386/tcg-target-mo.h b/libtcg/include/tcg/x86_64/tcg-target-mo.h similarity index 100% rename from libtcg/include/tcg/i386/tcg-target-mo.h rename to libtcg/include/tcg/x86_64/tcg-target-mo.h diff --git a/libtcg/include/tcg/i386/tcg-target-opc.h.inc b/libtcg/include/tcg/x86_64/tcg-target-opc.h.inc similarity index 100% rename from libtcg/include/tcg/i386/tcg-target-opc.h.inc rename to libtcg/include/tcg/x86_64/tcg-target-opc.h.inc diff --git a/libtcg/include/tcg/i386/tcg-target.h b/libtcg/include/tcg/x86_64/tcg-target.h similarity index 89% rename from libtcg/include/tcg/i386/tcg-target.h rename to libtcg/include/tcg/x86_64/tcg-target.h index fefa2dc17..0f7fb435d 100644 --- a/libtcg/include/tcg/i386/tcg-target.h +++ b/libtcg/include/tcg/x86_64/tcg-target.h @@ -27,13 +27,8 @@ #define TCG_TARGET_INSN_UNIT_SIZE 1 -#ifdef __x86_64__ #define TCG_TARGET_NB_REGS 32 #define MAX_CODE_GEN_BUFFER_SIZE (2 * GiB) -#else -#define TCG_TARGET_NB_REGS 24 -#define MAX_CODE_GEN_BUFFER_SIZE UINT32_MAX -#endif typedef enum { TCG_REG_EAX = 0, @@ -45,8 +40,6 @@ typedef enum { TCG_REG_ESI, TCG_REG_EDI, - /* 64-bit registers; always define the symbols to avoid - too much if-deffing. */ TCG_REG_R8, TCG_REG_R9, TCG_REG_R10, @@ -64,8 +57,6 @@ typedef enum { TCG_REG_XMM5, TCG_REG_XMM6, TCG_REG_XMM7, - - /* 64-bit registers; likewise always define. */ TCG_REG_XMM8, TCG_REG_XMM9, TCG_REG_XMM10, diff --git a/libtcg/src/CMakeLists.txt b/libtcg/src/CMakeLists.txt index 1ac0c8fcb..59c743789 100644 --- a/libtcg/src/CMakeLists.txt +++ b/libtcg/src/CMakeLists.txt @@ -56,11 +56,8 @@ else (TARGET_LONG_BITS) MESSAGE (FATAL_ERROR "Please specify -DTARGET_LONG_BITS") endif (TARGET_LONG_BITS) -if (TARGET_INSN_START_EXTRA_WORDS) - set (COMMON_FLAGS "${COMMON_FLAGS} -DTARGET_INSN_START_EXTRA_WORDS=${TARGET_INSN_START_EXTRA_WORDS}") -else (TARGET_INSN_START_EXTRA_WORDS) - MESSAGE (FATAL_ERROR "Please specify -DTARGET_INSN_START_EXTRA_WORDS") -endif (TARGET_INSN_START_EXTRA_WORDS) +# TARGET_INSN_START_EXTRA_WORDS was dropped in QEMU 11.1: tcg_gen_insn_start +# now always takes INSN_START_WORDS arguments, padded with zeroes by the caller. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COMMON_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COMMON_FLAGS}") diff --git a/libtcg/src/atomic_common.c.inc b/libtcg/src/atomic_common.c.inc index 468ffd11b..93ebc2aa2 100644 --- a/libtcg/src/atomic_common.c.inc +++ b/libtcg/src/atomic_common.c.inc @@ -1,6 +1,6 @@ -#define CMPXCHG_HELPER(OP, TYPE) \ - TYPE HELPER(atomic_##OP)(CPUArchState * env, target_ulong addr, TYPE oldv, TYPE newv, uint32_t oi) { \ - abort(); \ +#define CMPXCHG_HELPER(OP, TYPE) \ + TYPE HELPER(atomic_##OP)(CPUArchState * env, uint64_t addr, TYPE oldv, TYPE newv, uint32_t oi) { \ + abort(); \ } CMPXCHG_HELPER(cmpxchgb, uint32_t) @@ -8,24 +8,16 @@ CMPXCHG_HELPER(cmpxchgw_be, uint32_t) CMPXCHG_HELPER(cmpxchgw_le, uint32_t) CMPXCHG_HELPER(cmpxchgl_be, uint32_t) CMPXCHG_HELPER(cmpxchgl_le, uint32_t) - -#ifdef CONFIG_ATOMIC64 CMPXCHG_HELPER(cmpxchgq_be, uint64_t) CMPXCHG_HELPER(cmpxchgq_le, uint64_t) -#endif #undef CMPXCHG_HELPER -Int128 HELPER(nonatomic_cmpxchgo)(CPUArchState *env, uint64_t addr, Int128 cmpv, Int128 newv, uint32_t oi) { - abort(); -} - -#define ATOMIC_HELPER(OP, TYPE) \ - TYPE HELPER(glue(atomic_, OP))(CPUArchState * env, target_ulong addr, TYPE val, uint32_t oi) { \ - abort(); \ +#define ATOMIC_HELPER(OP, TYPE) \ + TYPE HELPER(glue(atomic_, OP))(CPUArchState * env, uint64_t addr, TYPE val, uint32_t oi) { \ + abort(); \ } -#ifdef CONFIG_ATOMIC64 #define GEN_ATOMIC_HELPERS(OP) \ ATOMIC_HELPER(glue(OP, b), uint32_t) \ ATOMIC_HELPER(glue(OP, w_be), uint32_t) \ @@ -34,14 +26,6 @@ Int128 HELPER(nonatomic_cmpxchgo)(CPUArchState *env, uint64_t addr, Int128 cmpv, ATOMIC_HELPER(glue(OP, l_le), uint32_t) \ ATOMIC_HELPER(glue(OP, q_be), uint64_t) \ ATOMIC_HELPER(glue(OP, q_le), uint64_t) -#else -#define GEN_ATOMIC_HELPERS(OP) \ - ATOMIC_HELPER(glue(OP, b), uint32_t) \ - ATOMIC_HELPER(glue(OP, w_be), uint32_t) \ - ATOMIC_HELPER(glue(OP, w_le), uint32_t) \ - ATOMIC_HELPER(glue(OP, l_be), uint32_t) \ - ATOMIC_HELPER(glue(OP, l_le), uint32_t) -#endif GEN_ATOMIC_HELPERS(fetch_add) GEN_ATOMIC_HELPERS(fetch_and) diff --git a/libtcg/src/atomic_template.h b/libtcg/src/atomic_template.h index 4787da828..263a3f340 100644 --- a/libtcg/src/atomic_template.h +++ b/libtcg/src/atomic_template.h @@ -25,8 +25,8 @@ #define SHIFT 4 #elif DATA_SIZE == 8 #define SUFFIX q -#define DATA_TYPE aligned_uint64_t -#define SDATA_TYPE aligned_int64_t +#define DATA_TYPE uint64_t +#define SDATA_TYPE int64_t #define BSWAP bswap64 #define SHIFT 3 #elif DATA_SIZE == 4 diff --git a/libtcg/src/optimize.c b/libtcg/src/optimize.c index 315e05e7b..820d44136 100644 --- a/libtcg/src/optimize.c +++ b/libtcg/src/optimize.c @@ -721,21 +721,6 @@ static bool swap_commutative(TCGArg dest, TCGArg *p1, TCGArg *p2) { return false; } -static bool swap_commutative2(TCGArg *p1, TCGArg *p2) { - int sum = 0; - sum += pref_commutative(arg_info(p1[0])); - sum += pref_commutative(arg_info(p1[1])); - sum -= pref_commutative(arg_info(p2[0])); - sum -= pref_commutative(arg_info(p2[1])); - if (sum > 0) { - TCGArg t; - t = p1[0], p1[0] = p2[0], p2[0] = t; - t = p1[1], p1[1] = p2[1], p2[1] = t; - return true; - } - return false; -} - /* * Return -1 if the condition can't be simplified, * and the result of the condition (0 or 1) if it can. @@ -797,107 +782,6 @@ static int do_constant_folding_cond1(OptContext *ctx, TCGOp *op, TCGArg dest, TC return -1; } -static int do_constant_folding_cond2(OptContext *ctx, TCGOp *op, TCGArg *args) { - TCGArg al, ah, bl, bh; - TCGCond c; - bool swap; - int r; - - swap = swap_commutative2(args, args + 2); - c = args[4]; - if (swap) { - args[4] = c = tcg_swap_cond(c); - } - - al = args[0]; - ah = args[1]; - bl = args[2]; - bh = args[3]; - - if (arg_is_const(bl) && arg_is_const(bh)) { - tcg_target_ulong blv = arg_const_val(bl); - tcg_target_ulong bhv = arg_const_val(bh); - uint64_t b = deposit64(blv, 32, 32, bhv); - - if (arg_is_const(al) && arg_is_const(ah)) { - tcg_target_ulong alv = arg_const_val(al); - tcg_target_ulong ahv = arg_const_val(ah); - uint64_t a = deposit64(alv, 32, 32, ahv); - - r = do_constant_folding_cond_64(a, b, c); - if (r >= 0) { - return r; - } - } - - if (b == 0) { - switch (c) { - case TCG_COND_LTU: - case TCG_COND_TSTNE: - return 0; - case TCG_COND_GEU: - case TCG_COND_TSTEQ: - return 1; - default: - break; - } - } - - /* TSTNE x,-1 -> NE x,0 */ - if (b == -1 && is_tst_cond(c)) { - args[3] = args[2] = arg_new_constant(ctx, 0); - args[4] = tcg_tst_eqne_cond(c); - return -1; - } - - /* TSTNE x,sign -> LT x,0 */ - if (b == INT64_MIN && is_tst_cond(c)) { - /* bl must be 0, so copy that to bh */ - args[3] = bl; - args[4] = tcg_tst_ltge_cond(c); - return -1; - } - } - - if (args_are_copies(al, bl) && args_are_copies(ah, bh)) { - r = do_constant_folding_cond_eq(c); - if (r >= 0) { - return r; - } - - /* TSTNE x,x -> NE x,0 */ - if (is_tst_cond(c)) { - args[3] = args[2] = arg_new_constant(ctx, 0); - args[4] = tcg_tst_eqne_cond(c); - return -1; - } - } - - /* Expand to AND with a temporary if no backend support. */ - if (!TCG_TARGET_HAS_tst && is_tst_cond(c)) { - TCGOp *op1 = opt_insert_before(ctx, op, INDEX_op_and, 3); - TCGOp *op2 = opt_insert_before(ctx, op, INDEX_op_and, 3); - TCGArg t1 = arg_new_temp(ctx); - TCGArg t2 = arg_new_temp(ctx); - - op1->args[0] = t1; - op1->args[1] = al; - op1->args[2] = bl; - fold_and(ctx, op1); - - op2->args[0] = t2; - op2->args[1] = ah; - op2->args[2] = bh; - fold_and(ctx, op1); - - args[0] = t1; - args[1] = t2; - args[3] = args[2] = arg_new_constant(ctx, 0); - args[4] = tcg_tst_eqne_cond(c); - } - return -1; -} - static void init_arguments(OptContext *ctx, TCGOp *op, int nb_args) { for (int i = 0; i < nb_args; i++) { TCGTemp *ts = arg_temp(op->args[i]); @@ -1028,8 +912,9 @@ static bool fold_masks_zosa_int(OptContext *ctx, TCGOp *op, uint64_t z_mask, uin ti = ts_info(ts); ti->z_mask = z_mask; + ti->o_mask = o_mask; - /* Canonicalize s_mask and incorporate data from z_mask. */ + /* Canonicalize s_mask and incorporate data from [zo]_mask. */ rep = clz64(~s_mask); rep = MAX(rep, clz64(z_mask)); rep = MAX(rep, clz64(~o_mask)); @@ -1041,7 +926,7 @@ static bool fold_masks_zosa_int(OptContext *ctx, TCGOp *op, uint64_t z_mask, uin static bool fold_masks_zosa(OptContext *ctx, TCGOp *op, uint64_t z_mask, uint64_t o_mask, int64_t s_mask, uint64_t a_mask) { - fold_masks_zosa_int(ctx, op, z_mask, o_mask, s_mask, -1); + fold_masks_zosa_int(ctx, op, z_mask, o_mask, s_mask, a_mask); return true; } @@ -1504,98 +1389,6 @@ static bool fold_brcond(OptContext *ctx, TCGOp *op) { return true; } -static bool fold_brcond2(OptContext *ctx, TCGOp *op) { - TCGCond cond; - TCGArg label; - int i, inv = 0; - - i = do_constant_folding_cond2(ctx, op, &op->args[0]); - cond = op->args[4]; - label = op->args[5]; - if (i >= 0) { - goto do_brcond_const; - } - - switch (cond) { - case TCG_COND_LT: - case TCG_COND_GE: - /* - * Simplify LT/GE comparisons vs zero to a single compare - * vs the high word of the input. - */ - if (arg_is_const_val(op->args[2], 0) && arg_is_const_val(op->args[3], 0)) { - goto do_brcond_high; - } - break; - - case TCG_COND_NE: - inv = 1; - QEMU_FALLTHROUGH; - case TCG_COND_EQ: - /* - * Simplify EQ/NE comparisons where one of the pairs - * can be simplified. - */ - i = do_constant_folding_cond(TCG_TYPE_I32, op->args[0], op->args[2], cond); - switch (i ^ inv) { - case 0: - goto do_brcond_const; - case 1: - goto do_brcond_high; - } - - i = do_constant_folding_cond(TCG_TYPE_I32, op->args[1], op->args[3], cond); - switch (i ^ inv) { - case 0: - goto do_brcond_const; - case 1: - goto do_brcond_low; - } - break; - - case TCG_COND_TSTEQ: - case TCG_COND_TSTNE: - if (arg_is_const_val(op->args[2], 0)) { - goto do_brcond_high; - } - if (arg_is_const_val(op->args[3], 0)) { - goto do_brcond_low; - } - break; - - default: - break; - - do_brcond_low: - op->opc = INDEX_op_brcond; - op->args[1] = op->args[2]; - op->args[2] = cond; - op->args[3] = label; - return fold_brcond(ctx, op); - - do_brcond_high: - op->opc = INDEX_op_brcond; - op->args[0] = op->args[1]; - op->args[1] = op->args[3]; - op->args[2] = cond; - op->args[3] = label; - return fold_brcond(ctx, op); - - do_brcond_const: - if (i == 0) { - tcg_op_remove(ctx->tcg, op); - return true; - } - op->opc = INDEX_op_br; - op->args[0] = label; - finish_ebb(ctx); - return true; - } - - finish_bb(ctx); - return true; -} - static bool fold_bswap(OptContext *ctx, TCGOp *op) { uint64_t z_mask, o_mask, s_mask; TempOptInfo *t1 = arg_info(op->args[1]); @@ -1760,46 +1553,207 @@ static bool fold_ctpop(OptContext *ctx, TCGOp *op) { } static bool fold_deposit(OptContext *ctx, TCGOp *op) { - TempOptInfo *t1 = arg_info(op->args[1]); - TempOptInfo *t2 = arg_info(op->args[2]); + TCGArg ret = op->args[0]; + TCGArg arg1 = op->args[1]; + TCGArg arg2 = op->args[2]; int ofs = op->args[3]; int len = op->args[4]; - int width = 8 * tcg_type_size(ctx->type); - uint64_t z_mask, o_mask, s_mask; + TempOptInfo *t1 = arg_info(arg1); + TempOptInfo *t2 = arg_info(arg2); + int width; + uint64_t z_mask, o_mask, s_mask, type_mask, len_mask; + TCGOp *op2; + bool valid; if (ti_is_const(t1) && ti_is_const(t2)) { return tcg_opt_gen_movi(ctx, op, op->args[0], deposit64(ti_const_val(t1), ofs, len, ti_const_val(t2))); } - /* Inserting a value into zero at offset 0. */ - if (ti_is_const_val(t1, 0) && ofs == 0) { - uint64_t mask = MAKE_64BIT_MASK(0, len); + width = 8 * tcg_type_size(ctx->type); + type_mask = MAKE_64BIT_MASK(0, width); + len_mask = MAKE_64BIT_MASK(0, len); + /* Inserting all-zero into a value. */ + if ((t2->z_mask & len_mask) == 0) { op->opc = INDEX_op_and; - op->args[1] = op->args[2]; - op->args[2] = arg_new_constant(ctx, mask); + op->args[2] = arg_new_constant(ctx, ~(len_mask << ofs)); return fold_and(ctx, op); } - /* Inserting zero into a value. */ - if (ti_is_const_val(t2, 0)) { - uint64_t mask = deposit64(-1, ofs, len, 0); - - op->opc = INDEX_op_and; - op->args[2] = arg_new_constant(ctx, mask); - return fold_and(ctx, op); + /* Inserting all-one into a value. */ + if ((t2->o_mask & len_mask) == len_mask) { + op->opc = INDEX_op_or; + op->args[2] = arg_new_constant(ctx, len_mask << ofs); + return fold_or(ctx, op); } - /* The s_mask from the top portion of the deposit is still valid. */ - if (ofs + len == width) { - s_mask = t2->s_mask << ofs; - } else { - s_mask = t1->s_mask & ~MAKE_64BIT_MASK(0, ofs + len); + valid = TCG_TARGET_deposit_valid(ctx->type, ofs, len); + + /* Lower invalid deposit of constant as AND + OR. */ + if (!valid && ti_is_const(t2)) { + uint64_t ins_val = (ti_const_val(t2) & len_mask) << ofs; + + op2 = opt_insert_before(ctx, op, INDEX_op_and, 3); + op2->args[0] = ret; + op2->args[1] = arg1; + op2->args[2] = arg_new_constant(ctx, ~(len_mask << ofs)); + fold_and(ctx, op2); + + op->opc = INDEX_op_or; + op->args[1] = ret; + op->args[2] = arg_new_constant(ctx, ins_val); + return fold_or(ctx, op); } + /* + * Compute result masks before calling other fold_* subroutines + * which could modify the masks of our inputs. + */ z_mask = deposit64(t1->z_mask, ofs, len, t2->z_mask); o_mask = deposit64(t1->o_mask, ofs, len, t2->o_mask); + if (ofs + len < width) { + s_mask = t1->s_mask & ~MAKE_64BIT_MASK(0, ofs + len); + } else { + s_mask = t2->s_mask << ofs; + } + /* Inserting a value into zero. */ + if (ti_is_const_val(t1, 0)) { + uint64_t need_mask; + + /* Always lower deposit into zero at 0 as AND. */ + if (ofs == 0) { + op->opc = INDEX_op_and; + op->args[1] = arg2; + op->args[2] = arg_new_constant(ctx, len_mask); + return fold_and(ctx, op); + } + + /* + * If the portion of the value outside len that remains after + * shifting is zero, we can elide the mask and just shift. + */ + need_mask = t2->z_mask & ~len_mask; + need_mask = (need_mask << ofs) & type_mask; + if (!need_mask) { + op->opc = INDEX_op_shl; + op->args[1] = arg2; + op->args[2] = arg_new_constant(ctx, ofs); + goto done; + } + + /* Lower invalid deposit into zero as AND + SHL or SHL + SHR. */ + if (!valid) { + if (TCG_TARGET_extract_valid(ctx->type, 0, len)) { + /* EXTRACT (at 0) + SHL */ + op2 = opt_insert_before(ctx, op, INDEX_op_extract, 4); + op2->args[0] = ret; + op2->args[1] = arg2; + op2->args[2] = 0; + op2->args[3] = len; + } else if (tcg_op_imm_match(INDEX_op_and, ctx->type, len_mask)) { + /* AND + SHL */ + op2 = opt_insert_before(ctx, op, INDEX_op_and, 3); + op2->args[0] = ret; + op2->args[1] = arg2; + op2->args[2] = arg_new_constant(ctx, len_mask); + } else { + /* SHL + SHR */ + int shl = width - len; + int shr = width - len - ofs; + + op2 = opt_insert_before(ctx, op, INDEX_op_shl, 3); + op2->args[0] = ret; + op2->args[1] = arg2; + op2->args[2] = arg_new_constant(ctx, shl); + + op->opc = INDEX_op_shr; + op->args[1] = ret; + op->args[2] = arg_new_constant(ctx, shr); + goto done; + } + + /* Finish the (EXTRACT|AND) + SHL cases. */ + op->opc = INDEX_op_shl; + op->args[1] = ret; + op->args[2] = arg_new_constant(ctx, ofs); + goto done; + } + } + + /* After special cases, lower invalid deposit. */ + if (!valid) { + TCGArg tmp; + + if (tcg_op_supported(INDEX_op_extract2, ctx->type, 0)) { + if (ofs == 0 && tcg_op_supported(INDEX_op_rotl, ctx->type, 0)) { + /* + * ret = arg2:arg1 >> len + * ret = rotl(ret, len) + */ + op2 = opt_insert_before(ctx, op, INDEX_op_extract2, 4); + op2->args[0] = ret; + op2->args[1] = arg1; + op2->args[2] = arg2; + op2->args[3] = len; + + op->opc = INDEX_op_rotl; + op->args[1] = ret; + op->args[2] = arg_new_constant(ctx, len); + goto done; + } + if (ofs + len == width) { + /* + * tmp = arg1 << len + * ret = arg2:tmp >> len + */ + tmp = ret == arg2 ? arg_new_temp(ctx) : ret; + + op2 = opt_insert_before(ctx, op, INDEX_op_shl, 4); + op2->args[0] = tmp; + op2->args[1] = arg1; + op2->args[2] = arg_new_constant(ctx, len); + + op->opc = INDEX_op_extract2; + op->args[0] = ret; + op->args[1] = tmp; + op->args[2] = arg2; + op->args[3] = len; + goto done; + } + } + + /* + * tmp = arg2 & mask + * ret = arg1 & ~(mask << ofs) + * tmp = tmp << ofs + * ret = ret | tmp + */ + tmp = arg_new_temp(ctx); + + op2 = opt_insert_before(ctx, op, INDEX_op_and, 3); + op2->args[0] = tmp; + op2->args[1] = arg2; + op2->args[2] = arg_new_constant(ctx, len_mask); + fold_and(ctx, op2); + + op2 = opt_insert_before(ctx, op, INDEX_op_shl, 3); + op2->args[0] = tmp; + op2->args[1] = tmp; + op2->args[2] = arg_new_constant(ctx, ofs); + + op2 = opt_insert_before(ctx, op, INDEX_op_and, 3); + op2->args[0] = ret; + op2->args[1] = arg1; + op2->args[2] = arg_new_constant(ctx, ~(len_mask << ofs)); + fold_and(ctx, op2); + + op->opc = INDEX_op_or; + op->args[1] = ret; + op->args[2] = tmp; + } + +done: return fold_masks_zos(ctx, op, z_mask, o_mask, s_mask); } @@ -1819,19 +1773,6 @@ static bool fold_dup(OptContext *ctx, TCGOp *op) { return finish_folding(ctx, op); } -static bool fold_dup2(OptContext *ctx, TCGOp *op) { - if (arg_is_const(op->args[1]) && arg_is_const(op->args[2])) { - uint64_t t = deposit64(arg_const_val(op->args[1]), 32, 32, arg_const_val(op->args[2])); - return tcg_opt_gen_movi(ctx, op, op->args[0], t); - } - - if (args_are_copies(op->args[1], op->args[2])) { - op->opc = INDEX_op_dup_vec; - TCGOP_VECE(op) = MO_32; - } - return finish_folding(ctx, op); -} - static bool fold_eqv(OptContext *ctx, TCGOp *op) { uint64_t z_mask, o_mask, s_mask; TempOptInfo *t1, *t2; @@ -1893,21 +1834,74 @@ static bool fold_extract2(OptContext *ctx, TCGOp *op) { uint64_t z2 = t2->z_mask; uint64_t o1 = t1->o_mask; uint64_t o2 = t2->o_mask; + uint64_t zr, or ; int shr = op->args[3]; + int shl; if (ctx->type == TCG_TYPE_I32) { z1 = (uint32_t) z1 >> shr; o1 = (uint32_t) o1 >> shr; - z2 = (uint64_t) ((int32_t) z2 << (32 - shr)); - o2 = (uint64_t) ((int32_t) o2 << (32 - shr)); + shl = 32 - shr; + z2 = (uint64_t) ((int32_t) z2 << shl); + o2 = (uint64_t) ((int32_t) o2 << shl); } else { z1 >>= shr; o1 >>= shr; - z2 <<= 64 - shr; - o2 <<= 64 - shr; + shl = 64 - shr; + z2 <<= shl; + o2 <<= shl; + } + zr = z1 | z2; + or = o1 | o2; + + if (zr == or) { + return tcg_opt_gen_movi(ctx, op, op->args[0], zr); } - return fold_masks_zo(ctx, op, z1 | z2, o1 | o2); + if (z2 == 0) { + /* High part zeros folds to simple right shift. */ + op->opc = INDEX_op_shr; + op->args[2] = arg_new_constant(ctx, shr); + } else if (z1 == 0) { + /* Low part zeros folds to simple left shift. */ + op->opc = INDEX_op_shl; + op->args[1] = op->args[2]; + op->args[2] = arg_new_constant(ctx, shl); + } else if (!tcg_op_supported(INDEX_op_extract2, ctx->type, 0)) { + TCGArg tmp = arg_new_temp(ctx); + TCGOp *op2 = opt_insert_before(ctx, op, INDEX_op_shr, 3); + + op2->args[0] = tmp; + op2->args[1] = op->args[1]; + op2->args[2] = arg_new_constant(ctx, shr); + + if (TCG_TARGET_deposit_valid(ctx->type, shl, shr)) { + /* + * Deposit has more arguments than extract2, + * so we need to create a new TCGOp. + */ + op2 = opt_insert_before(ctx, op, INDEX_op_deposit, 5); + op2->args[0] = op->args[0]; + op2->args[1] = tmp; + op2->args[2] = op->args[2]; + op2->args[3] = shl; + op2->args[4] = shr; + + tcg_op_remove(ctx->tcg, op); + op = op2; + } else { + op2 = opt_insert_before(ctx, op, INDEX_op_shl, 3); + op2->args[0] = op->args[0]; + op2->args[1] = op->args[2]; + op2->args[2] = arg_new_constant(ctx, shl); + + op->opc = INDEX_op_or; + op->args[1] = op->args[0]; + op->args[2] = tmp; + } + } + + return fold_masks_zo(ctx, op, zr, or); } static bool fold_exts(OptContext *ctx, TCGOp *op) { @@ -2059,45 +2053,72 @@ static bool fold_mul_highpart(OptContext *ctx, TCGOp *op) { static bool fold_multiply2(OptContext *ctx, TCGOp *op) { swap_commutative(op->args[0], &op->args[2], &op->args[3]); - if (arg_is_const(op->args[2]) && arg_is_const(op->args[3])) { - uint64_t a = arg_const_val(op->args[2]); + if (arg_is_const(op->args[3])) { uint64_t b = arg_const_val(op->args[3]); - uint64_t h, l; - TCGArg rl, rh; + TCGArg rl = op->args[0]; + TCGArg rh = op->args[1]; TCGOp *op2; - switch (op->opc) { - case INDEX_op_mulu2: - if (ctx->type == TCG_TYPE_I32) { - l = (uint64_t) (uint32_t) a * (uint32_t) b; - h = (int32_t) (l >> 32); - l = (int32_t) l; - } else { - mulu64(&l, &h, a, b); - } - break; - case INDEX_op_muls2: - if (ctx->type == TCG_TYPE_I32) { - l = (int64_t) (int32_t) a * (int32_t) b; - h = l >> 32; - l = (int32_t) l; - } else { - muls64(&l, &h, a, b); - } - break; - default: - g_assert_not_reached(); + if (arg_is_const(op->args[2])) { + uint64_t a = arg_const_val(op->args[2]); + uint64_t h, l; + + switch (op->opc) { + case INDEX_op_mulu2: + if (ctx->type == TCG_TYPE_I32) { + l = (uint64_t) (uint32_t) a * (uint32_t) b; + h = (int32_t) (l >> 32); + l = (int32_t) l; + } else { + mulu64(&l, &h, a, b); + } + break; + case INDEX_op_muls2: + if (ctx->type == TCG_TYPE_I32) { + l = (int64_t) (int32_t) a * (int32_t) b; + h = l >> 32; + l = (int32_t) l; + } else { + muls64(&l, &h, a, b); + } + break; + default: + g_assert_not_reached(); + } + + /* The proper opcode is supplied by tcg_opt_gen_mov. */ + op2 = opt_insert_before(ctx, op, 0, 2); + tcg_opt_gen_movi(ctx, op, rl, l); + tcg_opt_gen_movi(ctx, op2, rh, h); + return true; } - rl = op->args[0]; - rh = op->args[1]; + if (b == 0) { + op2 = opt_insert_before(ctx, op, 0, 2); + tcg_opt_gen_movi(ctx, op2, rl, 0); + tcg_opt_gen_movi(ctx, op, rh, 0); + return true; + } + if (b == 1) { + op2 = opt_insert_before(ctx, op, 0, 2); + tcg_opt_gen_mov(ctx, op2, rl, op->args[2]); - /* The proper opcode is supplied by tcg_opt_gen_mov. */ - op2 = opt_insert_before(ctx, op, 0, 2); + switch (op->opc) { + case INDEX_op_mulu2: + tcg_opt_gen_movi(ctx, op, rh, 0); + break; + case INDEX_op_muls2: + op->opc = INDEX_op_sar; + op->args[0] = rh; + op->args[1] = rl; + op->args[2] = arg_new_constant(ctx, tcg_type_size(ctx->type) * 8 - 1); + break; + default: + g_assert_not_reached(); + } - tcg_opt_gen_movi(ctx, op, rl, l); - tcg_opt_gen_movi(ctx, op2, rh, h); - return true; + return true; + } } return finish_folding(ctx, op); } @@ -2219,7 +2240,7 @@ static bool fold_orc(OptContext *ctx, TCGOp *op) { s_mask = t1->s_mask & t2->s_mask; /* Affected bits are those not known one, masked by those known one. */ - a_mask = ~t1->o_mask & t2->o_mask; + a_mask = ~t1->o_mask & ~t2->o_mask; return fold_masks_zosa(ctx, op, z_mask, o_mask, s_mask, a_mask); } @@ -2447,86 +2468,6 @@ static bool fold_negsetcond(OptContext *ctx, TCGOp *op) { return fold_masks_s(ctx, op, -1); } -static bool fold_setcond2(OptContext *ctx, TCGOp *op) { - TCGCond cond; - int i, inv = 0; - - i = do_constant_folding_cond2(ctx, op, &op->args[1]); - cond = op->args[5]; - if (i >= 0) { - goto do_setcond_const; - } - - switch (cond) { - case TCG_COND_LT: - case TCG_COND_GE: - /* - * Simplify LT/GE comparisons vs zero to a single compare - * vs the high word of the input. - */ - if (arg_is_const_val(op->args[3], 0) && arg_is_const_val(op->args[4], 0)) { - goto do_setcond_high; - } - break; - - case TCG_COND_NE: - inv = 1; - QEMU_FALLTHROUGH; - case TCG_COND_EQ: - /* - * Simplify EQ/NE comparisons where one of the pairs - * can be simplified. - */ - i = do_constant_folding_cond(TCG_TYPE_I32, op->args[1], op->args[3], cond); - switch (i ^ inv) { - case 0: - goto do_setcond_const; - case 1: - goto do_setcond_high; - } - - i = do_constant_folding_cond(TCG_TYPE_I32, op->args[2], op->args[4], cond); - switch (i ^ inv) { - case 0: - goto do_setcond_const; - case 1: - goto do_setcond_low; - } - break; - - case TCG_COND_TSTEQ: - case TCG_COND_TSTNE: - if (arg_is_const_val(op->args[3], 0)) { - goto do_setcond_high; - } - if (arg_is_const_val(op->args[4], 0)) { - goto do_setcond_low; - } - break; - - default: - break; - - do_setcond_low: - op->args[2] = op->args[3]; - op->args[3] = cond; - op->opc = INDEX_op_setcond; - return fold_setcond(ctx, op); - - do_setcond_high: - op->args[1] = op->args[2]; - op->args[2] = op->args[4]; - op->args[3] = cond; - op->opc = INDEX_op_setcond; - return fold_setcond(ctx, op); - } - - return fold_masks_z(ctx, op, 1); - -do_setcond_const: - return tcg_opt_gen_movi(ctx, op, op->args[0], i); -} - static bool fold_sextract(OptContext *ctx, TCGOp *op) { uint64_t z_mask, o_mask, s_mask, a_mask; TempOptInfo *t1 = arg_info(op->args[1]); @@ -2981,9 +2922,6 @@ void tcg_optimize(TCGContext *s) { case INDEX_op_brcond: done = fold_brcond(&ctx, op); break; - case INDEX_op_brcond2_i32: - done = fold_brcond2(&ctx, op); - break; case INDEX_op_bswap16: case INDEX_op_bswap32: case INDEX_op_bswap64: @@ -3006,9 +2944,6 @@ void tcg_optimize(TCGContext *s) { case INDEX_op_dup_vec: done = fold_dup(&ctx, op); break; - case INDEX_op_dup2_vec: - done = fold_dup2(&ctx, op); - break; case INDEX_op_eqv: case INDEX_op_eqv_vec: done = fold_eqv(&ctx, op); @@ -3119,9 +3054,6 @@ void tcg_optimize(TCGContext *s) { case INDEX_op_negsetcond: done = fold_negsetcond(&ctx, op); break; - case INDEX_op_setcond2_i32: - done = fold_setcond2(&ctx, op); - break; case INDEX_op_cmp_vec: done = fold_cmp_vec(&ctx, op); break; diff --git a/libtcg/src/region.c b/libtcg/src/region.c index e21f0afa6..c1e6567b3 100644 --- a/libtcg/src/region.c +++ b/libtcg/src/region.c @@ -456,17 +456,6 @@ static size_t tcg_n_regions(size_t tb_size, unsigned max_threads) { */ #define MIN_CODE_GEN_BUFFER_SIZE (1 * MiB) -#if TCG_TARGET_REG_BITS == 32 -#define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (32 * MiB) -#ifdef CONFIG_USER_ONLY -/* - * For user mode on smaller 32 bit systems we may run into trouble - * allocating big chunks of data in the right place. On these systems - * we utilise a static code generation buffer directly in the binary. - */ -#define USE_STATIC_CODE_GEN_BUFFER -#endif -#else /* TCG_TARGET_REG_BITS == 64 */ #ifdef CONFIG_USER_ONLY /* * As user-mode emulation typically means running multiple instances @@ -482,7 +471,6 @@ static size_t tcg_n_regions(size_t tb_size, unsigned max_threads) { */ #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (1 * GiB) #endif -#endif #define DEFAULT_CODE_GEN_BUFFER_SIZE \ (DEFAULT_CODE_GEN_BUFFER_SIZE_1 < MAX_CODE_GEN_BUFFER_SIZE ? DEFAULT_CODE_GEN_BUFFER_SIZE_1 \ diff --git a/libtcg/src/tcg-ldst.c.inc b/libtcg/src/tcg-ldst.c.inc deleted file mode 100644 index 3bc5341d2..000000000 --- a/libtcg/src/tcg-ldst.c.inc +++ /dev/null @@ -1,61 +0,0 @@ -/* - * TCG Backend Data: load-store optimization only. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* - * Generate TB finalization at the end of block - */ - -static bool tcg_out_qemu_ld_slow_path(TCGContext *s, TCGLabelQemuLdst *l); -static bool tcg_out_qemu_st_slow_path(TCGContext *s, TCGLabelQemuLdst *l); - -static int tcg_out_ldst_finalize(TCGContext *s) { - TCGLabelQemuLdst *lb; - - /* qemu_ld/st slow paths */ - QSIMPLEQ_FOREACH(lb, &s->ldst_labels, next) { - if (lb->is_ld ? !tcg_out_qemu_ld_slow_path(s, lb) : !tcg_out_qemu_st_slow_path(s, lb)) { - return -2; - } - - /* Test for (pending) buffer overflow. The assumption is that any - one operation beginning below the high water mark cannot overrun - the buffer completely. Thus we can test for overflow after - generating code without having to check during generation. */ - if (unlikely((void *) s->code_ptr > s->code_gen_highwater)) { - return -1; - } - } - return 0; -} - -/* - * Allocate a new TCGLabelQemuLdst entry. - */ - -static inline TCGLabelQemuLdst *new_ldst_label(TCGContext *s) { - TCGLabelQemuLdst *l = tcg_malloc(sizeof(*l)); - - memset(l, 0, sizeof(*l)); - QSIMPLEQ_INSERT_TAIL(&s->ldst_labels, l, next); - - return l; -} diff --git a/libtcg/src/tcg-op-gvec.c b/libtcg/src/tcg-op-gvec.c index c954120a1..1b26ca90d 100644 --- a/libtcg/src/tcg-op-gvec.c +++ b/libtcg/src/tcg-op-gvec.c @@ -532,11 +532,11 @@ static void do_dup(unsigned vece, TCGv_ptr dbase, uint32_t dofs, uint32_t oprsz, } } - /* Implement inline with a vector type, if possible. - * Prefer integer when 64-bit host and no variable dup. + /* + * Implement inline with a vector type, if possible; + * prefer_i64 with 64-bit variable dup. */ - type = choose_vector_type(NULL, vece, oprsz, - (TCG_TARGET_REG_BITS == 64 && in_32 == NULL && (in_64 == NULL || vece == MO_64))); + type = choose_vector_type(NULL, vece, oprsz, vece == MO_64 && in_64); if (type != 0) { TCGv_vec t_vec = tcg_temp_new_vec(type); @@ -552,15 +552,16 @@ static void do_dup(unsigned vece, TCGv_ptr dbase, uint32_t dofs, uint32_t oprsz, } /* Otherwise, inline with an integer type, unless "large". */ - if (check_size_impl(oprsz, TCG_TARGET_REG_BITS / 8)) { + if (check_size_impl(oprsz, sizeof(tcg_target_long))) { t_64 = NULL; t_32 = NULL; if (in_32) { - /* We are given a 32-bit variable input. For a 64-bit host, - use a 64-bit operation unless the 32-bit operation would - be simple enough. */ - if (TCG_TARGET_REG_BITS == 64 && (vece != MO_32 || !check_size_impl(oprsz, 4))) { + /* + * We are given a 32-bit variable input. Use a 64-bit operation + * unless the 32-bit operation would be simple enough. + */ + if (vece != MO_32 || !check_size_impl(oprsz, 4)) { t_64 = tcg_temp_ebb_new_i64(); tcg_gen_extu_i32_i64(t_64, in_32); tcg_gen_dup_i64(vece, t_64, t_64); @@ -573,12 +574,13 @@ static void do_dup(unsigned vece, TCGv_ptr dbase, uint32_t dofs, uint32_t oprsz, t_64 = tcg_temp_ebb_new_i64(); tcg_gen_dup_i64(vece, t_64, in_64); } else { - /* We are given a constant input. */ - /* For 64-bit hosts, use 64-bit constants for "simple" constants - or when we'd need too many 32-bit stores, or when a 64-bit - constant is really required. */ - if (vece == MO_64 || - (TCG_TARGET_REG_BITS == 64 && (in_c == 0 || in_c == -1 || !check_size_impl(oprsz, 4)))) { + /* + * We are given a constant input. + * Use 64-bit constants for "simple" constants or when we'd + * need too many 32-bit stores, or when a 64-bit constant + * is really required. + */ + if (vece == MO_64 || in_c == 0 || in_c == -1 || !check_size_impl(oprsz, 4)) { t_64 = tcg_constant_i64(in_c); } else { t_32 = tcg_constant_i32(in_c); @@ -1576,7 +1578,7 @@ void tcg_gen_gvec_mov_var(unsigned vece, TCGv_ptr dbase, uint32_t dofs, TCGv_ptr .fni8 = tcg_gen_mov_i64, .fniv = vec_mov2, .fno = gen_helper_gvec_mov, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; if (dofs == aofs && dbase == abase) { @@ -1726,7 +1728,7 @@ void tcg_gen_gvec_not(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t oprs .fni8 = tcg_gen_not_i64, .fniv = tcg_gen_not_vec, .fno = gen_helper_gvec_not, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; tcg_gen_gvec_2(dofs, aofs, oprsz, maxsz, &g); } @@ -1830,7 +1832,7 @@ void tcg_gen_gvec_add_var(unsigned vece, TCGv_ptr dbase, uint32_t dofs, TCGv_ptr .fniv = tcg_gen_add_vec, .fno = gen_helper_gvec_add64, .opt_opc = vecop_list_add, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -1863,7 +1865,7 @@ void tcg_gen_gvec_adds(unsigned vece, uint32_t dofs, uint32_t aofs, TCGv_i64 c, .fniv = tcg_gen_add_vec, .fno = gen_helper_gvec_adds64, .opt_opc = vecop_list_add, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -1899,7 +1901,7 @@ void tcg_gen_gvec_subs(unsigned vece, uint32_t dofs, uint32_t aofs, TCGv_i64 c, .fniv = tcg_gen_sub_vec, .fno = gen_helper_gvec_subs64, .opt_opc = vecop_list_sub, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -2002,7 +2004,7 @@ void tcg_gen_gvec_sub_var(unsigned vece, TCGv_ptr dbase, uint32_t dofs, TCGv_ptr .fniv = tcg_gen_sub_vec, .fno = gen_helper_gvec_sub64, .opt_opc = vecop_list_sub, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -2029,7 +2031,7 @@ void tcg_gen_gvec_mul(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bofs .fniv = tcg_gen_mul_vec, .fno = gen_helper_gvec_mul64, .opt_opc = vecop_list_mul, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -2050,7 +2052,7 @@ void tcg_gen_gvec_muls(unsigned vece, uint32_t dofs, uint32_t aofs, TCGv_i64 c, .fniv = tcg_gen_mul_vec, .fno = gen_helper_gvec_muls64, .opt_opc = vecop_list_mul, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -2285,7 +2287,7 @@ void tcg_gen_gvec_neg(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t oprs .fniv = tcg_gen_neg_vec, .fno = gen_helper_gvec_neg64, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -2344,7 +2346,7 @@ void tcg_gen_gvec_abs(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t oprs .fniv = tcg_gen_abs_vec, .fno = gen_helper_gvec_abs64, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -2357,7 +2359,7 @@ void tcg_gen_gvec_and(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bofs .fni8 = tcg_gen_and_i64, .fniv = tcg_gen_and_vec, .fno = gen_helper_gvec_and, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; if (aofs == bofs) { @@ -2372,7 +2374,7 @@ void tcg_gen_gvec_or(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bofs, .fni8 = tcg_gen_or_i64, .fniv = tcg_gen_or_vec, .fno = gen_helper_gvec_or, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; if (aofs == bofs) { @@ -2387,7 +2389,7 @@ void tcg_gen_gvec_xor(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bofs .fni8 = tcg_gen_xor_i64, .fniv = tcg_gen_xor_vec, .fno = gen_helper_gvec_xor, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; if (aofs == bofs) { @@ -2402,7 +2404,7 @@ void tcg_gen_gvec_andc(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bof .fni8 = tcg_gen_andc_i64, .fniv = tcg_gen_andc_vec, .fno = gen_helper_gvec_andc, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; if (aofs == bofs) { @@ -2417,7 +2419,7 @@ void tcg_gen_gvec_orc(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bofs .fni8 = tcg_gen_orc_i64, .fniv = tcg_gen_orc_vec, .fno = gen_helper_gvec_orc, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; if (aofs == bofs) { @@ -2432,7 +2434,7 @@ void tcg_gen_gvec_nand(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bof .fni8 = tcg_gen_nand_i64, .fniv = tcg_gen_nand_vec, .fno = gen_helper_gvec_nand, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; if (aofs == bofs) { @@ -2447,7 +2449,7 @@ void tcg_gen_gvec_nor(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bofs .fni8 = tcg_gen_nor_i64, .fniv = tcg_gen_nor_vec, .fno = gen_helper_gvec_nor, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; if (aofs == bofs) { @@ -2462,7 +2464,7 @@ void tcg_gen_gvec_eqv(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bofs .fni8 = tcg_gen_eqv_i64, .fniv = tcg_gen_eqv_vec, .fno = gen_helper_gvec_eqv, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, }; if (aofs == bofs) { @@ -2472,11 +2474,8 @@ void tcg_gen_gvec_eqv(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bofs } } -static const GVecGen2s gop_ands = {.fni8 = tcg_gen_and_i64, - .fniv = tcg_gen_and_vec, - .fno = gen_helper_gvec_ands, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, - .vece = MO_64}; +static const GVecGen2s gop_ands = { + .fni8 = tcg_gen_and_i64, .fniv = tcg_gen_and_vec, .fno = gen_helper_gvec_ands, .prefer_i64 = true, .vece = MO_64}; void tcg_gen_gvec_ands(unsigned vece, uint32_t dofs, uint32_t aofs, TCGv_i64 c, uint32_t oprsz, uint32_t maxsz) { TCGv_i64 tmp = tcg_temp_ebb_new_i64(); @@ -2494,7 +2493,7 @@ void tcg_gen_gvec_andcs(unsigned vece, uint32_t dofs, uint32_t aofs, TCGv_i64 c, static GVecGen2s g = {.fni8 = tcg_gen_andc_i64, .fniv = tcg_gen_andc_vec, .fno = gen_helper_gvec_andcs, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}; TCGv_i64 tmp = tcg_temp_ebb_new_i64(); @@ -2503,11 +2502,8 @@ void tcg_gen_gvec_andcs(unsigned vece, uint32_t dofs, uint32_t aofs, TCGv_i64 c, tcg_temp_free_i64(tmp); } -static const GVecGen2s gop_xors = {.fni8 = tcg_gen_xor_i64, - .fniv = tcg_gen_xor_vec, - .fno = gen_helper_gvec_xors, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, - .vece = MO_64}; +static const GVecGen2s gop_xors = { + .fni8 = tcg_gen_xor_i64, .fniv = tcg_gen_xor_vec, .fno = gen_helper_gvec_xors, .prefer_i64 = true, .vece = MO_64}; void tcg_gen_gvec_xors(unsigned vece, uint32_t dofs, uint32_t aofs, TCGv_i64 c, uint32_t oprsz, uint32_t maxsz) { TCGv_i64 tmp = tcg_temp_ebb_new_i64(); @@ -2521,11 +2517,8 @@ void tcg_gen_gvec_xori(unsigned vece, uint32_t dofs, uint32_t aofs, int64_t c, u tcg_gen_gvec_2s(dofs, aofs, oprsz, maxsz, tmp, &gop_xors); } -static const GVecGen2s gop_ors = {.fni8 = tcg_gen_or_i64, - .fniv = tcg_gen_or_vec, - .fno = gen_helper_gvec_ors, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, - .vece = MO_64}; +static const GVecGen2s gop_ors = { + .fni8 = tcg_gen_or_i64, .fniv = tcg_gen_or_vec, .fno = gen_helper_gvec_ors, .prefer_i64 = true, .vece = MO_64}; void tcg_gen_gvec_ors(unsigned vece, uint32_t dofs, uint32_t aofs, TCGv_i64 c, uint32_t oprsz, uint32_t maxsz) { TCGv_i64 tmp = tcg_temp_ebb_new_i64(); @@ -2585,7 +2578,7 @@ void tcg_gen_gvec_shli(unsigned vece, uint32_t dofs, uint32_t aofs, int64_t shif .fniv = tcg_gen_shli_vec, .fno = gen_helper_gvec_shl64i, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -2644,7 +2637,7 @@ void tcg_gen_gvec_shri(unsigned vece, uint32_t dofs, uint32_t aofs, int64_t shif .fniv = tcg_gen_shri_vec, .fno = gen_helper_gvec_shr64i, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -2731,7 +2724,7 @@ void tcg_gen_gvec_sari(unsigned vece, uint32_t dofs, uint32_t aofs, int64_t shif .fniv = tcg_gen_sari_vec, .fno = gen_helper_gvec_sar64i, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -2786,7 +2779,7 @@ void tcg_gen_gvec_rotli(unsigned vece, uint32_t dofs, uint32_t aofs, int64_t shi .fniv = tcg_gen_rotli_vec, .fno = gen_helper_gvec_rotl64i, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -3083,7 +3076,7 @@ void tcg_gen_gvec_shlv(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bof .fniv = tcg_gen_shlv_mod_vec, .fno = gen_helper_gvec_shl64v, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -3134,7 +3127,7 @@ void tcg_gen_gvec_shrv(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bof .fniv = tcg_gen_shrv_mod_vec, .fno = gen_helper_gvec_shr64v, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -3185,7 +3178,7 @@ void tcg_gen_gvec_sarv(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bof .fniv = tcg_gen_sarv_mod_vec, .fno = gen_helper_gvec_sar64v, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -3236,7 +3229,7 @@ void tcg_gen_gvec_rotlv(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bo .fniv = tcg_gen_rotlv_mod_vec, .fno = gen_helper_gvec_rotl64v, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -3283,7 +3276,7 @@ void tcg_gen_gvec_rotrv(unsigned vece, uint32_t dofs, uint32_t aofs, uint32_t bo .fniv = tcg_gen_rotrv_mod_vec, .fno = gen_helper_gvec_rotr64v, .opt_opc = vecop_list, - .prefer_i64 = TCG_TARGET_REG_BITS == 64, + .prefer_i64 = true, .vece = MO_64}, }; @@ -3369,11 +3362,11 @@ void tcg_gen_gvec_cmp(TCGCond cond, unsigned vece, uint32_t dofs, uint32_t aofs, } /* - * Implement inline with a vector type, if possible. - * Prefer integer when 64-bit host and 64-bit comparison. + * Implement inline with a vector type, if possible; + * prefer_i64 for a 64-bit comparison. */ hold_list = tcg_swap_vecop_list(cmp_list); - type = choose_vector_type(cmp_list, vece, oprsz, TCG_TARGET_REG_BITS == 64 && vece == MO_64); + type = choose_vector_type(cmp_list, vece, oprsz, vece == MO_64); switch (type) { case TCG_TYPE_V256: /* Recall that ARM SVE allows vector sizes that are not a @@ -3470,10 +3463,10 @@ void tcg_gen_gvec_cmps(TCGCond cond, unsigned vece, uint32_t dofs, uint32_t aofs } /* - * Implement inline with a vector type, if possible. - * Prefer integer when 64-bit host and 64-bit comparison. + * Implement inline with a vector type, if possible; + * prefer_i64 for a 64-bit comparison. */ - type = choose_vector_type(cmp_list, vece, oprsz, TCG_TARGET_REG_BITS == 64 && vece == MO_64); + type = choose_vector_type(cmp_list, vece, oprsz, vece == MO_64); if (type != 0) { const TCGOpcode *hold_list = tcg_swap_vecop_list(cmp_list); TCGv_vec t_vec = tcg_temp_new_vec(type); diff --git a/libtcg/src/tcg-op-gvec.h b/libtcg/src/tcg-op-gvec.h index aeac653c2..1f7dd3384 100644 --- a/libtcg/src/tcg-op-gvec.h +++ b/libtcg/src/tcg-op-gvec.h @@ -15,33 +15,9 @@ #endif #if TARGET_LONG_BITS == 64 -#define tcg_gen_gvec_dup_tl tcg_gen_gvec_dup_i64 -#define tcg_gen_vec_add8_tl tcg_gen_vec_add8_i64 -#define tcg_gen_vec_sub8_tl tcg_gen_vec_sub8_i64 -#define tcg_gen_vec_add16_tl tcg_gen_vec_add16_i64 -#define tcg_gen_vec_sub16_tl tcg_gen_vec_sub16_i64 -#define tcg_gen_vec_add32_tl tcg_gen_vec_add32_i64 -#define tcg_gen_vec_sub32_tl tcg_gen_vec_sub32_i64 -#define tcg_gen_vec_shl8i_tl tcg_gen_vec_shl8i_i64 -#define tcg_gen_vec_shr8i_tl tcg_gen_vec_shr8i_i64 -#define tcg_gen_vec_sar8i_tl tcg_gen_vec_sar8i_i64 -#define tcg_gen_vec_shl16i_tl tcg_gen_vec_shl16i_i64 -#define tcg_gen_vec_shr16i_tl tcg_gen_vec_shr16i_i64 -#define tcg_gen_vec_sar16i_tl tcg_gen_vec_sar16i_i64 +#define tcg_gen_gvec_dup_tl tcg_gen_gvec_dup_i64 #elif TARGET_LONG_BITS == 32 -#define tcg_gen_gvec_dup_tl tcg_gen_gvec_dup_i32 -#define tcg_gen_vec_add8_tl tcg_gen_vec_add8_i32 -#define tcg_gen_vec_sub8_tl tcg_gen_vec_sub8_i32 -#define tcg_gen_vec_add16_tl tcg_gen_vec_add16_i32 -#define tcg_gen_vec_sub16_tl tcg_gen_vec_sub16_i32 -#define tcg_gen_vec_add32_tl tcg_gen_add_i32 -#define tcg_gen_vec_sub32_tl tcg_gen_sub_i32 -#define tcg_gen_vec_shl8i_tl tcg_gen_vec_shl8i_i32 -#define tcg_gen_vec_shr8i_tl tcg_gen_vec_shr8i_i32 -#define tcg_gen_vec_sar8i_tl tcg_gen_vec_sar8i_i32 -#define tcg_gen_vec_shl16i_tl tcg_gen_vec_shl16i_i32 -#define tcg_gen_vec_shr16i_tl tcg_gen_vec_shr16i_i32 -#define tcg_gen_vec_sar16i_tl tcg_gen_vec_sar16i_i32 +#define tcg_gen_gvec_dup_tl tcg_gen_gvec_dup_i32 #else #error #endif diff --git a/libtcg/src/tcg-op-ldst.c b/libtcg/src/tcg-op-ldst.c index 911f02ee9..76787a6e7 100644 --- a/libtcg/src/tcg-op-ldst.c +++ b/libtcg/src/tcg-op-ldst.c @@ -31,7 +31,7 @@ #include #include #include -#include +#include #include #include // clang-format on @@ -102,19 +102,11 @@ static void gen_ldst2(TCGOpcode opc, TCGType type, TCGTemp *vl, TCGTemp *vh, TCG } static void gen_ld_i64(TCGv_i64 v, TCGTemp *addr, MemOpIdx oi) { - if (TCG_TARGET_REG_BITS == 32) { - gen_ldst2(INDEX_op_qemu_ld2, TCG_TYPE_I64, tcgv_i32_temp(TCGV_LOW(v)), tcgv_i32_temp(TCGV_HIGH(v)), addr, oi); - } else { - gen_ldst1(INDEX_op_qemu_ld, TCG_TYPE_I64, tcgv_i64_temp(v), addr, oi); - } + gen_ldst1(INDEX_op_qemu_ld, TCG_TYPE_I64, tcgv_i64_temp(v), addr, oi); } static void gen_st_i64(TCGv_i64 v, TCGTemp *addr, MemOpIdx oi) { - if (TCG_TARGET_REG_BITS == 32) { - gen_ldst2(INDEX_op_qemu_st2, TCG_TYPE_I64, tcgv_i32_temp(TCGV_LOW(v)), tcgv_i32_temp(TCGV_HIGH(v)), addr, oi); - } else { - gen_ldst1(INDEX_op_qemu_st, TCG_TYPE_I64, tcgv_i64_temp(v), addr, oi); - } + gen_ldst1(INDEX_op_qemu_st, TCG_TYPE_I64, tcgv_i64_temp(v), addr, oi); } static void tcg_gen_req_mo(TCGBar type) { @@ -132,7 +124,7 @@ static TCGTemp *tci_extend_addr(TCGTemp *addr) { * Compare to the extension performed by tcg_out_{ld,st}_helper_args * for native code generation. */ - if (TCG_TARGET_REG_BITS == 64 && tcg_ctx->addr_type == TCG_TYPE_I32) { + if (tcg_ctx->addr_type == TCG_TYPE_I32) { TCGv_i64 temp = tcg_temp_ebb_new_i64(); tcg_gen_extu_i32_i64(temp, temp_tcgv_i32(addr)); return tcgv_i64_temp(temp); @@ -240,8 +232,6 @@ static void tcg_gen_qemu_ld_i32_int(TCGv_i32 val, TCGTemp *addr, TCGArg idx, Mem addr_new = tci_extend_addr(addr); copy_addr = plugin_maybe_preserve_addr(addr); gen_ldst1(INDEX_op_qemu_ld, TCG_TYPE_I32, tcgv_i32_temp(val), addr_new, oi); - plugin_gen_mem_callbacks_i32(val, copy_addr, addr, orig_oi, QEMU_PLUGIN_MEM_R); - maybe_free_addr(addr, addr_new); if ((orig_memop ^ memop) & MO_BSWAP) { switch (orig_memop & MO_SIZE) { @@ -256,6 +246,9 @@ static void tcg_gen_qemu_ld_i32_int(TCGv_i32 val, TCGTemp *addr, TCGArg idx, Mem g_assert_not_reached(); } } + + plugin_gen_mem_callbacks_i32(val, copy_addr, addr, orig_oi, QEMU_PLUGIN_MEM_R); + maybe_free_addr(addr, addr_new); } void tcg_gen_qemu_ld_i32_chk(TCGv_i32 val, TCGTemp *addr, TCGArg idx, MemOp memop, TCGType addr_type) { @@ -264,8 +257,8 @@ void tcg_gen_qemu_ld_i32_chk(TCGv_i32 val, TCGTemp *addr, TCGArg idx, MemOp memo tcg_gen_qemu_ld_i32_int(val, addr, idx, memop); } -static void tcg_gen_qemu_st_i32_int(TCGv_i32 val, TCGTemp *addr, TCGArg idx, MemOp memop) { - TCGv_i32 swap = NULL; +static void tcg_gen_qemu_st_i32_int(TCGv_i32 orig_val, TCGTemp *addr, TCGArg idx, MemOp memop) { + TCGv_i32 val = orig_val; MemOpIdx orig_oi, oi; TCGTemp *addr_new; @@ -274,29 +267,28 @@ static void tcg_gen_qemu_st_i32_int(TCGv_i32 val, TCGTemp *addr, TCGArg idx, Mem orig_oi = oi = make_memop_idx(memop, idx); if ((memop & MO_BSWAP) && !tcg_target_has_memory_bswap(memop)) { - swap = tcg_temp_ebb_new_i32(); + val = tcg_temp_ebb_new_i32(); switch (memop & MO_SIZE) { case MO_16: - tcg_gen_bswap16_i32(swap, val, 0); + tcg_gen_bswap16_i32(val, orig_val, 0); break; case MO_32: - tcg_gen_bswap32_i32(swap, val); + tcg_gen_bswap32_i32(val, orig_val); break; default: g_assert_not_reached(); } - val = swap; memop &= ~MO_BSWAP; oi = make_memop_idx(memop, idx); } addr_new = tci_extend_addr(addr); gen_ldst1(INDEX_op_qemu_st, TCG_TYPE_I32, tcgv_i32_temp(val), addr_new, oi); - plugin_gen_mem_callbacks_i32(val, NULL, addr, orig_oi, QEMU_PLUGIN_MEM_W); + plugin_gen_mem_callbacks_i32(orig_val, NULL, addr, orig_oi, QEMU_PLUGIN_MEM_W); maybe_free_addr(addr, addr_new); - if (swap) { - tcg_temp_free_i32(swap); + if (val != orig_val) { + tcg_temp_free_i32(val); } } @@ -312,16 +304,6 @@ static void tcg_gen_qemu_ld_i64_int(TCGv_i64 val, TCGTemp *addr, TCGArg idx, Mem TCGv_i64 copy_addr; TCGTemp *addr_new; - if (TCG_TARGET_REG_BITS == 32 && (memop & MO_SIZE) < MO_64) { - tcg_gen_qemu_ld_i32_int(TCGV_LOW(val), addr, idx, memop); - if (memop & MO_SIGN) { - tcg_gen_sari_i32(TCGV_HIGH(val), TCGV_LOW(val), 31); - } else { - tcg_gen_movi_i32(TCGV_HIGH(val), 0); - } - return; - } - tcg_gen_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD); orig_memop = memop = tcg_canonicalize_memop(memop, 1, 0); orig_oi = oi = make_memop_idx(memop, idx); @@ -338,8 +320,6 @@ static void tcg_gen_qemu_ld_i64_int(TCGv_i64 val, TCGTemp *addr, TCGArg idx, Mem addr_new = tci_extend_addr(addr); copy_addr = plugin_maybe_preserve_addr(addr); gen_ld_i64(val, addr_new, oi); - plugin_gen_mem_callbacks_i64(val, copy_addr, addr, orig_oi, QEMU_PLUGIN_MEM_R); - maybe_free_addr(addr, addr_new); if ((orig_memop ^ memop) & MO_BSWAP) { int flags = (orig_memop & MO_SIGN ? TCG_BSWAP_IZ | TCG_BSWAP_OS : TCG_BSWAP_IZ | TCG_BSWAP_OZ); @@ -357,6 +337,9 @@ static void tcg_gen_qemu_ld_i64_int(TCGv_i64 val, TCGTemp *addr, TCGArg idx, Mem g_assert_not_reached(); } } + + plugin_gen_mem_callbacks_i64(val, copy_addr, addr, orig_oi, QEMU_PLUGIN_MEM_R); + maybe_free_addr(addr, addr_new); } void tcg_gen_qemu_ld_i64_chk(TCGv_i64 val, TCGTemp *addr, TCGArg idx, MemOp memop, TCGType addr_type) { @@ -365,47 +348,41 @@ void tcg_gen_qemu_ld_i64_chk(TCGv_i64 val, TCGTemp *addr, TCGArg idx, MemOp memo tcg_gen_qemu_ld_i64_int(val, addr, idx, memop); } -static void tcg_gen_qemu_st_i64_int(TCGv_i64 val, TCGTemp *addr, TCGArg idx, MemOp memop) { - TCGv_i64 swap = NULL; +static void tcg_gen_qemu_st_i64_int(TCGv_i64 orig_val, TCGTemp *addr, TCGArg idx, MemOp memop) { + TCGv_i64 val = orig_val; MemOpIdx orig_oi, oi; TCGTemp *addr_new; - if (TCG_TARGET_REG_BITS == 32 && (memop & MO_SIZE) < MO_64) { - tcg_gen_qemu_st_i32_int(TCGV_LOW(val), addr, idx, memop); - return; - } - tcg_gen_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST); memop = tcg_canonicalize_memop(memop, 1, 1); orig_oi = oi = make_memop_idx(memop, idx); if ((memop & MO_BSWAP) && !tcg_target_has_memory_bswap(memop)) { - swap = tcg_temp_ebb_new_i64(); + val = tcg_temp_ebb_new_i64(); switch (memop & MO_SIZE) { case MO_16: - tcg_gen_bswap16_i64(swap, val, 0); + tcg_gen_bswap16_i64(val, orig_val, 0); break; case MO_32: - tcg_gen_bswap32_i64(swap, val, 0); + tcg_gen_bswap32_i64(val, orig_val, 0); break; case MO_64: - tcg_gen_bswap64_i64(swap, val); + tcg_gen_bswap64_i64(val, orig_val); break; default: g_assert_not_reached(); } - val = swap; memop &= ~MO_BSWAP; oi = make_memop_idx(memop, idx); } addr_new = tci_extend_addr(addr); gen_st_i64(val, addr_new, oi); - plugin_gen_mem_callbacks_i64(val, NULL, addr, orig_oi, QEMU_PLUGIN_MEM_W); + plugin_gen_mem_callbacks_i64(orig_val, NULL, addr, orig_oi, QEMU_PLUGIN_MEM_W); maybe_free_addr(addr, addr_new); - if (swap) { - tcg_temp_free_i64(swap); + if (val != orig_val) { + tcg_temp_free_i64(val); } } @@ -518,7 +495,7 @@ static void tcg_gen_qemu_ld_i128_int(TCGv_i128 val, TCGTemp *addr, TCGArg idx, M orig_oi = make_memop_idx(memop, idx); /* TODO: For now, force 32-bit hosts to use the helper. */ - if (TCG_TARGET_HAS_qemu_ldst_i128 && TCG_TARGET_REG_BITS == 64) { + if (TCG_TARGET_HAS_qemu_ldst_i128) { TCGv_i64 lo, hi; bool need_bswap = false; MemOpIdx oi = orig_oi; @@ -625,7 +602,7 @@ static void tcg_gen_qemu_st_i128_int(TCGv_i128 val, TCGTemp *addr, TCGArg idx, M /* TODO: For now, force 32-bit hosts to use the helper. */ - if (TCG_TARGET_HAS_qemu_ldst_i128 && TCG_TARGET_REG_BITS == 64) { + if (TCG_TARGET_HAS_qemu_ldst_i128) { TCGv_i64 lo, hi; MemOpIdx oi = orig_oi; bool need_bswap = false; @@ -773,11 +750,6 @@ typedef void (*gen_atomic_op_i32)(TCGv_i32, TCGv_env, TCGv_i64, TCGv_i32, TCGv_i typedef void (*gen_atomic_op_i64)(TCGv_i64, TCGv_env, TCGv_i64, TCGv_i64, TCGv_i32); typedef void (*gen_atomic_op_i128)(TCGv_i128, TCGv_env, TCGv_i64, TCGv_i128, TCGv_i32); -#ifdef CONFIG_ATOMIC64 -#define WITH_ATOMIC64(X) X, -#else -#define WITH_ATOMIC64(X) -#endif #if HAVE_CMPXCHG128 #define WITH_ATOMIC128(X) X, #else @@ -790,10 +762,10 @@ static void *const table_cmpxchg[(MO_SIZE | MO_BSWAP) + 1] = { [MO_16 | MO_BE] = gen_helper_atomic_cmpxchgw_be, [MO_32 | MO_LE] = gen_helper_atomic_cmpxchgl_le, [MO_32 | MO_BE] = gen_helper_atomic_cmpxchgl_be, - WITH_ATOMIC64([MO_64 | MO_LE] = gen_helper_atomic_cmpxchgq_le) - WITH_ATOMIC64([MO_64 | MO_BE] = gen_helper_atomic_cmpxchgq_be) - WITH_ATOMIC128([MO_128 | MO_LE] = gen_helper_atomic_cmpxchgo_le) - WITH_ATOMIC128([MO_128 | MO_BE] = gen_helper_atomic_cmpxchgo_be)}; + [MO_64 | MO_LE] = gen_helper_atomic_cmpxchgq_le, + [MO_64 | MO_BE] = gen_helper_atomic_cmpxchgq_be, + WITH_ATOMIC128([MO_128 | MO_LE] = gen_helper_atomic_cmpxchgo_le) + WITH_ATOMIC128([MO_128 | MO_BE] = gen_helper_atomic_cmpxchgo_be)}; static void tcg_gen_nonatomic_cmpxchg_i32_int(TCGv_i32 retv, TCGTemp *addr, TCGv_i32 cmpv, TCGv_i32 newv, TCGArg idx, MemOp memop) { @@ -858,16 +830,6 @@ static void tcg_gen_nonatomic_cmpxchg_i64_int(TCGv_i64 retv, TCGTemp *addr, TCGv MemOp memop) { TCGv_i64 t1, t2; - if (TCG_TARGET_REG_BITS == 32 && (memop & MO_SIZE) < MO_64) { - tcg_gen_nonatomic_cmpxchg_i32_int(TCGV_LOW(retv), addr, TCGV_LOW(cmpv), TCGV_LOW(newv), idx, memop); - if (memop & MO_SIGN) { - tcg_gen_sari_i32(TCGV_HIGH(retv), TCGV_LOW(retv), 31); - } else { - tcg_gen_movi_i32(TCGV_HIGH(retv), 0); - } - return; - } - t1 = tcg_temp_ebb_new_i64(); t2 = tcg_temp_ebb_new_i64(); @@ -921,16 +883,6 @@ static void tcg_gen_atomic_cmpxchg_i64_int(TCGv_i64 retv, TCGTemp *addr, TCGv_i6 * is removed. */ tcg_gen_movi_i64(retv, 0); - return; - } - - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_atomic_cmpxchg_i32_int(TCGV_LOW(retv), addr, TCGV_LOW(cmpv), TCGV_LOW(newv), idx, memop); - if (memop & MO_SIGN) { - tcg_gen_sari_i32(TCGV_HIGH(retv), TCGV_LOW(retv), 31); - } else { - tcg_gen_movi_i32(TCGV_HIGH(retv), 0); - } } else { TCGv_i32 c32 = tcg_temp_ebb_new_i32(); TCGv_i32 n32 = tcg_temp_ebb_new_i32(); @@ -960,40 +912,31 @@ void tcg_gen_atomic_cmpxchg_i64_chk(TCGv_i64 retv, TCGTemp *addr, TCGv_i64 cmpv, static void tcg_gen_nonatomic_cmpxchg_i128_int(TCGv_i128 retv, TCGTemp *addr, TCGv_i128 cmpv, TCGv_i128 newv, TCGArg idx, MemOp memop) { - if (TCG_TARGET_REG_BITS == 32) { - /* Inline expansion below is simply too large for 32-bit hosts. */ - MemOpIdx oi = make_memop_idx(memop, idx); - TCGv_i64 a64 = maybe_extend_addr64(addr); + TCGv_i128 oldv = tcg_temp_ebb_new_i128(); + TCGv_i128 tmpv = tcg_temp_ebb_new_i128(); + TCGv_i64 t0 = tcg_temp_ebb_new_i64(); + TCGv_i64 t1 = tcg_temp_ebb_new_i64(); + TCGv_i64 z = tcg_constant_i64(0); - gen_helper_nonatomic_cmpxchgo(retv, tcg_env, a64, cmpv, newv, tcg_constant_i32(oi)); - maybe_free_addr64(a64); - } else { - TCGv_i128 oldv = tcg_temp_ebb_new_i128(); - TCGv_i128 tmpv = tcg_temp_ebb_new_i128(); - TCGv_i64 t0 = tcg_temp_ebb_new_i64(); - TCGv_i64 t1 = tcg_temp_ebb_new_i64(); - TCGv_i64 z = tcg_constant_i64(0); - - tcg_gen_qemu_ld_i128_int(oldv, addr, idx, memop); - - /* Compare i128 */ - tcg_gen_xor_i64(t0, TCGV128_LOW(oldv), TCGV128_LOW(cmpv)); - tcg_gen_xor_i64(t1, TCGV128_HIGH(oldv), TCGV128_HIGH(cmpv)); - tcg_gen_or_i64(t0, t0, t1); - - /* tmpv = equal ? newv : oldv */ - tcg_gen_movcond_i64(TCG_COND_EQ, TCGV128_LOW(tmpv), t0, z, TCGV128_LOW(newv), TCGV128_LOW(oldv)); - tcg_gen_movcond_i64(TCG_COND_EQ, TCGV128_HIGH(tmpv), t0, z, TCGV128_HIGH(newv), TCGV128_HIGH(oldv)); - - /* Unconditional writeback. */ - tcg_gen_qemu_st_i128_int(tmpv, addr, idx, memop); - tcg_gen_mov_i128(retv, oldv); - - tcg_temp_free_i64(t0); - tcg_temp_free_i64(t1); - tcg_temp_free_i128(tmpv); - tcg_temp_free_i128(oldv); - } + tcg_gen_qemu_ld_i128_int(oldv, addr, idx, memop); + + /* Compare i128 */ + tcg_gen_xor_i64(t0, TCGV128_LOW(oldv), TCGV128_LOW(cmpv)); + tcg_gen_xor_i64(t1, TCGV128_HIGH(oldv), TCGV128_HIGH(cmpv)); + tcg_gen_or_i64(t0, t0, t1); + + /* tmpv = equal ? newv : oldv */ + tcg_gen_movcond_i64(TCG_COND_EQ, TCGV128_LOW(tmpv), t0, z, TCGV128_LOW(newv), TCGV128_LOW(oldv)); + tcg_gen_movcond_i64(TCG_COND_EQ, TCGV128_HIGH(tmpv), t0, z, TCGV128_HIGH(newv), TCGV128_HIGH(oldv)); + + /* Unconditional writeback. */ + tcg_gen_qemu_st_i128_int(tmpv, addr, idx, memop); + tcg_gen_mov_i128(retv, oldv); + + tcg_temp_free_i64(t0); + tcg_temp_free_i64(t1); + tcg_temp_free_i128(tmpv); + tcg_temp_free_i128(oldv); } void tcg_gen_nonatomic_cmpxchg_i128_chk(TCGv_i128 retv, TCGTemp *addr, TCGv_i128 cmpv, TCGv_i128 newv, TCGArg idx, @@ -1168,10 +1111,10 @@ static void do_atomic_op_i128(TCGv_i128 ret, TCGTemp *addr, TCGv_i128 val, TCGAr [MO_16 | MO_BE] = gen_helper_atomic_##NAME##w_be, \ [MO_32 | MO_LE] = gen_helper_atomic_##NAME##l_le, \ [MO_32 | MO_BE] = gen_helper_atomic_##NAME##l_be, \ - WITH_ATOMIC64([MO_64 | MO_LE] = gen_helper_atomic_##NAME##q_le) \ - WITH_ATOMIC64([MO_64 | MO_BE] = gen_helper_atomic_##NAME##q_be) \ - WITH_ATOMIC128([MO_128 | MO_LE] = gen_helper_atomic_##NAME##o_le) \ - WITH_ATOMIC128([MO_128 | MO_BE] = gen_helper_atomic_##NAME##o_be)}; \ + [MO_64 | MO_LE] = gen_helper_atomic_##NAME##q_le, \ + [MO_64 | MO_BE] = gen_helper_atomic_##NAME##q_be, \ + WITH_ATOMIC128([MO_128 | MO_LE] = gen_helper_atomic_##NAME##o_le) \ + WITH_ATOMIC128([MO_128 | MO_BE] = gen_helper_atomic_##NAME##o_be)}; \ void tcg_gen_atomic_##NAME##_i32_chk(TCGv_i32 ret, TCGTemp *addr, TCGv_i32 val, TCGArg idx, MemOp memop, \ TCGType addr_type) { \ tcg_debug_assert(addr_type == tcg_ctx->addr_type); \ @@ -1210,8 +1153,9 @@ static void do_atomic_op_i128(TCGv_i128 ret, TCGTemp *addr, TCGv_i128 val, TCGAr [MO_16 | MO_BE] = gen_helper_atomic_##NAME##w_be, \ [MO_32 | MO_LE] = gen_helper_atomic_##NAME##l_le, \ [MO_32 | MO_BE] = gen_helper_atomic_##NAME##l_be, \ - WITH_ATOMIC64([MO_64 | MO_LE] = gen_helper_atomic_##NAME##q_le) \ - WITH_ATOMIC64([MO_64 | MO_BE] = gen_helper_atomic_##NAME##q_be)}; \ + [MO_64 | MO_LE] = gen_helper_atomic_##NAME##q_le, \ + [MO_64 | MO_BE] = gen_helper_atomic_##NAME##q_be, \ + }; \ void tcg_gen_atomic_##NAME##_i32_chk(TCGv_i32 ret, TCGTemp *addr, TCGv_i32 val, TCGArg idx, MemOp memop, \ TCGType addr_type) { \ tcg_debug_assert(addr_type == tcg_ctx->addr_type); \ diff --git a/libtcg/src/tcg-op-vec.c b/libtcg/src/tcg-op-vec.c index fcec02910..2f3c167de 100644 --- a/libtcg/src/tcg-op-vec.c +++ b/libtcg/src/tcg-op-vec.c @@ -74,7 +74,6 @@ bool tcg_can_emit_vecop_list(const TCGOpcode *list, TCGType type, unsigned vece) case INDEX_op_xor_vec: case INDEX_op_mov_vec: case INDEX_op_dup_vec: - case INDEX_op_dup2_vec: case INDEX_op_ld_vec: case INDEX_op_st_vec: case INDEX_op_bitsel_vec: @@ -214,20 +213,11 @@ void tcg_gen_dupi_vec(unsigned vece, TCGv_vec r, uint64_t a) { void tcg_gen_dup_i64_vec(unsigned vece, TCGv_vec r, TCGv_i64 a) { TCGArg ri = tcgv_vec_arg(r); + TCGArg ai = tcgv_i64_arg(a); TCGTemp *rt = arg_temp(ri); TCGType type = rt->base_type; - if (TCG_TARGET_REG_BITS == 64) { - TCGArg ai = tcgv_i64_arg(a); - vec_gen_2(INDEX_op_dup_vec, type, vece, ri, ai); - } else if (vece == MO_64) { - TCGArg al = tcgv_i32_arg(TCGV_LOW(a)); - TCGArg ah = tcgv_i32_arg(TCGV_HIGH(a)); - vec_gen_3(INDEX_op_dup2_vec, type, MO_64, ri, al, ah); - } else { - TCGArg ai = tcgv_i32_arg(TCGV_LOW(a)); - vec_gen_2(INDEX_op_dup_vec, type, vece, ri, ai); - } + vec_gen_2(INDEX_op_dup_vec, type, vece, ri, ai); } void tcg_gen_dup_i32_vec(unsigned vece, TCGv_vec r, TCGv_i32 a) { diff --git a/libtcg/src/tcg-op.c b/libtcg/src/tcg-op.c index d2420b74c..78d6de74a 100644 --- a/libtcg/src/tcg-op.c +++ b/libtcg/src/tcg-op.c @@ -208,12 +208,6 @@ static void DNI tcg_gen_op6i_i64(TCGOpcode opc, TCGv_i64 a1, TCGv_i64 a2, TCGv_i tcgv_i64_arg(a5), a6); } -static TCGOp *DNI tcg_gen_op6ii_i32(TCGOpcode opc, TCGv_i32 a1, TCGv_i32 a2, TCGv_i32 a3, TCGv_i32 a4, TCGArg a5, - TCGArg a6) { - return tcg_gen_op6(opc, TCG_TYPE_I32, tcgv_i32_arg(a1), tcgv_i32_arg(a2), tcgv_i32_arg(a3), tcgv_i32_arg(a4), a5, - a6); -} - /* Generic ops. */ void gen_set_label(TCGLabel *l) { @@ -715,23 +709,12 @@ void tcg_gen_rotl_i32(TCGv_i32 ret, TCGv_i32 arg1, TCGv_i32 arg2) { void tcg_gen_rotli_i32(TCGv_i32 ret, TCGv_i32 arg1, int32_t arg2) { tcg_debug_assert(arg2 >= 0 && arg2 < 32); - /* some cases can be optimized here */ if (arg2 == 0) { tcg_gen_mov_i32(ret, arg1); } else if (tcg_op_supported(INDEX_op_rotl, TCG_TYPE_I32, 0)) { - TCGv_i32 t0 = tcg_constant_i32(arg2); - tcg_gen_op3_i32(INDEX_op_rotl, ret, arg1, t0); - } else if (tcg_op_supported(INDEX_op_rotr, TCG_TYPE_I32, 0)) { - TCGv_i32 t0 = tcg_constant_i32(32 - arg2); - tcg_gen_op3_i32(INDEX_op_rotr, ret, arg1, t0); + tcg_gen_op3_i32(INDEX_op_rotl, ret, arg1, tcg_constant_i32(arg2)); } else { - TCGv_i32 t0 = tcg_temp_ebb_new_i32(); - TCGv_i32 t1 = tcg_temp_ebb_new_i32(); - tcg_gen_shli_i32(t0, arg1, arg2); - tcg_gen_shri_i32(t1, arg1, 32 - arg2); - tcg_gen_or_i32(ret, t0, t1); - tcg_temp_free_i32(t0); - tcg_temp_free_i32(t1); + tcg_gen_rotri_i32(ret, arg1, -arg2 & 31); } } @@ -757,13 +740,19 @@ void tcg_gen_rotr_i32(TCGv_i32 ret, TCGv_i32 arg1, TCGv_i32 arg2) { void tcg_gen_rotri_i32(TCGv_i32 ret, TCGv_i32 arg1, int32_t arg2) { tcg_debug_assert(arg2 >= 0 && arg2 < 32); - tcg_gen_rotli_i32(ret, arg1, -arg2 & 31); + if (arg2 == 0) { + tcg_gen_mov_i32(ret, arg1); + } else if (tcg_op_supported(INDEX_op_rotr, TCG_TYPE_I32, 0)) { + tcg_gen_op3_i32(INDEX_op_rotr, ret, arg1, tcg_constant_i32(arg2)); + } else if (tcg_op_supported(INDEX_op_rotl, TCG_TYPE_I32, 0)) { + tcg_gen_op3_i32(INDEX_op_rotl, ret, arg1, tcg_constant_i32(32 - arg2)); + } else { + /* Do not recurse with the rotri simplification. */ + tcg_gen_op4i_i32(INDEX_op_extract2, ret, arg1, arg1, arg2); + } } void tcg_gen_deposit_i32(TCGv_i32 ret, TCGv_i32 arg1, TCGv_i32 arg2, unsigned int ofs, unsigned int len) { - uint32_t mask; - TCGv_i32 t1; - tcg_debug_assert(ofs < 32); tcg_debug_assert(len > 0); tcg_debug_assert(len <= 32); @@ -771,39 +760,9 @@ void tcg_gen_deposit_i32(TCGv_i32 ret, TCGv_i32 arg1, TCGv_i32 arg2, unsigned in if (len == 32) { tcg_gen_mov_i32(ret, arg2); - return; - } - if (TCG_TARGET_deposit_valid(TCG_TYPE_I32, ofs, len)) { - tcg_gen_op5ii_i32(INDEX_op_deposit, ret, arg1, arg2, ofs, len); - return; - } - - t1 = tcg_temp_ebb_new_i32(); - - if (tcg_op_supported(INDEX_op_extract2, TCG_TYPE_I32, 0)) { - if (ofs + len == 32) { - tcg_gen_shli_i32(t1, arg1, len); - tcg_gen_extract2_i32(ret, t1, arg2, len); - goto done; - } - if (ofs == 0) { - tcg_gen_extract2_i32(ret, arg1, arg2, len); - tcg_gen_rotli_i32(ret, ret, len); - goto done; - } - } - - mask = (1u << len) - 1; - if (ofs + len < 32) { - tcg_gen_andi_i32(t1, arg2, mask); - tcg_gen_shli_i32(t1, t1, ofs); } else { - tcg_gen_shli_i32(t1, arg2, ofs); + tcg_gen_op5ii_i32(INDEX_op_deposit, ret, arg1, arg2, ofs, len); } - tcg_gen_andi_i32(ret, arg1, ~(mask << ofs)); - tcg_gen_or_i32(ret, ret, t1); -done: - tcg_temp_free_i32(t1); } void tcg_gen_deposit_z_i32(TCGv_i32 ret, TCGv_i32 arg, unsigned int ofs, unsigned int len) { @@ -815,32 +774,16 @@ void tcg_gen_deposit_z_i32(TCGv_i32 ret, TCGv_i32 arg, unsigned int ofs, unsigne if (ofs + len == 32) { tcg_gen_shli_i32(ret, arg, ofs); } else if (ofs == 0) { - tcg_gen_andi_i32(ret, arg, (1u << len) - 1); - } else if (TCG_TARGET_deposit_valid(TCG_TYPE_I32, ofs, len)) { + tcg_gen_extract_i32(ret, arg, 0, len); + } else { TCGv_i32 zero = tcg_constant_i32(0); tcg_gen_op5ii_i32(INDEX_op_deposit, ret, zero, arg, ofs, len); - } else { - /* - * To help two-operand hosts we prefer to zero-extend first, - * which allows ARG to stay live. - */ - if (TCG_TARGET_extract_valid(TCG_TYPE_I32, 0, len)) { - tcg_gen_extract_i32(ret, arg, 0, len); - tcg_gen_shli_i32(ret, ret, ofs); - return; - } - /* Otherwise prefer zero-extension over AND for code size. */ - if (TCG_TARGET_extract_valid(TCG_TYPE_I32, 0, ofs + len)) { - tcg_gen_shli_i32(ret, arg, ofs); - tcg_gen_extract_i32(ret, ret, 0, ofs + len); - return; - } - tcg_gen_andi_i32(ret, arg, (1u << len) - 1); - tcg_gen_shli_i32(ret, ret, ofs); } } void tcg_gen_extract_i32(TCGv_i32 ret, TCGv_i32 arg, unsigned int ofs, unsigned int len) { + uint32_t mask; + tcg_debug_assert(ofs < 32); tcg_debug_assert(len > 0); tcg_debug_assert(len <= 32); @@ -856,8 +799,10 @@ void tcg_gen_extract_i32(TCGv_i32 ret, TCGv_i32 arg, unsigned int ofs, unsigned tcg_gen_op4ii_i32(INDEX_op_extract, ret, arg, ofs, len); return; } + + mask = (1u << len) - 1; if (ofs == 0) { - tcg_gen_andi_i32(ret, arg, (1u << len) - 1); + tcg_gen_andi_i32(ret, arg, mask); return; } @@ -868,19 +813,12 @@ void tcg_gen_extract_i32(TCGv_i32 ret, TCGv_i32 arg, unsigned int ofs, unsigned return; } - /* ??? Ideally we'd know what values are available for immediate AND. - Assume that 8 bits are available, plus the special case of 16, - so that we get ext8u, ext16u. */ - switch (len) { - case 1 ... 8: - case 16: - tcg_gen_shri_i32(ret, arg, ofs); - tcg_gen_andi_i32(ret, ret, (1u << len) - 1); - break; - default: - tcg_gen_shli_i32(ret, arg, 32 - len - ofs); - tcg_gen_shri_i32(ret, ret, 32 - len); - break; + if (tcg_op_imm_match(INDEX_op_and, TCG_TYPE_I32, mask)) { + tcg_gen_shri_i32(ret, arg, ofs); + tcg_gen_andi_i32(ret, ret, mask); + } else { + tcg_gen_shli_i32(ret, arg, 32 - len - ofs); + tcg_gen_shri_i32(ret, ret, 32 - len); } } @@ -929,13 +867,8 @@ void tcg_gen_extract2_i32(TCGv_i32 ret, TCGv_i32 al, TCGv_i32 ah, unsigned int o tcg_gen_mov_i32(ret, ah); } else if (al == ah) { tcg_gen_rotri_i32(ret, al, ofs); - } else if (tcg_op_supported(INDEX_op_extract2, TCG_TYPE_I32, 0)) { - tcg_gen_op4i_i32(INDEX_op_extract2, ret, al, ah, ofs); } else { - TCGv_i32 t0 = tcg_temp_ebb_new_i32(); - tcg_gen_shri_i32(t0, al, ofs); - tcg_gen_deposit_i32(ret, t0, ah, 32 - ofs, ofs); - tcg_temp_free_i32(t0); + tcg_gen_op4i_i32(INDEX_op_extract2, ret, al, ah, ofs); } } @@ -1023,7 +956,7 @@ void tcg_gen_mulu2_i32(TCGv_i32 rl, TCGv_i32 rh, TCGv_i32 arg1, TCGv_i32 arg2) { tcg_gen_op3_i32(INDEX_op_muluh, rh, arg1, arg2); tcg_gen_mov_i32(rl, t); tcg_temp_free_i32(t); - } else if (TCG_TARGET_REG_BITS == 64) { + } else { TCGv_i64 t0 = tcg_temp_ebb_new_i64(); TCGv_i64 t1 = tcg_temp_ebb_new_i64(); tcg_gen_extu_i32_i64(t0, arg1); @@ -1032,8 +965,6 @@ void tcg_gen_mulu2_i32(TCGv_i32 rl, TCGv_i32 rh, TCGv_i32 arg1, TCGv_i32 arg2) { tcg_gen_extr_i64_i32(rl, rh, t0); tcg_temp_free_i64(t0); tcg_temp_free_i64(t1); - } else { - g_assert_not_reached(); } } @@ -1046,24 +977,6 @@ void tcg_gen_muls2_i32(TCGv_i32 rl, TCGv_i32 rh, TCGv_i32 arg1, TCGv_i32 arg2) { tcg_gen_op3_i32(INDEX_op_mulsh, rh, arg1, arg2); tcg_gen_mov_i32(rl, t); tcg_temp_free_i32(t); - } else if (TCG_TARGET_REG_BITS == 32) { - TCGv_i32 t0 = tcg_temp_ebb_new_i32(); - TCGv_i32 t1 = tcg_temp_ebb_new_i32(); - TCGv_i32 t2 = tcg_temp_ebb_new_i32(); - TCGv_i32 t3 = tcg_temp_ebb_new_i32(); - tcg_gen_mulu2_i32(t0, t1, arg1, arg2); - /* Adjust for negative inputs. */ - tcg_gen_sari_i32(t2, arg1, 31); - tcg_gen_sari_i32(t3, arg2, 31); - tcg_gen_and_i32(t2, t2, arg2); - tcg_gen_and_i32(t3, t3, arg1); - tcg_gen_sub_i32(rh, t1, t2); - tcg_gen_sub_i32(rh, rh, t3); - tcg_gen_mov_i32(rl, t0); - tcg_temp_free_i32(t0); - tcg_temp_free_i32(t1); - tcg_temp_free_i32(t2); - tcg_temp_free_i32(t3); } else { TCGv_i64 t0 = tcg_temp_ebb_new_i64(); TCGv_i64 t1 = tcg_temp_ebb_new_i64(); @@ -1077,29 +990,14 @@ void tcg_gen_muls2_i32(TCGv_i32 rl, TCGv_i32 rh, TCGv_i32 arg1, TCGv_i32 arg2) { } void tcg_gen_mulsu2_i32(TCGv_i32 rl, TCGv_i32 rh, TCGv_i32 arg1, TCGv_i32 arg2) { - if (TCG_TARGET_REG_BITS == 32) { - TCGv_i32 t0 = tcg_temp_ebb_new_i32(); - TCGv_i32 t1 = tcg_temp_ebb_new_i32(); - TCGv_i32 t2 = tcg_temp_ebb_new_i32(); - tcg_gen_mulu2_i32(t0, t1, arg1, arg2); - /* Adjust for negative input for the signed arg1. */ - tcg_gen_sari_i32(t2, arg1, 31); - tcg_gen_and_i32(t2, t2, arg2); - tcg_gen_sub_i32(rh, t1, t2); - tcg_gen_mov_i32(rl, t0); - tcg_temp_free_i32(t0); - tcg_temp_free_i32(t1); - tcg_temp_free_i32(t2); - } else { - TCGv_i64 t0 = tcg_temp_ebb_new_i64(); - TCGv_i64 t1 = tcg_temp_ebb_new_i64(); - tcg_gen_ext_i32_i64(t0, arg1); - tcg_gen_extu_i32_i64(t1, arg2); - tcg_gen_mul_i64(t0, t0, t1); - tcg_gen_extr_i64_i32(rl, rh, t0); - tcg_temp_free_i64(t0); - tcg_temp_free_i64(t1); - } + TCGv_i64 t0 = tcg_temp_ebb_new_i64(); + TCGv_i64 t1 = tcg_temp_ebb_new_i64(); + tcg_gen_ext_i32_i64(t0, arg1); + tcg_gen_extu_i32_i64(t1, arg2); + tcg_gen_mul_i64(t0, t0, t1); + tcg_gen_extr_i64_i32(rl, rh, t0); + tcg_temp_free_i64(t0); + tcg_temp_free_i64(t1); } void tcg_gen_ext8s_i32(TCGv_i32 ret, TCGv_i32 arg) { @@ -1259,261 +1157,113 @@ void tcg_gen_st_i32(TCGv_i32 arg1, TCGv_ptr arg2, tcg_target_long offset) { /* 64-bit ops */ void tcg_gen_discard_i64(TCGv_i64 arg) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op1_i64(INDEX_op_discard, TCG_TYPE_I64, arg); - } else { - tcg_gen_discard_i32(TCGV_LOW(arg)); - tcg_gen_discard_i32(TCGV_HIGH(arg)); - } + tcg_gen_op1_i64(INDEX_op_discard, TCG_TYPE_I64, arg); } void tcg_gen_mov_i64(TCGv_i64 ret, TCGv_i64 arg) { - if (ret == arg) { - return; - } - if (TCG_TARGET_REG_BITS == 64) { + if (ret != arg) { tcg_gen_op2_i64(INDEX_op_mov, ret, arg); - } else { - TCGTemp *ts = tcgv_i64_temp(arg); - - /* Canonicalize TCGv_i64 TEMP_CONST into TCGv_i32 TEMP_CONST. */ - if (ts->kind == TEMP_CONST) { - tcg_gen_movi_i64(ret, ts->val); - } else { - tcg_gen_mov_i32(TCGV_LOW(ret), TCGV_LOW(arg)); - tcg_gen_mov_i32(TCGV_HIGH(ret), TCGV_HIGH(arg)); - } } } void tcg_gen_movi_i64(TCGv_i64 ret, int64_t arg) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_mov_i64(ret, tcg_constant_i64(arg)); - } else { - tcg_gen_movi_i32(TCGV_LOW(ret), arg); - tcg_gen_movi_i32(TCGV_HIGH(ret), arg >> 32); - } + tcg_gen_mov_i64(ret, tcg_constant_i64(arg)); } void tcg_gen_ld8u_i64(TCGv_i64 ret, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_ld8u, ret, arg2, offset); - } else { - tcg_gen_ld8u_i32(TCGV_LOW(ret), arg2, offset); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } + tcg_gen_ldst_op_i64(INDEX_op_ld8u, ret, arg2, offset); } void tcg_gen_ld8s_i64(TCGv_i64 ret, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_ld8s, ret, arg2, offset); - } else { - tcg_gen_ld8s_i32(TCGV_LOW(ret), arg2, offset); - tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_LOW(ret), 31); - } + tcg_gen_ldst_op_i64(INDEX_op_ld8s, ret, arg2, offset); } void tcg_gen_ld16u_i64(TCGv_i64 ret, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_ld16u, ret, arg2, offset); - } else { - tcg_gen_ld16u_i32(TCGV_LOW(ret), arg2, offset); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } + tcg_gen_ldst_op_i64(INDEX_op_ld16u, ret, arg2, offset); } void tcg_gen_ld16s_i64(TCGv_i64 ret, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_ld16s, ret, arg2, offset); - } else { - tcg_gen_ld16s_i32(TCGV_LOW(ret), arg2, offset); - tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_LOW(ret), 31); - } + tcg_gen_ldst_op_i64(INDEX_op_ld16s, ret, arg2, offset); } void tcg_gen_ld32u_i64(TCGv_i64 ret, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_ld32u, ret, arg2, offset); - } else { - tcg_gen_ld_i32(TCGV_LOW(ret), arg2, offset); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } + tcg_gen_ldst_op_i64(INDEX_op_ld32u, ret, arg2, offset); } void tcg_gen_ld32s_i64(TCGv_i64 ret, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_ld32s, ret, arg2, offset); - } else { - tcg_gen_ld_i32(TCGV_LOW(ret), arg2, offset); - tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_LOW(ret), 31); - } + tcg_gen_ldst_op_i64(INDEX_op_ld32s, ret, arg2, offset); } void tcg_gen_ld_i64(TCGv_i64 ret, TCGv_ptr arg2, tcg_target_long offset) { - /* - * For 32-bit host, since arg2 and ret have different types, - * they cannot be the same temporary -- no chance of overlap. - */ - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_ld, ret, arg2, offset); - } else if (HOST_BIG_ENDIAN) { - tcg_gen_ld_i32(TCGV_HIGH(ret), arg2, offset); - tcg_gen_ld_i32(TCGV_LOW(ret), arg2, offset + 4); - } else { - tcg_gen_ld_i32(TCGV_LOW(ret), arg2, offset); - tcg_gen_ld_i32(TCGV_HIGH(ret), arg2, offset + 4); - } + tcg_gen_ldst_op_i64(INDEX_op_ld, ret, arg2, offset); } void tcg_gen_st8_i64(TCGv_i64 arg1, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_st8, arg1, arg2, offset); - } else { - tcg_gen_st8_i32(TCGV_LOW(arg1), arg2, offset); - } + tcg_gen_ldst_op_i64(INDEX_op_st8, arg1, arg2, offset); } void tcg_gen_st16_i64(TCGv_i64 arg1, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_st16, arg1, arg2, offset); - } else { - tcg_gen_st16_i32(TCGV_LOW(arg1), arg2, offset); - } + tcg_gen_ldst_op_i64(INDEX_op_st16, arg1, arg2, offset); } void tcg_gen_st32_i64(TCGv_i64 arg1, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_st32, arg1, arg2, offset); - } else { - tcg_gen_st_i32(TCGV_LOW(arg1), arg2, offset); - } + tcg_gen_ldst_op_i64(INDEX_op_st32, arg1, arg2, offset); } void tcg_gen_st_i64(TCGv_i64 arg1, TCGv_ptr arg2, tcg_target_long offset) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_ldst_op_i64(INDEX_op_st, arg1, arg2, offset); - } else if (HOST_BIG_ENDIAN) { - tcg_gen_st_i32(TCGV_HIGH(arg1), arg2, offset); - tcg_gen_st_i32(TCGV_LOW(arg1), arg2, offset + 4); - } else { - tcg_gen_st_i32(TCGV_LOW(arg1), arg2, offset); - tcg_gen_st_i32(TCGV_HIGH(arg1), arg2, offset + 4); - } + tcg_gen_ldst_op_i64(INDEX_op_st, arg1, arg2, offset); } void tcg_gen_add_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op3_i64(INDEX_op_add, ret, arg1, arg2); - } else { - tcg_gen_add2_i32(TCGV_LOW(ret), TCGV_HIGH(ret), TCGV_LOW(arg1), TCGV_HIGH(arg1), TCGV_LOW(arg2), - TCGV_HIGH(arg2)); - } + tcg_gen_op3_i64(INDEX_op_add, ret, arg1, arg2); } void tcg_gen_sub_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op3_i64(INDEX_op_sub, ret, arg1, arg2); - } else { - tcg_gen_sub2_i32(TCGV_LOW(ret), TCGV_HIGH(ret), TCGV_LOW(arg1), TCGV_HIGH(arg1), TCGV_LOW(arg2), - TCGV_HIGH(arg2)); - } + tcg_gen_op3_i64(INDEX_op_sub, ret, arg1, arg2); } void tcg_gen_and_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op3_i64(INDEX_op_and, ret, arg1, arg2); - } else { - tcg_gen_and_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_LOW(arg2)); - tcg_gen_and_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), TCGV_HIGH(arg2)); - } + tcg_gen_op3_i64(INDEX_op_and, ret, arg1, arg2); } void tcg_gen_or_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op3_i64(INDEX_op_or, ret, arg1, arg2); - } else { - tcg_gen_or_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_LOW(arg2)); - tcg_gen_or_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), TCGV_HIGH(arg2)); - } + tcg_gen_op3_i64(INDEX_op_or, ret, arg1, arg2); } void tcg_gen_xor_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op3_i64(INDEX_op_xor, ret, arg1, arg2); - } else { - tcg_gen_xor_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_LOW(arg2)); - tcg_gen_xor_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), TCGV_HIGH(arg2)); - } + tcg_gen_op3_i64(INDEX_op_xor, ret, arg1, arg2); } void tcg_gen_shl_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op3_i64(INDEX_op_shl, ret, arg1, arg2); - } else { - gen_helper_shl_i64(ret, arg1, arg2); - } + tcg_gen_op3_i64(INDEX_op_shl, ret, arg1, arg2); } void tcg_gen_shr_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op3_i64(INDEX_op_shr, ret, arg1, arg2); - } else { - gen_helper_shr_i64(ret, arg1, arg2); - } + tcg_gen_op3_i64(INDEX_op_shr, ret, arg1, arg2); } void tcg_gen_sar_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op3_i64(INDEX_op_sar, ret, arg1, arg2); - } else { - gen_helper_sar_i64(ret, arg1, arg2); - } + tcg_gen_op3_i64(INDEX_op_sar, ret, arg1, arg2); } void tcg_gen_mul_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - TCGv_i64 t0; - TCGv_i32 t1; - - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op3_i64(INDEX_op_mul, ret, arg1, arg2); - return; - } - - t0 = tcg_temp_ebb_new_i64(); - t1 = tcg_temp_ebb_new_i32(); - - tcg_gen_mulu2_i32(TCGV_LOW(t0), TCGV_HIGH(t0), TCGV_LOW(arg1), TCGV_LOW(arg2)); - - tcg_gen_mul_i32(t1, TCGV_LOW(arg1), TCGV_HIGH(arg2)); - tcg_gen_add_i32(TCGV_HIGH(t0), TCGV_HIGH(t0), t1); - tcg_gen_mul_i32(t1, TCGV_HIGH(arg1), TCGV_LOW(arg2)); - tcg_gen_add_i32(TCGV_HIGH(t0), TCGV_HIGH(t0), t1); - - tcg_gen_mov_i64(ret, t0); - tcg_temp_free_i64(t0); - tcg_temp_free_i32(t1); + tcg_gen_op3_i64(INDEX_op_mul, ret, arg1, arg2); } void tcg_gen_addi_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { /* some cases can be optimized here */ if (arg2 == 0) { tcg_gen_mov_i64(ret, arg1); - } else if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_add_i64(ret, arg1, tcg_constant_i64(arg2)); } else { - tcg_gen_add2_i32(TCGV_LOW(ret), TCGV_HIGH(ret), TCGV_LOW(arg1), TCGV_HIGH(arg1), tcg_constant_i32(arg2), - tcg_constant_i32(arg2 >> 32)); + tcg_gen_add_i64(ret, arg1, tcg_constant_i64(arg2)); } } void tcg_gen_subfi_i64(TCGv_i64 ret, int64_t arg1, TCGv_i64 arg2) { if (arg1 == 0) { tcg_gen_neg_i64(ret, arg2); - } else if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_sub_i64(ret, tcg_constant_i64(arg1), arg2); } else { - tcg_gen_sub2_i32(TCGV_LOW(ret), TCGV_HIGH(ret), tcg_constant_i32(arg1), tcg_constant_i32(arg1 >> 32), - TCGV_LOW(arg2), TCGV_HIGH(arg2)); + tcg_gen_sub_i64(ret, tcg_constant_i64(arg1), arg2); } } @@ -1522,21 +1272,10 @@ void tcg_gen_subi_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { } void tcg_gen_neg_i64(TCGv_i64 ret, TCGv_i64 arg) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op2_i64(INDEX_op_neg, ret, arg); - } else { - TCGv_i32 zero = tcg_constant_i32(0); - tcg_gen_sub2_i32(TCGV_LOW(ret), TCGV_HIGH(ret), zero, zero, TCGV_LOW(arg), TCGV_HIGH(arg)); - } + tcg_gen_op2_i64(INDEX_op_neg, ret, arg); } void tcg_gen_andi_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_andi_i32(TCGV_LOW(ret), TCGV_LOW(arg1), arg2); - tcg_gen_andi_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), arg2 >> 32); - return; - } - /* Some cases can be optimized here. */ switch (arg2) { case 0: @@ -1566,11 +1305,6 @@ void tcg_gen_andi_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { } void tcg_gen_ori_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_ori_i32(TCGV_LOW(ret), TCGV_LOW(arg1), arg2); - tcg_gen_ori_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), arg2 >> 32); - return; - } /* Some cases can be optimized here. */ if (arg2 == -1) { tcg_gen_movi_i64(ret, -1); @@ -1582,11 +1316,6 @@ void tcg_gen_ori_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { } void tcg_gen_xori_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_xori_i32(TCGV_LOW(ret), TCGV_LOW(arg1), arg2); - tcg_gen_xori_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), arg2 >> 32); - return; - } /* Some cases can be optimized here. */ if (arg2 == 0) { tcg_gen_mov_i64(ret, arg1); @@ -1598,43 +1327,9 @@ void tcg_gen_xori_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { } } -static inline void tcg_gen_shifti_i64(TCGv_i64 ret, TCGv_i64 arg1, unsigned c, bool right, bool arith) { - tcg_debug_assert(c < 64); - if (c == 0) { - tcg_gen_mov_i32(TCGV_LOW(ret), TCGV_LOW(arg1)); - tcg_gen_mov_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1)); - } else if (c >= 32) { - c -= 32; - if (right) { - if (arith) { - tcg_gen_sari_i32(TCGV_LOW(ret), TCGV_HIGH(arg1), c); - tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), 31); - } else { - tcg_gen_shri_i32(TCGV_LOW(ret), TCGV_HIGH(arg1), c); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } - } else { - tcg_gen_shli_i32(TCGV_HIGH(ret), TCGV_LOW(arg1), c); - tcg_gen_movi_i32(TCGV_LOW(ret), 0); - } - } else if (right) { - tcg_gen_extract2_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_HIGH(arg1), c); - if (arith) { - tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), c); - } else { - tcg_gen_shri_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), c); - } - } else { - tcg_gen_extract2_i32(TCGV_HIGH(ret), TCGV_LOW(arg1), TCGV_HIGH(arg1), 32 - c); - tcg_gen_shli_i32(TCGV_LOW(ret), TCGV_LOW(arg1), c); - } -} - void tcg_gen_shli_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { tcg_debug_assert(arg2 >= 0 && arg2 < 64); - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_shifti_i64(ret, arg1, arg2, 0, 0); - } else if (arg2 == 0) { + if (arg2 == 0) { tcg_gen_mov_i64(ret, arg1); } else { tcg_gen_shl_i64(ret, arg1, tcg_constant_i64(arg2)); @@ -1643,9 +1338,7 @@ void tcg_gen_shli_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { void tcg_gen_shri_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { tcg_debug_assert(arg2 >= 0 && arg2 < 64); - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_shifti_i64(ret, arg1, arg2, 1, 0); - } else if (arg2 == 0) { + if (arg2 == 0) { tcg_gen_mov_i64(ret, arg1); } else { tcg_gen_shr_i64(ret, arg1, tcg_constant_i64(arg2)); @@ -1654,9 +1347,7 @@ void tcg_gen_shri_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { void tcg_gen_sari_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { tcg_debug_assert(arg2 >= 0 && arg2 < 64); - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_shifti_i64(ret, arg1, arg2, 1, 1); - } else if (arg2 == 0) { + if (arg2 == 0) { tcg_gen_mov_i64(ret, arg1); } else { tcg_gen_sar_i64(ret, arg1, tcg_constant_i64(arg2)); @@ -1667,27 +1358,13 @@ void tcg_gen_brcond_i64(TCGCond cond, TCGv_i64 arg1, TCGv_i64 arg2, TCGLabel *l) if (cond == TCG_COND_ALWAYS) { tcg_gen_br(l); } else if (cond != TCG_COND_NEVER) { - TCGOp *op; - if (TCG_TARGET_REG_BITS == 32) { - op = tcg_gen_op6ii_i32(INDEX_op_brcond2_i32, TCGV_LOW(arg1), TCGV_HIGH(arg1), TCGV_LOW(arg2), - TCGV_HIGH(arg2), cond, label_arg(l)); - } else { - op = tcg_gen_op4ii_i64(INDEX_op_brcond, arg1, arg2, cond, label_arg(l)); - } + TCGOp *op = tcg_gen_op4ii_i64(INDEX_op_brcond, arg1, arg2, cond, label_arg(l)); add_as_label_use(l, op); } } void tcg_gen_brcondi_i64(TCGCond cond, TCGv_i64 arg1, int64_t arg2, TCGLabel *l) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_brcond_i64(cond, arg1, tcg_constant_i64(arg2), l); - } else if (cond == TCG_COND_ALWAYS) { - tcg_gen_br(l); - } else if (cond != TCG_COND_NEVER) { - TCGOp *op = tcg_gen_op6ii_i32(INDEX_op_brcond2_i32, TCGV_LOW(arg1), TCGV_HIGH(arg1), tcg_constant_i32(arg2), - tcg_constant_i32(arg2 >> 32), cond, label_arg(l)); - add_as_label_use(l, op); - } + tcg_gen_brcond_i64(cond, arg1, tcg_constant_i64(arg2), l); } void tcg_gen_setcond_i64(TCGCond cond, TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { @@ -1696,28 +1373,12 @@ void tcg_gen_setcond_i64(TCGCond cond, TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg } else if (cond == TCG_COND_NEVER) { tcg_gen_movi_i64(ret, 0); } else { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_op6i_i32(INDEX_op_setcond2_i32, TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_HIGH(arg1), TCGV_LOW(arg2), - TCGV_HIGH(arg2), cond); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } else { - tcg_gen_op4i_i64(INDEX_op_setcond, ret, arg1, arg2, cond); - } + tcg_gen_op4i_i64(INDEX_op_setcond, ret, arg1, arg2, cond); } } void tcg_gen_setcondi_i64(TCGCond cond, TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { - if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_setcond_i64(cond, ret, arg1, tcg_constant_i64(arg2)); - } else if (cond == TCG_COND_ALWAYS) { - tcg_gen_movi_i64(ret, 1); - } else if (cond == TCG_COND_NEVER) { - tcg_gen_movi_i64(ret, 0); - } else { - tcg_gen_op6i_i32(INDEX_op_setcond2_i32, TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_HIGH(arg1), tcg_constant_i32(arg2), - tcg_constant_i32(arg2 >> 32), cond); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } + tcg_gen_setcond_i64(cond, ret, arg1, tcg_constant_i64(arg2)); } void tcg_gen_negsetcondi_i64(TCGCond cond, TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { @@ -1729,13 +1390,8 @@ void tcg_gen_negsetcond_i64(TCGCond cond, TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 tcg_gen_movi_i64(ret, -1); } else if (cond == TCG_COND_NEVER) { tcg_gen_movi_i64(ret, 0); - } else if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op4i_i64(INDEX_op_negsetcond, ret, arg1, arg2, cond); } else { - tcg_gen_op6i_i32(INDEX_op_setcond2_i32, TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_HIGH(arg1), TCGV_LOW(arg2), - TCGV_HIGH(arg2), cond); - tcg_gen_neg_i32(TCGV_LOW(ret), TCGV_LOW(ret)); - tcg_gen_mov_i32(TCGV_HIGH(ret), TCGV_LOW(ret)); + tcg_gen_op4i_i64(INDEX_op_negsetcond, ret, arg1, arg2, cond); } } @@ -1849,14 +1505,7 @@ void tcg_gen_bswap16_i64(TCGv_i64 ret, TCGv_i64 arg, int flags) { /* Only one extension flag may be present. */ tcg_debug_assert(!(flags & TCG_BSWAP_OS) || !(flags & TCG_BSWAP_OZ)); - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_bswap16_i32(TCGV_LOW(ret), TCGV_LOW(arg), flags); - if (flags & TCG_BSWAP_OS) { - tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_LOW(ret), 31); - } else { - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } - } else if (tcg_op_supported(INDEX_op_bswap16, TCG_TYPE_I64, 0)) { + if (tcg_op_supported(INDEX_op_bswap16, TCG_TYPE_I64, 0)) { tcg_gen_op3i_i64(INDEX_op_bswap16, ret, arg, flags); } else { TCGv_i64 t0 = tcg_temp_ebb_new_i64(); @@ -1898,14 +1547,7 @@ void tcg_gen_bswap32_i64(TCGv_i64 ret, TCGv_i64 arg, int flags) { /* Only one extension flag may be present. */ tcg_debug_assert(!(flags & TCG_BSWAP_OS) || !(flags & TCG_BSWAP_OZ)); - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_bswap32_i32(TCGV_LOW(ret), TCGV_LOW(arg)); - if (flags & TCG_BSWAP_OS) { - tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_LOW(ret), 31); - } else { - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } - } else if (tcg_op_supported(INDEX_op_bswap32, TCG_TYPE_I64, 0)) { + if (tcg_op_supported(INDEX_op_bswap32, TCG_TYPE_I64, 0)) { tcg_gen_op3i_i64(INDEX_op_bswap32, ret, arg, flags); } else { TCGv_i64 t0 = tcg_temp_ebb_new_i64(); @@ -1940,18 +1582,7 @@ void tcg_gen_bswap32_i64(TCGv_i64 ret, TCGv_i64 arg, int flags) { * Byte pattern: abcdefgh -> hgfedcba */ void tcg_gen_bswap64_i64(TCGv_i64 ret, TCGv_i64 arg) { - if (TCG_TARGET_REG_BITS == 32) { - TCGv_i32 t0, t1; - t0 = tcg_temp_ebb_new_i32(); - t1 = tcg_temp_ebb_new_i32(); - - tcg_gen_bswap32_i32(t0, TCGV_LOW(arg)); - tcg_gen_bswap32_i32(t1, TCGV_HIGH(arg)); - tcg_gen_mov_i32(TCGV_LOW(ret), t1); - tcg_gen_mov_i32(TCGV_HIGH(ret), t0); - tcg_temp_free_i32(t0); - tcg_temp_free_i32(t1); - } else if (tcg_op_supported(INDEX_op_bswap64, TCG_TYPE_I64, 0)) { + if (tcg_op_supported(INDEX_op_bswap64, TCG_TYPE_I64, 0)) { tcg_gen_op3i_i64(INDEX_op_bswap64, ret, arg, 0); } else { TCGv_i64 t0 = tcg_temp_ebb_new_i64(); @@ -2017,10 +1648,7 @@ void tcg_gen_wswap_i64(TCGv_i64 ret, TCGv_i64 arg) { } void tcg_gen_not_i64(TCGv_i64 ret, TCGv_i64 arg) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_not_i32(TCGV_LOW(ret), TCGV_LOW(arg)); - tcg_gen_not_i32(TCGV_HIGH(ret), TCGV_HIGH(arg)); - } else if (tcg_op_supported(INDEX_op_not, TCG_TYPE_I64, 0)) { + if (tcg_op_supported(INDEX_op_not, TCG_TYPE_I64, 0)) { tcg_gen_op2_i64(INDEX_op_not, ret, arg); } else { tcg_gen_xori_i64(ret, arg, -1); @@ -2028,10 +1656,7 @@ void tcg_gen_not_i64(TCGv_i64 ret, TCGv_i64 arg) { } void tcg_gen_andc_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_andc_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_LOW(arg2)); - tcg_gen_andc_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), TCGV_HIGH(arg2)); - } else if (tcg_op_supported(INDEX_op_andc, TCG_TYPE_I64, 0)) { + if (tcg_op_supported(INDEX_op_andc, TCG_TYPE_I64, 0)) { tcg_gen_op3_i64(INDEX_op_andc, ret, arg1, arg2); } else { TCGv_i64 t0 = tcg_temp_ebb_new_i64(); @@ -2042,10 +1667,7 @@ void tcg_gen_andc_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { } void tcg_gen_eqv_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_eqv_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_LOW(arg2)); - tcg_gen_eqv_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), TCGV_HIGH(arg2)); - } else if (tcg_op_supported(INDEX_op_eqv, TCG_TYPE_I64, 0)) { + if (tcg_op_supported(INDEX_op_eqv, TCG_TYPE_I64, 0)) { tcg_gen_op3_i64(INDEX_op_eqv, ret, arg1, arg2); } else { tcg_gen_xor_i64(ret, arg1, arg2); @@ -2054,10 +1676,7 @@ void tcg_gen_eqv_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { } void tcg_gen_nand_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_nand_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_LOW(arg2)); - tcg_gen_nand_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), TCGV_HIGH(arg2)); - } else if (tcg_op_supported(INDEX_op_nand, TCG_TYPE_I64, 0)) { + if (tcg_op_supported(INDEX_op_nand, TCG_TYPE_I64, 0)) { tcg_gen_op3_i64(INDEX_op_nand, ret, arg1, arg2); } else { tcg_gen_and_i64(ret, arg1, arg2); @@ -2066,10 +1685,7 @@ void tcg_gen_nand_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { } void tcg_gen_nor_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_nor_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_LOW(arg2)); - tcg_gen_nor_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), TCGV_HIGH(arg2)); - } else if (tcg_op_supported(INDEX_op_nor, TCG_TYPE_I64, 0)) { + if (tcg_op_supported(INDEX_op_nor, TCG_TYPE_I64, 0)) { tcg_gen_op3_i64(INDEX_op_nor, ret, arg1, arg2); } else { tcg_gen_or_i64(ret, arg1, arg2); @@ -2078,10 +1694,7 @@ void tcg_gen_nor_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { } void tcg_gen_orc_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_orc_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_LOW(arg2)); - tcg_gen_orc_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), TCGV_HIGH(arg2)); - } else if (tcg_op_supported(INDEX_op_orc, TCG_TYPE_I64, 0)) { + if (tcg_op_supported(INDEX_op_orc, TCG_TYPE_I64, 0)) { tcg_gen_op3_i64(INDEX_op_orc, ret, arg1, arg2); } else { TCGv_i64 t0 = tcg_temp_ebb_new_i64(); @@ -2100,16 +1713,7 @@ void tcg_gen_clz_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { } void tcg_gen_clzi_i64(TCGv_i64 ret, TCGv_i64 arg1, uint64_t arg2) { - if (TCG_TARGET_REG_BITS == 32 && arg2 <= 0xffffffffu && tcg_op_supported(INDEX_op_clz, TCG_TYPE_I32, 0)) { - TCGv_i32 t = tcg_temp_ebb_new_i32(); - tcg_gen_clzi_i32(t, TCGV_LOW(arg1), arg2 - 32); - tcg_gen_addi_i32(t, t, 32); - tcg_gen_clz_i32(TCGV_LOW(ret), TCGV_HIGH(arg1), t); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - tcg_temp_free_i32(t); - } else { - tcg_gen_clz_i64(ret, arg1, tcg_constant_i64(arg2)); - } + tcg_gen_clz_i64(ret, arg1, tcg_constant_i64(arg2)); } void tcg_gen_ctz_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { @@ -2141,15 +1745,8 @@ void tcg_gen_ctz_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { } void tcg_gen_ctzi_i64(TCGv_i64 ret, TCGv_i64 arg1, uint64_t arg2) { - if (TCG_TARGET_REG_BITS == 32 && arg2 <= 0xffffffffu && tcg_op_supported(INDEX_op_ctz, TCG_TYPE_I32, 0)) { - TCGv_i32 t32 = tcg_temp_ebb_new_i32(); - tcg_gen_ctzi_i32(t32, TCGV_HIGH(arg1), arg2 - 32); - tcg_gen_addi_i32(t32, t32, 32); - tcg_gen_ctz_i32(TCGV_LOW(ret), TCGV_LOW(arg1), t32); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - tcg_temp_free_i32(t32); - } else if (arg2 == 64 && !tcg_op_supported(INDEX_op_ctz, TCG_TYPE_I64, 0) && - tcg_op_supported(INDEX_op_ctpop, TCG_TYPE_I64, 0)) { + if (arg2 == 64 && !tcg_op_supported(INDEX_op_ctz, TCG_TYPE_I64, 0) && + tcg_op_supported(INDEX_op_ctpop, TCG_TYPE_I64, 0)) { /* This equivalence has the advantage of not requiring a fixup. */ TCGv_i64 t = tcg_temp_ebb_new_i64(); tcg_gen_subi_i64(t, arg1, 1); @@ -2175,21 +1772,11 @@ void tcg_gen_clrsb_i64(TCGv_i64 ret, TCGv_i64 arg) { } void tcg_gen_ctpop_i64(TCGv_i64 ret, TCGv_i64 arg1) { - if (TCG_TARGET_REG_BITS == 64) { - if (tcg_op_supported(INDEX_op_ctpop, TCG_TYPE_I64, 0)) { - tcg_gen_op2_i64(INDEX_op_ctpop, ret, arg1); - return; - } + if (tcg_op_supported(INDEX_op_ctpop, TCG_TYPE_I64, 0)) { + tcg_gen_op2_i64(INDEX_op_ctpop, ret, arg1); } else { - if (tcg_op_supported(INDEX_op_ctpop, TCG_TYPE_I32, 0)) { - tcg_gen_ctpop_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1)); - tcg_gen_ctpop_i32(TCGV_LOW(ret), TCGV_LOW(arg1)); - tcg_gen_add_i32(TCGV_LOW(ret), TCGV_LOW(ret), TCGV_HIGH(ret)); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - return; - } + gen_helper_ctpop_i64(ret, arg1); } - gen_helper_ctpop_i64(ret, arg1); } void tcg_gen_rotl_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { @@ -2214,23 +1801,12 @@ void tcg_gen_rotl_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { void tcg_gen_rotli_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { tcg_debug_assert(arg2 >= 0 && arg2 < 64); - /* some cases can be optimized here */ if (arg2 == 0) { tcg_gen_mov_i64(ret, arg1); } else if (tcg_op_supported(INDEX_op_rotl, TCG_TYPE_I64, 0)) { - TCGv_i64 t0 = tcg_constant_i64(arg2); - tcg_gen_op3_i64(INDEX_op_rotl, ret, arg1, t0); - } else if (tcg_op_supported(INDEX_op_rotr, TCG_TYPE_I64, 0)) { - TCGv_i64 t0 = tcg_constant_i64(64 - arg2); - tcg_gen_op3_i64(INDEX_op_rotr, ret, arg1, t0); + tcg_gen_op3_i64(INDEX_op_rotl, ret, arg1, tcg_constant_i64(arg2)); } else { - TCGv_i64 t0 = tcg_temp_ebb_new_i64(); - TCGv_i64 t1 = tcg_temp_ebb_new_i64(); - tcg_gen_shli_i64(t0, arg1, arg2); - tcg_gen_shri_i64(t1, arg1, 64 - arg2); - tcg_gen_or_i64(ret, t0, t1); - tcg_temp_free_i64(t0); - tcg_temp_free_i64(t1); + tcg_gen_rotri_i64(ret, arg1, -arg2 & 63); } } @@ -2256,13 +1832,19 @@ void tcg_gen_rotr_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2) { void tcg_gen_rotri_i64(TCGv_i64 ret, TCGv_i64 arg1, int64_t arg2) { tcg_debug_assert(arg2 >= 0 && arg2 < 64); - tcg_gen_rotli_i64(ret, arg1, -arg2 & 63); + if (arg2 == 0) { + tcg_gen_mov_i64(ret, arg1); + } else if (tcg_op_supported(INDEX_op_rotr, TCG_TYPE_I64, 0)) { + tcg_gen_op3_i64(INDEX_op_rotr, ret, arg1, tcg_constant_i64(arg2)); + } else if (tcg_op_supported(INDEX_op_rotl, TCG_TYPE_I64, 0)) { + tcg_gen_op3_i64(INDEX_op_rotl, ret, arg1, tcg_constant_i64(64 - arg2)); + } else { + /* Do not recurse with the rotri simplification. */ + tcg_gen_op4i_i64(INDEX_op_extract2, ret, arg1, arg1, arg2); + } } void tcg_gen_deposit_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2, unsigned int ofs, unsigned int len) { - uint64_t mask; - TCGv_i64 t1; - tcg_debug_assert(ofs < 64); tcg_debug_assert(len > 0); tcg_debug_assert(len <= 64); @@ -2270,53 +1852,9 @@ void tcg_gen_deposit_i64(TCGv_i64 ret, TCGv_i64 arg1, TCGv_i64 arg2, unsigned in if (len == 64) { tcg_gen_mov_i64(ret, arg2); - return; - } - - if (TCG_TARGET_REG_BITS == 64) { - if (TCG_TARGET_deposit_valid(TCG_TYPE_I64, ofs, len)) { - tcg_gen_op5ii_i64(INDEX_op_deposit, ret, arg1, arg2, ofs, len); - return; - } } else { - if (ofs >= 32) { - tcg_gen_deposit_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), TCGV_LOW(arg2), ofs - 32, len); - tcg_gen_mov_i32(TCGV_LOW(ret), TCGV_LOW(arg1)); - return; - } - if (ofs + len <= 32) { - tcg_gen_deposit_i32(TCGV_LOW(ret), TCGV_LOW(arg1), TCGV_LOW(arg2), ofs, len); - tcg_gen_mov_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1)); - return; - } + tcg_gen_op5ii_i64(INDEX_op_deposit, ret, arg1, arg2, ofs, len); } - - t1 = tcg_temp_ebb_new_i64(); - - if (tcg_op_supported(INDEX_op_extract2, TCG_TYPE_I64, 0)) { - if (ofs + len == 64) { - tcg_gen_shli_i64(t1, arg1, len); - tcg_gen_extract2_i64(ret, t1, arg2, len); - goto done; - } - if (ofs == 0) { - tcg_gen_extract2_i64(ret, arg1, arg2, len); - tcg_gen_rotli_i64(ret, ret, len); - goto done; - } - } - - mask = (1ull << len) - 1; - if (ofs + len < 64) { - tcg_gen_andi_i64(t1, arg2, mask); - tcg_gen_shli_i64(t1, t1, ofs); - } else { - tcg_gen_shli_i64(t1, arg2, ofs); - } - tcg_gen_andi_i64(ret, arg1, ~(mask << ofs)); - tcg_gen_or_i64(ret, ret, t1); -done: - tcg_temp_free_i64(t1); } void tcg_gen_deposit_z_i64(TCGv_i64 ret, TCGv_i64 arg, unsigned int ofs, unsigned int len) { @@ -2329,43 +1867,15 @@ void tcg_gen_deposit_z_i64(TCGv_i64 ret, TCGv_i64 arg, unsigned int ofs, unsigne tcg_gen_shli_i64(ret, arg, ofs); } else if (ofs == 0) { tcg_gen_andi_i64(ret, arg, (1ull << len) - 1); - } else if (TCG_TARGET_REG_BITS == 64 && TCG_TARGET_deposit_valid(TCG_TYPE_I64, ofs, len)) { + } else { TCGv_i64 zero = tcg_constant_i64(0); tcg_gen_op5ii_i64(INDEX_op_deposit, ret, zero, arg, ofs, len); - } else { - if (TCG_TARGET_REG_BITS == 32) { - if (ofs >= 32) { - tcg_gen_deposit_z_i32(TCGV_HIGH(ret), TCGV_LOW(arg), ofs - 32, len); - tcg_gen_movi_i32(TCGV_LOW(ret), 0); - return; - } - if (ofs + len <= 32) { - tcg_gen_deposit_z_i32(TCGV_LOW(ret), TCGV_LOW(arg), ofs, len); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - return; - } - } - /* - * To help two-operand hosts we prefer to zero-extend first, - * which allows ARG to stay live. - */ - if (TCG_TARGET_extract_valid(TCG_TYPE_I64, 0, len)) { - tcg_gen_extract_i64(ret, arg, 0, len); - tcg_gen_shli_i64(ret, ret, ofs); - return; - } - /* Otherwise prefer zero-extension over AND for code size. */ - if (TCG_TARGET_extract_valid(TCG_TYPE_I64, 0, ofs + len)) { - tcg_gen_shli_i64(ret, arg, ofs); - tcg_gen_extract_i64(ret, ret, 0, ofs + len); - return; - } - tcg_gen_andi_i64(ret, arg, (1ull << len) - 1); - tcg_gen_shli_i64(ret, ret, ofs); } } void tcg_gen_extract_i64(TCGv_i64 ret, TCGv_i64 arg, unsigned int ofs, unsigned int len) { + uint64_t mask; + tcg_debug_assert(ofs < 64); tcg_debug_assert(len > 0); tcg_debug_assert(len <= 64); @@ -2377,36 +1887,14 @@ void tcg_gen_extract_i64(TCGv_i64 ret, TCGv_i64 arg, unsigned int ofs, unsigned return; } - if (TCG_TARGET_REG_BITS == 32) { - /* Look for a 32-bit extract within one of the two words. */ - if (ofs >= 32) { - tcg_gen_extract_i32(TCGV_LOW(ret), TCGV_HIGH(arg), ofs - 32, len); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - return; - } - if (ofs + len <= 32) { - tcg_gen_extract_i32(TCGV_LOW(ret), TCGV_LOW(arg), ofs, len); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - return; - } - - /* The field is split across two words. */ - tcg_gen_extract2_i32(TCGV_LOW(ret), TCGV_LOW(arg), TCGV_HIGH(arg), ofs); - if (len <= 32) { - tcg_gen_extract_i32(TCGV_LOW(ret), TCGV_LOW(ret), 0, len); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } else { - tcg_gen_extract_i32(TCGV_HIGH(ret), TCGV_HIGH(arg), ofs, len - 32); - } - return; - } - if (TCG_TARGET_extract_valid(TCG_TYPE_I64, ofs, len)) { tcg_gen_op4ii_i64(INDEX_op_extract, ret, arg, ofs, len); return; } + + mask = (1ull << len) - 1; if (ofs == 0) { - tcg_gen_andi_i64(ret, arg, (1ull << len) - 1); + tcg_gen_andi_i64(ret, arg, mask); return; } @@ -2417,20 +1905,12 @@ void tcg_gen_extract_i64(TCGv_i64 ret, TCGv_i64 arg, unsigned int ofs, unsigned return; } - /* ??? Ideally we'd know what values are available for immediate AND. - Assume that 8 bits are available, plus the special cases of 16 and 32, - so that we get ext8u, ext16u, and ext32u. */ - switch (len) { - case 1 ... 8: - case 16: - case 32: - tcg_gen_shri_i64(ret, arg, ofs); - tcg_gen_andi_i64(ret, ret, (1ull << len) - 1); - break; - default: - tcg_gen_shli_i64(ret, arg, 64 - len - ofs); - tcg_gen_shri_i64(ret, ret, 64 - len); - break; + if (tcg_op_imm_match(INDEX_op_and, TCG_TYPE_I64, mask)) { + tcg_gen_shri_i64(ret, arg, ofs); + tcg_gen_andi_i64(ret, ret, mask); + } else { + tcg_gen_shli_i64(ret, arg, 64 - len - ofs); + tcg_gen_shri_i64(ret, ret, 64 - len); } } @@ -2446,38 +1926,6 @@ void tcg_gen_sextract_i64(TCGv_i64 ret, TCGv_i64 arg, unsigned int ofs, unsigned return; } - if (TCG_TARGET_REG_BITS == 32) { - /* Look for a 32-bit extract within one of the two words. */ - if (ofs >= 32) { - tcg_gen_sextract_i32(TCGV_LOW(ret), TCGV_HIGH(arg), ofs - 32, len); - } else if (ofs + len <= 32) { - tcg_gen_sextract_i32(TCGV_LOW(ret), TCGV_LOW(arg), ofs, len); - } else if (ofs == 0) { - tcg_gen_mov_i32(TCGV_LOW(ret), TCGV_LOW(arg)); - tcg_gen_sextract_i32(TCGV_HIGH(ret), TCGV_HIGH(arg), 0, len - 32); - return; - } else if (len > 32) { - TCGv_i32 t = tcg_temp_ebb_new_i32(); - /* Extract the bits for the high word normally. */ - tcg_gen_sextract_i32(t, TCGV_HIGH(arg), ofs + 32, len - 32); - /* Shift the field down for the low part. */ - tcg_gen_shri_i64(ret, arg, ofs); - /* Overwrite the shift into the high part. */ - tcg_gen_mov_i32(TCGV_HIGH(ret), t); - tcg_temp_free_i32(t); - return; - } else { - /* Shift the field down for the low part, such that the - field sits at the MSB. */ - tcg_gen_shri_i64(ret, arg, ofs + len - 32); - /* Shift the field down from the MSB, sign extending. */ - tcg_gen_sari_i32(TCGV_LOW(ret), TCGV_LOW(ret), 32 - len); - } - /* Sign-extend the field from 32 bits. */ - tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_LOW(ret), 31); - return; - } - if (TCG_TARGET_sextract_valid(TCG_TYPE_I64, ofs, len)) { tcg_gen_op4ii_i64(INDEX_op_sextract, ret, arg, ofs, len); return; @@ -2511,13 +1959,8 @@ void tcg_gen_extract2_i64(TCGv_i64 ret, TCGv_i64 al, TCGv_i64 ah, unsigned int o tcg_gen_mov_i64(ret, ah); } else if (al == ah) { tcg_gen_rotri_i64(ret, al, ofs); - } else if (tcg_op_supported(INDEX_op_extract2, TCG_TYPE_I64, 0)) { - tcg_gen_op4i_i64(INDEX_op_extract2, ret, al, ah, ofs); } else { - TCGv_i64 t0 = tcg_temp_ebb_new_i64(); - tcg_gen_shri_i64(t0, al, ofs); - tcg_gen_deposit_i64(ret, t0, ah, 64 - ofs, ofs); - tcg_temp_free_i64(t0); + tcg_gen_op4i_i64(INDEX_op_extract2, ret, al, ah, ofs); } } @@ -2526,18 +1969,8 @@ void tcg_gen_movcond_i64(TCGCond cond, TCGv_i64 ret, TCGv_i64 c1, TCGv_i64 c2, T tcg_gen_mov_i64(ret, v1); } else if (cond == TCG_COND_NEVER) { tcg_gen_mov_i64(ret, v2); - } else if (TCG_TARGET_REG_BITS == 64) { - tcg_gen_op6i_i64(INDEX_op_movcond, ret, c1, c2, v1, v2, cond); } else { - TCGv_i32 t0 = tcg_temp_ebb_new_i32(); - TCGv_i32 zero = tcg_constant_i32(0); - - tcg_gen_op6i_i32(INDEX_op_setcond2_i32, t0, TCGV_LOW(c1), TCGV_HIGH(c1), TCGV_LOW(c2), TCGV_HIGH(c2), cond); - - tcg_gen_movcond_i32(TCG_COND_NE, TCGV_LOW(ret), t0, zero, TCGV_LOW(v1), TCGV_LOW(v2)); - tcg_gen_movcond_i32(TCG_COND_NE, TCGV_HIGH(ret), t0, zero, TCGV_HIGH(v1), TCGV_HIGH(v2)); - - tcg_temp_free_i32(t0); + tcg_gen_op6i_i64(INDEX_op_movcond, ret, c1, c2, v1, v2, cond); } } @@ -2545,16 +1978,8 @@ void tcg_gen_add2_i64(TCGv_i64 rl, TCGv_i64 rh, TCGv_i64 al, TCGv_i64 ah, TCGv_i if (tcg_op_supported(INDEX_op_addci, TCG_TYPE_REG, 0)) { TCGv_i64 t0 = tcg_temp_ebb_new_i64(); - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_op3_i32(INDEX_op_addco, TCGV_LOW(t0), TCGV_LOW(al), TCGV_LOW(bl)); - tcg_gen_op3_i32(INDEX_op_addcio, TCGV_HIGH(t0), TCGV_HIGH(al), TCGV_HIGH(bl)); - tcg_gen_op3_i32(INDEX_op_addcio, TCGV_LOW(rh), TCGV_LOW(ah), TCGV_LOW(bh)); - tcg_gen_op3_i32(INDEX_op_addci, TCGV_HIGH(rh), TCGV_HIGH(ah), TCGV_HIGH(bh)); - } else { - tcg_gen_op3_i64(INDEX_op_addco, t0, al, bl); - tcg_gen_op3_i64(INDEX_op_addci, rh, ah, bh); - } - + tcg_gen_op3_i64(INDEX_op_addco, t0, al, bl); + tcg_gen_op3_i64(INDEX_op_addci, rh, ah, bh); tcg_gen_mov_i64(rl, t0); tcg_temp_free_i64(t0); } else { @@ -2571,66 +1996,68 @@ void tcg_gen_add2_i64(TCGv_i64 rl, TCGv_i64 rh, TCGv_i64 al, TCGv_i64 ah, TCGv_i } void tcg_gen_addcio_i64(TCGv_i64 r, TCGv_i64 co, TCGv_i64 a, TCGv_i64 b, TCGv_i64 ci) { - if (TCG_TARGET_REG_BITS == 64) { - if (tcg_op_supported(INDEX_op_addci, TCG_TYPE_I64, 0)) { - TCGv_i64 discard = tcg_temp_ebb_new_i64(); - TCGv_i64 zero = tcg_constant_i64(0); - TCGv_i64 mone = tcg_constant_i64(-1); - - tcg_gen_op3_i64(INDEX_op_addco, discard, ci, mone); - tcg_gen_op3_i64(INDEX_op_addcio, r, a, b); - tcg_gen_op3_i64(INDEX_op_addci, co, zero, zero); - tcg_temp_free_i64(discard); - } else { - TCGv_i64 t0 = tcg_temp_ebb_new_i64(); - TCGv_i64 t1 = tcg_temp_ebb_new_i64(); + if (tcg_op_supported(INDEX_op_addci, TCG_TYPE_I64, 0)) { + TCGv_i64 discard = tcg_temp_ebb_new_i64(); + TCGv_i64 zero = tcg_constant_i64(0); + TCGv_i64 mone = tcg_constant_i64(-1); + + tcg_gen_op3_i64(INDEX_op_addco, discard, ci, mone); + tcg_gen_op3_i64(INDEX_op_addcio, r, a, b); + tcg_gen_op3_i64(INDEX_op_addci, co, zero, zero); + tcg_temp_free_i64(discard); + } else { + TCGv_i64 t0 = tcg_temp_ebb_new_i64(); + TCGv_i64 t1 = tcg_temp_ebb_new_i64(); + + tcg_gen_add_i64(t0, a, b); + tcg_gen_setcond_i64(TCG_COND_LTU, t1, t0, a); + tcg_gen_add_i64(r, t0, ci); + tcg_gen_setcond_i64(TCG_COND_LTU, t0, r, t0); + tcg_gen_or_i64(co, t0, t1); + + tcg_temp_free_i64(t0); + tcg_temp_free_i64(t1); + } +} + +void tcg_gen_addN_i64(int n, TCGv_i64 *r, TCGv_i64 *a, TCGv_i64 *b) { + tcg_debug_assert(n > 2); - tcg_gen_add_i64(t0, a, b); - tcg_gen_setcond_i64(TCG_COND_LTU, t1, t0, a); - tcg_gen_add_i64(r, t0, ci); - tcg_gen_setcond_i64(TCG_COND_LTU, t0, r, t0); - tcg_gen_or_i64(co, t0, t1); + /* ??? Don't allow overlap for now. */ + for (int i = 0; i < n - 1; ++i) { + for (int j = i + 1; j < n; ++j) { + tcg_debug_assert(r[i] != a[j]); + tcg_debug_assert(r[i] != b[j]); + } + } - tcg_temp_free_i64(t0); - tcg_temp_free_i64(t1); + if (tcg_op_supported(INDEX_op_addci, TCG_TYPE_I64, 0)) { + tcg_gen_op3_i64(INDEX_op_addco, r[0], a[0], b[0]); + for (int i = 1; i < n - 1; ++i) { + tcg_gen_op3_i64(INDEX_op_addcio, r[i], a[i], b[i]); } + tcg_gen_op3_i64(INDEX_op_addci, r[n - 1], a[n - 1], b[n - 1]); } else { - if (tcg_op_supported(INDEX_op_addci, TCG_TYPE_I32, 0)) { - TCGv_i32 discard = tcg_temp_ebb_new_i32(); - TCGv_i32 zero = tcg_constant_i32(0); - TCGv_i32 mone = tcg_constant_i32(-1); - - tcg_gen_op3_i32(INDEX_op_addco, discard, TCGV_LOW(ci), mone); - tcg_gen_op3_i32(INDEX_op_addcio, discard, TCGV_HIGH(ci), mone); - tcg_gen_op3_i32(INDEX_op_addcio, TCGV_LOW(r), TCGV_LOW(a), TCGV_LOW(b)); - tcg_gen_op3_i32(INDEX_op_addcio, TCGV_HIGH(r), TCGV_HIGH(a), TCGV_HIGH(b)); - tcg_gen_op3_i32(INDEX_op_addci, TCGV_LOW(co), zero, zero); - tcg_temp_free_i32(discard); - } else { - TCGv_i32 t0 = tcg_temp_ebb_new_i32(); - TCGv_i32 c0 = tcg_temp_ebb_new_i32(); - TCGv_i32 c1 = tcg_temp_ebb_new_i32(); - - tcg_gen_or_i32(c1, TCGV_LOW(ci), TCGV_HIGH(ci)); - tcg_gen_setcondi_i32(TCG_COND_NE, c1, c1, 0); - - tcg_gen_add_i32(t0, TCGV_LOW(a), TCGV_LOW(b)); - tcg_gen_setcond_i32(TCG_COND_LTU, c0, t0, TCGV_LOW(a)); - tcg_gen_add_i32(TCGV_LOW(r), t0, c1); - tcg_gen_setcond_i32(TCG_COND_LTU, c1, TCGV_LOW(r), c1); - tcg_gen_or_i32(c1, c1, c0); - - tcg_gen_add_i32(t0, TCGV_HIGH(a), TCGV_HIGH(b)); - tcg_gen_setcond_i32(TCG_COND_LTU, c0, t0, TCGV_HIGH(a)); - tcg_gen_add_i32(TCGV_HIGH(r), t0, c1); - tcg_gen_setcond_i32(TCG_COND_LTU, c1, TCGV_HIGH(r), c1); - tcg_gen_or_i32(TCGV_LOW(co), c0, c1); - - tcg_temp_free_i32(t0); - tcg_temp_free_i32(c0); - tcg_temp_free_i32(c1); + TCGv_i64 t = tcg_temp_ebb_new_i64(); + TCGv_i64 c = tcg_temp_ebb_new_i64(); + + tcg_gen_add_i64(t, a[0], b[0]); + tcg_gen_setcond_i64(TCG_COND_LTU, c, t, a[0]); + tcg_gen_mov_i64(r[0], t); + + for (int i = 1; i < n - 1; ++i) { + tcg_gen_add_i64(t, a[i], c); + tcg_gen_setcond_i64(TCG_COND_LTU, c, t, c); + tcg_gen_add_i64(r[i], b[i], t); + tcg_gen_setcond_i64(TCG_COND_LTU, t, r[i], t); + tcg_gen_or_i64(c, c, t); } - tcg_gen_movi_i32(TCGV_HIGH(co), 0); + + tcg_gen_add_i64(r[n - 1], a[n - 1], b[n - 1]); + tcg_gen_add_i64(r[n - 1], r[n - 1], c); + + tcg_temp_free_i64(t); + tcg_temp_free_i64(c); } } @@ -2638,16 +2065,8 @@ void tcg_gen_sub2_i64(TCGv_i64 rl, TCGv_i64 rh, TCGv_i64 al, TCGv_i64 ah, TCGv_i if (tcg_op_supported(INDEX_op_subbi, TCG_TYPE_REG, 0)) { TCGv_i64 t0 = tcg_temp_ebb_new_i64(); - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_op3_i32(INDEX_op_subbo, TCGV_LOW(t0), TCGV_LOW(al), TCGV_LOW(bl)); - tcg_gen_op3_i32(INDEX_op_subbio, TCGV_HIGH(t0), TCGV_HIGH(al), TCGV_HIGH(bl)); - tcg_gen_op3_i32(INDEX_op_subbio, TCGV_LOW(rh), TCGV_LOW(ah), TCGV_LOW(bh)); - tcg_gen_op3_i32(INDEX_op_subbi, TCGV_HIGH(rh), TCGV_HIGH(ah), TCGV_HIGH(bh)); - } else { - tcg_gen_op3_i64(INDEX_op_subbo, t0, al, bl); - tcg_gen_op3_i64(INDEX_op_subbi, rh, ah, bh); - } - + tcg_gen_op3_i64(INDEX_op_subbo, t0, al, bl); + tcg_gen_op3_i64(INDEX_op_subbi, rh, ah, bh); tcg_gen_mov_i64(rl, t0); tcg_temp_free_i64(t0); } else { @@ -2760,49 +2179,24 @@ void tcg_gen_abs_i64(TCGv_i64 ret, TCGv_i64 a) { /* Size changing operations. */ void tcg_gen_extrl_i64_i32(TCGv_i32 ret, TCGv_i64 arg) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_mov_i32(ret, TCGV_LOW(arg)); - } else { - tcg_gen_op2(INDEX_op_extrl_i64_i32, TCG_TYPE_I32, tcgv_i32_arg(ret), tcgv_i64_arg(arg)); - } + tcg_gen_op2(INDEX_op_extrl_i64_i32, TCG_TYPE_I32, tcgv_i32_arg(ret), tcgv_i64_arg(arg)); } void tcg_gen_extrh_i64_i32(TCGv_i32 ret, TCGv_i64 arg) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_mov_i32(ret, TCGV_HIGH(arg)); - } else { - tcg_gen_op2(INDEX_op_extrh_i64_i32, TCG_TYPE_I32, tcgv_i32_arg(ret), tcgv_i64_arg(arg)); - } + tcg_gen_op2(INDEX_op_extrh_i64_i32, TCG_TYPE_I32, tcgv_i32_arg(ret), tcgv_i64_arg(arg)); } void tcg_gen_extu_i32_i64(TCGv_i64 ret, TCGv_i32 arg) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_mov_i32(TCGV_LOW(ret), arg); - tcg_gen_movi_i32(TCGV_HIGH(ret), 0); - } else { - tcg_gen_op2(INDEX_op_extu_i32_i64, TCG_TYPE_I64, tcgv_i64_arg(ret), tcgv_i32_arg(arg)); - } + tcg_gen_op2(INDEX_op_extu_i32_i64, TCG_TYPE_I64, tcgv_i64_arg(ret), tcgv_i32_arg(arg)); } void tcg_gen_ext_i32_i64(TCGv_i64 ret, TCGv_i32 arg) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_mov_i32(TCGV_LOW(ret), arg); - tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_LOW(ret), 31); - } else { - tcg_gen_op2(INDEX_op_ext_i32_i64, TCG_TYPE_I64, tcgv_i64_arg(ret), tcgv_i32_arg(arg)); - } + tcg_gen_op2(INDEX_op_ext_i32_i64, TCG_TYPE_I64, tcgv_i64_arg(ret), tcgv_i32_arg(arg)); } void tcg_gen_concat_i32_i64(TCGv_i64 dest, TCGv_i32 low, TCGv_i32 high) { - TCGv_i64 tmp; + TCGv_i64 tmp = tcg_temp_ebb_new_i64(); - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_mov_i32(TCGV_LOW(dest), low); - tcg_gen_mov_i32(TCGV_HIGH(dest), high); - return; - } - - tmp = tcg_temp_ebb_new_i64(); /* These extensions are only needed for type correctness. We may be able to do better given target specific information. */ tcg_gen_extu_i32_i64(tmp, high); @@ -2819,13 +2213,8 @@ void tcg_gen_concat_i32_i64(TCGv_i64 dest, TCGv_i32 low, TCGv_i32 high) { } void tcg_gen_extr_i64_i32(TCGv_i32 lo, TCGv_i32 hi, TCGv_i64 arg) { - if (TCG_TARGET_REG_BITS == 32) { - tcg_gen_mov_i32(lo, TCGV_LOW(arg)); - tcg_gen_mov_i32(hi, TCGV_HIGH(arg)); - } else { - tcg_gen_extrl_i64_i32(lo, arg); - tcg_gen_extrh_i64_i32(hi, arg); - } + tcg_gen_extrl_i64_i32(lo, arg); + tcg_gen_extrh_i64_i32(hi, arg); } void tcg_gen_extr32_i64(TCGv_i64 lo, TCGv_i64 hi, TCGv_i64 arg) { @@ -2847,6 +2236,15 @@ void tcg_gen_concat_i64_i128(TCGv_i128 ret, TCGv_i64 lo, TCGv_i64 hi) { tcg_gen_mov_i64(TCGV128_HIGH(ret), hi); } +TCGv_i128 tcg_zero_i128(void) { + TCGv_i64 zero64 = tcg_constant_i64(0); + TCGv_i128 zero128 = tcg_temp_new_i128(); + + tcg_gen_concat_i64_i128(zero128, zero64, zero64); + + return zero128; +} + void tcg_gen_mov_i128(TCGv_i128 dst, TCGv_i128 src) { if (dst != src) { tcg_gen_mov_i64(TCGV128_LOW(dst), TCGV128_LOW(src)); diff --git a/libtcg/src/tcg-pool.c.inc b/libtcg/src/tcg-pool.c.inc deleted file mode 100644 index 0014b8f45..000000000 --- a/libtcg/src/tcg-pool.c.inc +++ /dev/null @@ -1,144 +0,0 @@ -/* - * TCG Backend Data: constant pool. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -typedef struct TCGLabelPoolData { - struct TCGLabelPoolData *next; - tcg_insn_unit *label; - intptr_t addend; - int rtype; - unsigned nlong; - tcg_target_ulong data[]; -} TCGLabelPoolData; - -static TCGLabelPoolData *new_pool_alloc(TCGContext *s, int nlong, int rtype, tcg_insn_unit *label, intptr_t addend) { - TCGLabelPoolData *n = tcg_malloc(sizeof(TCGLabelPoolData) + sizeof(tcg_target_ulong) * nlong); - - n->label = label; - n->addend = addend; - n->rtype = rtype; - n->nlong = nlong; - return n; -} - -static void new_pool_insert(TCGContext *s, TCGLabelPoolData *n) { - TCGLabelPoolData *i, **pp; - int nlong = n->nlong; - - /* Insertion sort on the pool. */ - for (pp = &s->pool_labels; (i = *pp) != NULL; pp = &i->next) { - if (nlong > i->nlong) { - break; - } - if (nlong < i->nlong) { - continue; - } - if (memcmp(n->data, i->data, sizeof(tcg_target_ulong) * nlong) >= 0) { - break; - } - } - n->next = *pp; - *pp = n; -} - -/* The "usual" for generic integer code. */ -static inline void new_pool_label(TCGContext *s, tcg_target_ulong d, int rtype, tcg_insn_unit *label, intptr_t addend) { - TCGLabelPoolData *n = new_pool_alloc(s, 1, rtype, label, addend); - n->data[0] = d; - new_pool_insert(s, n); -} - -/* For v64 or v128, depending on the host. */ -static inline void new_pool_l2(TCGContext *s, int rtype, tcg_insn_unit *label, intptr_t addend, tcg_target_ulong d0, - tcg_target_ulong d1) { - TCGLabelPoolData *n = new_pool_alloc(s, 2, rtype, label, addend); - n->data[0] = d0; - n->data[1] = d1; - new_pool_insert(s, n); -} - -/* For v128 or v256, depending on the host. */ -static inline void new_pool_l4(TCGContext *s, int rtype, tcg_insn_unit *label, intptr_t addend, tcg_target_ulong d0, - tcg_target_ulong d1, tcg_target_ulong d2, tcg_target_ulong d3) { - TCGLabelPoolData *n = new_pool_alloc(s, 4, rtype, label, addend); - n->data[0] = d0; - n->data[1] = d1; - n->data[2] = d2; - n->data[3] = d3; - new_pool_insert(s, n); -} - -/* For v256, for 32-bit host. */ -static inline void new_pool_l8(TCGContext *s, int rtype, tcg_insn_unit *label, intptr_t addend, tcg_target_ulong d0, - tcg_target_ulong d1, tcg_target_ulong d2, tcg_target_ulong d3, tcg_target_ulong d4, - tcg_target_ulong d5, tcg_target_ulong d6, tcg_target_ulong d7) { - TCGLabelPoolData *n = new_pool_alloc(s, 8, rtype, label, addend); - n->data[0] = d0; - n->data[1] = d1; - n->data[2] = d2; - n->data[3] = d3; - n->data[4] = d4; - n->data[5] = d5; - n->data[6] = d6; - n->data[7] = d7; - new_pool_insert(s, n); -} - -/* To be provided by cpu/tcg-target.c.inc. */ -static void tcg_out_nop_fill(tcg_insn_unit *p, int count); - -static int tcg_out_pool_finalize(TCGContext *s) { - TCGLabelPoolData *p = s->pool_labels; - TCGLabelPoolData *l = NULL; - void *a; - - if (p == NULL) { - return 0; - } - - /* ??? Round up to qemu_icache_linesize, but then do not round - again when allocating the next TranslationBlock structure. */ - a = (void *) ROUND_UP((uintptr_t) s->code_ptr, sizeof(tcg_target_ulong) * p->nlong); - tcg_out_nop_fill(s->code_ptr, (tcg_insn_unit *) a - s->code_ptr); - s->data_gen_ptr = a; - - for (; p != NULL; p = p->next) { - size_t size = sizeof(tcg_target_ulong) * p->nlong; - uintptr_t value; - - if (!l || l->nlong != p->nlong || memcmp(l->data, p->data, size)) { - if (unlikely(a > s->code_gen_highwater)) { - return -1; - } - memcpy(a, p->data, size); - a += size; - l = p; - } - - value = (uintptr_t) tcg_splitwx_to_rx(a) - size; - if (!patch_reloc(p->label, p->rtype, value, p->addend)) { - return -2; - } - } - - s->code_ptr = a; - return 0; -} diff --git a/libtcg/src/tcg-rt/tcg-runtime-gvec.c b/libtcg/src/tcg-rt/tcg-runtime-gvec.c index d785e77b0..982765074 100644 --- a/libtcg/src/tcg-rt/tcg-runtime-gvec.c +++ b/libtcg/src/tcg-rt/tcg-runtime-gvec.c @@ -1023,10 +1023,7 @@ void HELPER(gvec_ssadd32)(void *d, void *a, void *b, uint32_t desc) { for (i = 0; i < oprsz; i += sizeof(int32_t)) { int32_t ai = *(int32_t *) (a + i); int32_t bi = *(int32_t *) (b + i); - int32_t di; - if (sadd32_overflow(ai, bi, &di)) { - di = (di < 0 ? INT32_MAX : INT32_MIN); - } + int32_t di = sadd32_saturate(ai, bi); *(int32_t *) (d + i) = di; } clear_high(d, oprsz, desc); @@ -1039,10 +1036,7 @@ void HELPER(gvec_ssadd64)(void *d, void *a, void *b, uint32_t desc) { for (i = 0; i < oprsz; i += sizeof(int64_t)) { int64_t ai = *(int64_t *) (a + i); int64_t bi = *(int64_t *) (b + i); - int64_t di; - if (sadd64_overflow(ai, bi, &di)) { - di = (di < 0 ? INT64_MAX : INT64_MIN); - } + int64_t di = sadd64_saturate(ai, bi); *(int64_t *) (d + i) = di; } clear_high(d, oprsz, desc); @@ -1087,10 +1081,7 @@ void HELPER(gvec_sssub32)(void *d, void *a, void *b, uint32_t desc) { for (i = 0; i < oprsz; i += sizeof(int32_t)) { int32_t ai = *(int32_t *) (a + i); int32_t bi = *(int32_t *) (b + i); - int32_t di; - if (ssub32_overflow(ai, bi, &di)) { - di = (di < 0 ? INT32_MAX : INT32_MIN); - } + int32_t di = ssub32_saturate(ai, bi); *(int32_t *) (d + i) = di; } clear_high(d, oprsz, desc); @@ -1103,10 +1094,7 @@ void HELPER(gvec_sssub64)(void *d, void *a, void *b, uint32_t desc) { for (i = 0; i < oprsz; i += sizeof(int64_t)) { int64_t ai = *(int64_t *) (a + i); int64_t bi = *(int64_t *) (b + i); - int64_t di; - if (ssub64_overflow(ai, bi, &di)) { - di = (di < 0 ? INT64_MAX : INT64_MIN); - } + int64_t di = ssub64_saturate(ai, bi); *(int64_t *) (d + i) = di; } clear_high(d, oprsz, desc); diff --git a/libtcg/src/tcg-rt/tcg-runtime.c b/libtcg/src/tcg-rt/tcg-runtime.c index 18d737484..d7cd0066e 100644 --- a/libtcg/src/tcg-rt/tcg-runtime.c +++ b/libtcg/src/tcg-rt/tcg-runtime.c @@ -57,18 +57,6 @@ uint32_t HELPER(remu_i32)(uint32_t arg1, uint32_t arg2) { /* 64-bit helpers */ -uint64_t HELPER(shl_i64)(uint64_t arg1, uint64_t arg2) { - return arg1 << arg2; -} - -uint64_t HELPER(shr_i64)(uint64_t arg1, uint64_t arg2) { - return arg1 >> arg2; -} - -int64_t HELPER(sar_i64)(int64_t arg1, int64_t arg2) { - return arg1 >> arg2; -} - int64_t HELPER(div_i64)(int64_t arg1, int64_t arg2) { return arg1 / arg2; } diff --git a/libtcg/src/tcg.c b/libtcg/src/tcg.c index fff850c62..7559125df 100644 --- a/libtcg/src/tcg.c +++ b/libtcg/src/tcg.c @@ -200,18 +200,13 @@ static void tcg_out_st_helper_args(TCGContext *s, const TCGLabelQemuLdst *l, con __attribute__((unused)); static void *const qemu_ld_helpers[MO_SSIZE + 1] __attribute__((unused)) = { - [MO_UB] = helper_ldub_mmu, [MO_SB] = helper_ldsb_mmu, [MO_UW] = helper_lduw_mmu, - [MO_SW] = helper_ldsw_mmu, [MO_UL] = helper_ldul_mmu, [MO_UQ] = helper_ldq_mmu, -#if TCG_TARGET_REG_BITS == 64 - [MO_SL] = helper_ldsl_mmu, [MO_128] = helper_ld16_mmu, -#endif + [MO_UB] = helper_ldub_mmu, [MO_SB] = helper_ldsb_mmu, [MO_UW] = helper_lduw_mmu, [MO_SW] = helper_ldsw_mmu, + [MO_UL] = helper_ldul_mmu, [MO_UQ] = helper_ldq_mmu, [MO_SL] = helper_ldsl_mmu, [MO_128] = helper_ld16_mmu, }; static void *const qemu_st_helpers[MO_SIZE + 1] __attribute__((unused)) = { - [MO_8] = helper_stb_mmu, [MO_16] = helper_stw_mmu, [MO_32] = helper_stl_mmu, [MO_64] = helper_stq_mmu, -#if TCG_TARGET_REG_BITS == 64 - [MO_128] = helper_st16_mmu, -#endif + [MO_8] = helper_stb_mmu, [MO_16] = helper_stw_mmu, [MO_32] = helper_stl_mmu, + [MO_64] = helper_stq_mmu, [MO_128] = helper_st16_mmu, }; typedef struct { @@ -222,10 +217,6 @@ typedef struct { static TCGAtomAlign atom_and_align_for_opc(TCGContext *s, MemOp opc, MemOp host_atom, bool allow_two_ops) __attribute__((unused)); -#ifdef CONFIG_USER_ONLY -bool tcg_use_softmmu; -#endif - TCGContext tcg_init_ctx; __thread TCGContext *tcg_ctx; @@ -234,7 +225,7 @@ unsigned int tcg_cur_ctxs; unsigned int tcg_max_ctxs; TCGv_env tcg_env; const void *tcg_code_gen_epilogue; -uintptr_t tcg_splitwx_diff; +ptrdiff_t tcg_splitwx_diff; #ifndef CONFIG_TCG_INTERPRETER tcg_prologue_fn *tcg_qemu_tb_exec; @@ -458,7 +449,6 @@ static void tcg_out_movext(TCGContext *s, TCGType dst_type, TCGReg dst, TCGType } break; case MO_UQ: - tcg_debug_assert(TCG_TARGET_REG_BITS == 64); if (dst_type == TCG_TYPE_I32) { tcg_out_extrl_i64_i32(s, dst, src); } else { @@ -791,7 +781,7 @@ static int tcg_out_pool_finalize(TCGContext *s) { typedef enum { C_Dynamic = -2, C_NotImplemented = -1, -#include "i386/tcg-target-con-set.h" +#include "x86_64/tcg-target-con-set.h" } TCGConstraintSetIndex; static TCGConstraintSetIndex tcg_target_op_def(TCGOpcode, TCGType, unsigned); @@ -841,7 +831,7 @@ typedef struct TCGConstraintSet { #define C_N1_O1_I4(O1, O2, I1, I2, I3, I4) {2, 4, {"&" #O1, #O2, #I1, #I2, #I3, #I4}}, static const TCGConstraintSet constraint_sets[] = { -#include "i386/tcg-target-con-set.h" +#include "x86_64/tcg-target-con-set.h" }; #undef C_O0_I1 @@ -926,12 +916,6 @@ typedef struct TCGOutOpBrcond { void (*out_ri)(TCGContext *s, TCGType type, TCGCond cond, TCGReg a1, tcg_target_long a2, TCGLabel *label); } TCGOutOpBrcond; -typedef struct TCGOutOpBrcond2 { - TCGOutOp base; - void (*out)(TCGContext *s, TCGCond cond, TCGReg al, TCGReg ah, TCGArg bl, bool const_bl, TCGArg bh, bool const_bh, - TCGLabel *l); -} TCGOutOpBrcond2; - typedef struct TCGOutOpBswap { TCGOutOp base; void (*out_rr)(TCGContext *s, TCGType type, TCGReg a0, TCGReg a1, unsigned flags); @@ -996,12 +980,6 @@ typedef struct TCGOutOpSetcond { void (*out_rri)(TCGContext *s, TCGType type, TCGCond cond, TCGReg ret, TCGReg a1, tcg_target_long a2); } TCGOutOpSetcond; -typedef struct TCGOutOpSetcond2 { - TCGOutOp base; - void (*out)(TCGContext *s, TCGCond cond, TCGReg ret, TCGReg al, TCGReg ah, TCGArg bl, bool const_bl, TCGArg bh, - bool const_bh); -} TCGOutOpSetcond2; - typedef struct TCGOutOpStore { TCGOutOp base; void (*out_r)(TCGContext *s, TCGType type, TCGReg data, TCGReg base, intptr_t offset); @@ -1014,7 +992,7 @@ typedef struct TCGOutOpSubtract { void (*out_rir)(TCGContext *s, TCGType type, TCGReg a0, tcg_target_long a1, TCGReg a2); } TCGOutOpSubtract; -#include "i386/tcg-target.c.inc" +#include "x86_64/tcg-target.c.inc" #ifndef CONFIG_TCG_INTERPRETER /* Validate CPUTLBDescFast placement. */ @@ -1022,7 +1000,6 @@ typedef struct TCGOutOpSubtract { // MIN_TLB_MASK_TABLE_OFS); #endif -#if TCG_TARGET_REG_BITS == 64 /* * We require these functions for slow-path function calls. * Adapt them generically for opcode output. @@ -1054,7 +1031,6 @@ static const TCGOutOpUnary outop_extrl_i64_i32 = { .base.static_constraint = C_O1_I1(r, r), .out_rr = TCG_TARGET_HAS_extr_i64_i32 ? tgen_extrl_i64_i32 : NULL, }; -#endif static const TCGOutOp outop_goto_ptr = { .static_constraint = C_O0_I1(r), @@ -1140,10 +1116,6 @@ static const TCGOutOp *const all_outop[NB_OPS] = { [INDEX_op_goto_ptr] = &outop_goto_ptr, -#if TCG_TARGET_REG_BITS == 32 - OUTOP(INDEX_op_brcond2_i32, TCGOutOpBrcond2, outop_brcond2), - OUTOP(INDEX_op_setcond2_i32, TCGOutOpSetcond2, outop_setcond2), -#else OUTOP(INDEX_op_bswap64, TCGOutOpUnary, outop_bswap64), OUTOP(INDEX_op_ext_i32_i64, TCGOutOpUnary, outop_exts_i32_i64), OUTOP(INDEX_op_extu_i32_i64, TCGOutOpUnary, outop_extu_i32_i64), @@ -1152,7 +1124,6 @@ static const TCGOutOp *const all_outop[NB_OPS] = { OUTOP(INDEX_op_ld32u, TCGOutOpLoad, outop_ld32u), OUTOP(INDEX_op_ld32s, TCGOutOpLoad, outop_ld32s), OUTOP(INDEX_op_st32, TCGOutOpStore, outop_st), -#endif }; #undef OUTOP @@ -1267,11 +1238,7 @@ void tcg_pool_reset(TCGContext *s) { * the helpers, with the end result that it's easier to build manually. */ -#if TCG_TARGET_REG_BITS == 32 -#define dh_typecode_ttl dh_typecode_i32 -#else #define dh_typecode_ttl dh_typecode_i64 -#endif static TCGHelperInfo info_helper_ld32_mmu = { .flags = TCG_CALL_NO_WG, @@ -1497,16 +1464,11 @@ static void init_call_layout(TCGHelperInfo *info) { break; case dh_typecode_i32: case dh_typecode_s32: - case dh_typecode_ptr: - info->nr_out = 1; - info->out_kind = TCG_CALL_RET_NORMAL; - break; case dh_typecode_i64: case dh_typecode_s64: - info->nr_out = 64 / TCG_TARGET_REG_BITS; + case dh_typecode_ptr: + info->nr_out = 1; info->out_kind = TCG_CALL_RET_NORMAL; - /* Query the last register now to trigger any assert early. */ - tcg_target_call_oarg_reg(info->out_kind, info->nr_out - 1); break; case dh_typecode_i128: info->nr_out = 128 / TCG_TARGET_REG_BITS; @@ -1587,11 +1549,7 @@ static void init_call_layout(TCGHelperInfo *info) { layout_arg_even(&cum); /* fall through */ case TCG_CALL_ARG_NORMAL: - if (TCG_TARGET_REG_BITS == 32) { - layout_arg_normal_n(&cum, info, 2); - } else { - layout_arg_1(&cum, info, TCG_CALL_ARG_NORMAL); - } + layout_arg_1(&cum, info, TCG_CALL_ARG_NORMAL); break; default: qemu_build_not_reached(); @@ -1870,11 +1828,8 @@ static TCGTemp *tcg_global_alloc(TCGContext *s) { } static TCGTemp *tcg_global_reg_new_internal(TCGContext *s, TCGType type, TCGReg reg, const char *name) { - TCGTemp *ts; - - tcg_debug_assert(TCG_TARGET_REG_BITS == 64 || type == TCG_TYPE_I32); + TCGTemp *ts = tcg_global_alloc(s); - ts = tcg_global_alloc(s); ts->base_type = type; ts->type = type; ts->kind = TEMP_FIXED; @@ -1904,47 +1859,20 @@ static TCGTemp *tcg_global_mem_new_internal(TCGv_ptr base, intptr_t offset, cons /* We do not support double-indirect registers. */ tcg_debug_assert(!base_ts->indirect_reg); base_ts->indirect_base = 1; - s->nb_indirects += (TCG_TARGET_REG_BITS == 32 && type == TCG_TYPE_I64 ? 2 : 1); + s->nb_indirects += 1; indirect_reg = 1; break; default: g_assert_not_reached(); } - if (TCG_TARGET_REG_BITS == 32 && type == TCG_TYPE_I64) { - TCGTemp *ts2 = tcg_global_alloc(s); - char buf[64]; - - ts->base_type = TCG_TYPE_I64; - ts->type = TCG_TYPE_I32; - ts->indirect_reg = indirect_reg; - ts->mem_allocated = 1; - ts->mem_base = base_ts; - ts->mem_offset = offset; - pstrcpy(buf, sizeof(buf), name); - pstrcat(buf, sizeof(buf), "_0"); - ts->name = strdup(buf); - - tcg_debug_assert(ts2 == ts + 1); - ts2->base_type = TCG_TYPE_I64; - ts2->type = TCG_TYPE_I32; - ts2->indirect_reg = indirect_reg; - ts2->mem_allocated = 1; - ts2->mem_base = base_ts; - ts2->mem_offset = offset + 4; - ts2->temp_subindex = 1; - pstrcpy(buf, sizeof(buf), name); - pstrcat(buf, sizeof(buf), "_1"); - ts2->name = strdup(buf); - } else { - ts->base_type = type; - ts->type = type; - ts->indirect_reg = indirect_reg; - ts->mem_allocated = 1; - ts->mem_base = base_ts; - ts->mem_offset = offset; - ts->name = name; - } + ts->base_type = type; + ts->type = type; + ts->indirect_reg = indirect_reg; + ts->mem_allocated = 1; + ts->mem_base = base_ts; + ts->mem_offset = offset; + ts->name = name; return ts; } @@ -1987,14 +1915,12 @@ TCGTemp *tcg_temp_new_internal(TCGType type, TCGTempKind kind) { switch (type) { case TCG_TYPE_I32: + case TCG_TYPE_I64: case TCG_TYPE_V64: case TCG_TYPE_V128: case TCG_TYPE_V256: n = 1; break; - case TCG_TYPE_I64: - n = 64 / TCG_TARGET_REG_BITS; - break; case TCG_TYPE_I128: n = 128 / TCG_TARGET_REG_BITS; break; @@ -2142,43 +2068,13 @@ TCGTemp *tcg_constant_internal(TCGType type, int64_t val) { ts = g_hash_table_lookup(h, &val); if (ts == NULL) { - int64_t *val_ptr; - ts = tcg_temp_alloc(s); - - if (TCG_TARGET_REG_BITS == 32 && type == TCG_TYPE_I64) { - TCGTemp *ts2 = tcg_temp_alloc(s); - - tcg_debug_assert(ts2 == ts + 1); - - ts->base_type = TCG_TYPE_I64; - ts->type = TCG_TYPE_I32; - ts->kind = TEMP_CONST; - ts->temp_allocated = 1; - - ts2->base_type = TCG_TYPE_I64; - ts2->type = TCG_TYPE_I32; - ts2->kind = TEMP_CONST; - ts2->temp_allocated = 1; - ts2->temp_subindex = 1; - - /* - * Retain the full value of the 64-bit constant in the low - * part, so that the hash table works. Actual uses will - * truncate the value to the low part. - */ - ts[HOST_BIG_ENDIAN].val = val; - ts[!HOST_BIG_ENDIAN].val = val >> 32; - val_ptr = &ts[HOST_BIG_ENDIAN].val; - } else { - ts->base_type = type; - ts->type = type; - ts->kind = TEMP_CONST; - ts->temp_allocated = 1; - ts->val = val; - val_ptr = &ts->val; - } - g_hash_table_insert(h, val_ptr, ts); + ts->base_type = type; + ts->type = type; + ts->kind = TEMP_CONST; + ts->temp_allocated = 1; + ts->val = val; + g_hash_table_insert(h, &ts->val, ts); } return ts; @@ -2238,10 +2134,8 @@ bool tcg_op_supported(TCGOpcode op, TCGType type, unsigned flags) { switch (type) { case TCG_TYPE_I32: - has_type = true; - break; case TCG_TYPE_I64: - has_type = TCG_TARGET_REG_BITS == 64; + has_type = true; break; case TCG_TYPE_V64: has_type = TCG_TARGET_HAS_v64; @@ -2276,10 +2170,6 @@ bool tcg_op_supported(TCGOpcode op, TCGType type, unsigned flags) { case INDEX_op_qemu_ld2: case INDEX_op_qemu_st2: - if (TCG_TARGET_REG_BITS == 32) { - tcg_debug_assert(type == TCG_TYPE_I64); - return true; - } tcg_debug_assert(type == TCG_TYPE_I128); goto do_lookup; @@ -2305,10 +2195,6 @@ bool tcg_op_supported(TCGOpcode op, TCGType type, unsigned flags) { case INDEX_op_xor: return has_type; - case INDEX_op_brcond2_i32: - case INDEX_op_setcond2_i32: - return TCG_TARGET_REG_BITS == 32; - case INDEX_op_ld32u: case INDEX_op_ld32s: case INDEX_op_st32: @@ -2316,7 +2202,7 @@ bool tcg_op_supported(TCGOpcode op, TCGType type, unsigned flags) { case INDEX_op_extu_i32_i64: case INDEX_op_extrl_i64_i32: case INDEX_op_extrh_i64_i32: - return TCG_TARGET_REG_BITS == 64; + return true; case INDEX_op_mov_vec: case INDEX_op_dup_vec: @@ -2330,8 +2216,6 @@ bool tcg_op_supported(TCGOpcode op, TCGType type, unsigned flags) { case INDEX_op_xor_vec: case INDEX_op_cmp_vec: return has_type; - case INDEX_op_dup2_vec: - return has_type && TCG_TARGET_REG_BITS == 32; case INDEX_op_not_vec: return has_type && TCG_TARGET_HAS_not_vec; case INDEX_op_neg_vec: @@ -2610,11 +2494,9 @@ static char *tcg_get_arg_str_ptr(TCGContext *s, char *buf, int buf_size, TCGTemp case TCG_TYPE_I32: snprintf(buf, buf_size, "$0x%x", (int32_t) ts->val); break; -#if TCG_TARGET_REG_BITS > 32 case TCG_TYPE_I64: snprintf(buf, buf_size, "$0x%" PRIx64, ts->val); break; -#endif case TCG_TYPE_V64: case TCG_TYPE_V128: case TCG_TYPE_V256: @@ -2771,8 +2653,6 @@ void tcg_dump_ops(TCGContext *s, FILE *f, bool have_prefs) { case INDEX_op_setcond: case INDEX_op_negsetcond: case INDEX_op_movcond: - case INDEX_op_brcond2_i32: - case INDEX_op_setcond2_i32: case INDEX_op_cmp_vec: case INDEX_op_cmpsel_vec: if (op->args[k] < ARRAY_SIZE(cond_name) && cond_name[op->args[k]]) { @@ -2846,7 +2726,6 @@ void tcg_dump_ops(TCGContext *s, FILE *f, bool have_prefs) { case INDEX_op_set_label: case INDEX_op_br: case INDEX_op_brcond: - case INDEX_op_brcond2_i32: col += ne_fprintf(f, "%s$L%d", k ? "," : "", arg_label(op->args[k])->id); i++, k++; break; @@ -3150,7 +3029,7 @@ static void process_constraint_sets(void) { args_ct[i].regs |= MASK; \ break; -#include "i386/tcg-target-con-str.h" +#include "x86_64/tcg-target-con-str.h" #undef REGS #undef CONST @@ -3246,10 +3125,7 @@ static void process_constraint_sets(void) { } } -static const TCGArgConstraint *opcode_args_ct(const TCGOp *op) { - TCGOpcode opc = op->opc; - TCGType type = TCGOP_TYPE(op); - unsigned flags = TCGOP_FLAGS(op); +static const TCGArgConstraint *op_args_ct(TCGOpcode opc, TCGType type, unsigned flags) { const TCGOpDef *def = &tcg_op_defs[opc]; const TCGOutOp *outop = all_outop[opc]; TCGConstraintSetIndex con_set; @@ -3276,6 +3152,19 @@ static const TCGArgConstraint *opcode_args_ct(const TCGOp *op) { return all_cts[con_set]; } +static const TCGArgConstraint *opcode_args_ct(const TCGOp *op) { + return op_args_ct(op->opc, TCGOP_TYPE(op), TCGOP_FLAGS(op)); +} + +bool tcg_op_imm_match(TCGOpcode opc, TCGType type, tcg_target_ulong imm) { + const TCGArgConstraint *args_ct = op_args_ct(opc, type, 0); + const TCGOpDef *def = &tcg_op_defs[opc]; + + tcg_debug_assert(def->nb_oargs == 1); + tcg_debug_assert(def->nb_iargs == 2); + return tcg_target_const_match(imm, args_ct[2].ct, type, 0, 0); +} + static void remove_label_use(TCGOp *op, int idx) { TCGLabel *label = arg_label(op->args[idx]); TCGLabelUse *use; @@ -3297,9 +3186,6 @@ void tcg_op_remove(TCGContext *s, TCGOp *op) { case INDEX_op_brcond: remove_label_use(op, 3); break; - case INDEX_op_brcond2_i32: - remove_label_use(op, 5); - break; default: break; } @@ -3390,9 +3276,6 @@ static void move_label_uses(TCGLabel *to, TCGLabel *from) { case INDEX_op_brcond: op->args[3] = label_arg(to); break; - case INDEX_op_brcond2_i32: - op->args[5] = label_arg(to); - break; default: g_assert_not_reached(); } @@ -4942,11 +4825,7 @@ static void tcg_reg_alloc_op(TCGContext *s, const TCGOp *op) { case INDEX_op_cmp_vec: op_cond = op->args[3]; break; - case INDEX_op_brcond2_i32: - op_cond = op->args[4]; - break; case INDEX_op_movcond: - case INDEX_op_setcond2_i32: case INDEX_op_cmpsel_vec: op_cond = op->args[5]; break; @@ -5307,8 +5186,6 @@ static void tcg_reg_alloc_op(TCGContext *s, const TCGOp *op) { case INDEX_op_extu_i32_i64: case INDEX_op_extrl_i64_i32: case INDEX_op_extrh_i64_i32: - assert(TCG_TARGET_REG_BITS == 64); - /* fall through */ case INDEX_op_ctpop: case INDEX_op_neg: case INDEX_op_not: { @@ -5456,31 +5333,6 @@ static void tcg_reg_alloc_op(TCGContext *s, const TCGOp *op) { } } break; -#if TCG_TARGET_REG_BITS == 32 - case INDEX_op_brcond2_i32: { - const TCGOutOpBrcond2 *out = &outop_brcond2; - TCGCond cond = new_args[4]; - TCGLabel *label = arg_label(new_args[5]); - - tcg_debug_assert(!const_args[0]); - tcg_debug_assert(!const_args[1]); - out->out(s, cond, new_args[0], new_args[1], new_args[2], const_args[2], new_args[3], const_args[3], label); - } break; - case INDEX_op_setcond2_i32: { - const TCGOutOpSetcond2 *out = &outop_setcond2; - TCGCond cond = new_args[5]; - - tcg_debug_assert(!const_args[1]); - tcg_debug_assert(!const_args[2]); - out->out(s, cond, new_args[0], new_args[1], new_args[2], new_args[3], const_args[3], new_args[4], - const_args[4]); - } break; -#else - case INDEX_op_brcond2_i32: - case INDEX_op_setcond2_i32: - g_assert_not_reached(); -#endif - case INDEX_op_goto_ptr: tcg_debug_assert(!const_args[0]); tcg_out_goto_ptr(s, new_args[0]); @@ -5514,89 +5366,6 @@ static void tcg_reg_alloc_op(TCGContext *s, const TCGOp *op) { } } -static bool tcg_reg_alloc_dup2(TCGContext *s, const TCGOp *op) { - const TCGLifeData arg_life = op->life; - TCGTemp *ots, *itsl, *itsh; - TCGType vtype = TCGOP_TYPE(op); - - /* This opcode is only valid for 32-bit hosts, for 64-bit elements. */ - tcg_debug_assert(TCG_TARGET_REG_BITS == 32); - tcg_debug_assert(TCGOP_VECE(op) == MO_64); - - ots = arg_temp(op->args[0]); - itsl = arg_temp(op->args[1]); - itsh = arg_temp(op->args[2]); - - /* ENV should not be modified. */ - tcg_debug_assert(!temp_readonly(ots)); - - /* Allocate the output register now. */ - if (ots->val_type != TEMP_VAL_REG) { - TCGRegSet allocated_regs = s->reserved_regs; - TCGRegSet dup_out_regs = opcode_args_ct(op)[0].regs; - TCGReg oreg; - - /* Make sure to not spill the input registers. */ - if (!IS_DEAD_ARG(1) && itsl->val_type == TEMP_VAL_REG) { - tcg_regset_set_reg(allocated_regs, itsl->reg); - } - if (!IS_DEAD_ARG(2) && itsh->val_type == TEMP_VAL_REG) { - tcg_regset_set_reg(allocated_regs, itsh->reg); - } - - oreg = tcg_reg_alloc(s, dup_out_regs, allocated_regs, output_pref(op, 0), ots->indirect_base); - set_temp_val_reg(s, ots, oreg); - } - - /* Promote dup2 of immediates to dupi_vec. */ - if (itsl->val_type == TEMP_VAL_CONST && itsh->val_type == TEMP_VAL_CONST) { - uint64_t val = deposit64(itsl->val, 32, 32, itsh->val); - MemOp vece = MO_64; - - if (val == dup_const(MO_8, val)) { - vece = MO_8; - } else if (val == dup_const(MO_16, val)) { - vece = MO_16; - } else if (val == dup_const(MO_32, val)) { - vece = MO_32; - } - - tcg_out_dupi_vec(s, vtype, vece, ots->reg, val); - goto done; - } - - /* If the two inputs form one 64-bit value, try dupm_vec. */ - if (itsl->temp_subindex == HOST_BIG_ENDIAN && itsh->temp_subindex == !HOST_BIG_ENDIAN && - itsl == itsh + (HOST_BIG_ENDIAN ? 1 : -1)) { - TCGTemp *its = itsl - HOST_BIG_ENDIAN; - - temp_sync(s, its + 0, s->reserved_regs, 0, 0); - temp_sync(s, its + 1, s->reserved_regs, 0, 0); - - if (tcg_out_dupm_vec(s, vtype, MO_64, ots->reg, its->mem_base->reg, its->mem_offset)) { - goto done; - } - } - - /* Fall back to generic expansion. */ - return false; - -done: - ots->mem_coherent = 0; - if (IS_DEAD_ARG(1)) { - temp_dead(s, itsl); - } - if (IS_DEAD_ARG(2)) { - temp_dead(s, itsh); - } - if (NEED_SYNC_ARG(0)) { - temp_sync(s, ots, s->reserved_regs, 0, IS_DEAD_ARG(0)); - } else if (IS_DEAD_ARG(0)) { - temp_dead(s, ots); - } - return true; -} - static void load_arg_reg(TCGContext *s, TCGReg reg, TCGTemp *ts, TCGRegSet allocated_regs) { if (ts->val_type == TEMP_VAL_REG) { if (ts->reg != reg) { @@ -5871,7 +5640,7 @@ static int tcg_out_helper_stk_ofs(TCGType type, unsigned slot) { * Each stack slot is TCG_TARGET_LONG_BITS. If the host does not * require extension to uint64_t, adjust the address for uint32_t. */ - if (HOST_BIG_ENDIAN && TCG_TARGET_REG_BITS == 64 && type == TCG_TYPE_I32) { + if (HOST_BIG_ENDIAN && type == TCG_TYPE_I32) { ofs += 4; } return ofs; @@ -6062,13 +5831,8 @@ static unsigned tcg_out_helper_add_mov(TCGMovExtend *mov, const TCGCallArgumentL return 1; } - if (TCG_TARGET_REG_BITS == 32) { - assert(dst_type == TCG_TYPE_I64); - reg_mo = MO_32; - } else { - assert(dst_type == TCG_TYPE_I128); - reg_mo = MO_64; - } + assert(dst_type == TCG_TYPE_I128); + reg_mo = MO_64; mov[0].dst = loc[HOST_BIG_ENDIAN].arg_slot; mov[0].src = lo; @@ -6112,22 +5876,9 @@ static void tcg_out_ld_helper_args(TCGContext *s, const TCGLabelQemuLdst *ldst, next_arg = 1; loc = &info->in[next_arg]; - if (TCG_TARGET_REG_BITS == 32 && s->addr_type == TCG_TYPE_I32) { - /* - * 32-bit host with 32-bit guest: zero-extend the guest address - * to 64-bits for the helper by storing the low part, then - * load a zero for the high part. - */ - tcg_out_helper_add_mov(mov, loc + HOST_BIG_ENDIAN, TCG_TYPE_I32, TCG_TYPE_I32, ldst->addr_reg, -1); - tcg_out_helper_load_slots(s, 1, mov, parm); - - tcg_out_helper_load_imm(s, loc[!HOST_BIG_ENDIAN].arg_slot, TCG_TYPE_I32, 0, parm); - next_arg += 2; - } else { - nmov = tcg_out_helper_add_mov(mov, loc, TCG_TYPE_I64, s->addr_type, ldst->addr_reg, -1); - tcg_out_helper_load_slots(s, nmov, mov, parm); - next_arg += nmov; - } + nmov = tcg_out_helper_add_mov(mov, loc, TCG_TYPE_I64, s->addr_type, ldst->addr_reg, -1); + tcg_out_helper_load_slots(s, nmov, mov, parm); + next_arg += nmov; switch (info->out_kind) { case TCG_CALL_RET_NORMAL: @@ -6164,13 +5915,8 @@ static void tcg_out_ld_helper_ret(TCGContext *s, const TCGLabelQemuLdst *ldst, b int ofs_slot0; switch (ldst->type) { - case TCG_TYPE_I64: - if (TCG_TARGET_REG_BITS == 32) { - break; - } - /* fall through */ - case TCG_TYPE_I32: + case TCG_TYPE_I64: mov[0].dst = ldst->datalo_reg; mov[0].src = tcg_target_call_oarg_reg(TCG_CALL_RET_NORMAL, 0); mov[0].dst_type = ldst->type; @@ -6187,7 +5933,7 @@ static void tcg_out_ld_helper_ret(TCGContext *s, const TCGLabelQemuLdst *ldst, b * helper functions. */ if (load_sign || !(mop & MO_SIGN)) { - if (TCG_TARGET_REG_BITS == 32 || ldst->type == TCG_TYPE_I32) { + if (ldst->type == TCG_TYPE_I32) { mov[0].src_ext = MO_32; } else { mov[0].src_ext = MO_64; @@ -6199,7 +5945,6 @@ static void tcg_out_ld_helper_ret(TCGContext *s, const TCGLabelQemuLdst *ldst, b return; case TCG_TYPE_I128: - tcg_debug_assert(TCG_TARGET_REG_BITS == 64); ofs_slot0 = TCG_TARGET_CALL_STACK_OFFSET; switch (TCG_TARGET_CALL_RET_I128) { case TCG_CALL_RET_NORMAL: @@ -6225,13 +5970,13 @@ static void tcg_out_ld_helper_ret(TCGContext *s, const TCGLabelQemuLdst *ldst, b mov[0].src = tcg_target_call_oarg_reg(TCG_CALL_RET_NORMAL, HOST_BIG_ENDIAN); mov[0].dst_type = TCG_TYPE_REG; mov[0].src_type = TCG_TYPE_REG; - mov[0].src_ext = TCG_TARGET_REG_BITS == 32 ? MO_32 : MO_64; + mov[0].src_ext = MO_64; mov[1].dst = ldst->datahi_reg; mov[1].src = tcg_target_call_oarg_reg(TCG_CALL_RET_NORMAL, !HOST_BIG_ENDIAN); mov[1].dst_type = TCG_TYPE_REG; mov[1].src_type = TCG_TYPE_REG; - mov[1].src_ext = TCG_TARGET_REG_BITS == 32 ? MO_32 : MO_64; + mov[1].src_ext = MO_64; tcg_out_movext2(s, mov, mov + 1, parm->ntmp ? parm->tmp[0] : -1); } @@ -6270,21 +6015,9 @@ static void tcg_out_st_helper_args(TCGContext *s, const TCGLabelQemuLdst *ldst, /* Handle addr argument. */ loc = &info->in[next_arg]; tcg_debug_assert(s->addr_type <= TCG_TYPE_REG); - if (TCG_TARGET_REG_BITS == 32) { - /* - * 32-bit host (and thus 32-bit guest): zero-extend the guest address - * to 64-bits for the helper by storing the low part. Later, - * after we have processed the register inputs, we will load a - * zero for the high part. - */ - tcg_out_helper_add_mov(mov, loc + HOST_BIG_ENDIAN, TCG_TYPE_I32, TCG_TYPE_I32, ldst->addr_reg, -1); - next_arg += 2; - nmov += 1; - } else { - n = tcg_out_helper_add_mov(mov, loc, TCG_TYPE_I64, s->addr_type, ldst->addr_reg, -1); - next_arg += n; - nmov += n; - } + n = tcg_out_helper_add_mov(mov, loc, TCG_TYPE_I64, s->addr_type, ldst->addr_reg, -1); + next_arg += n; + nmov += n; /* Handle data argument. */ loc = &info->in[next_arg]; @@ -6299,7 +6032,6 @@ static void tcg_out_st_helper_args(TCGContext *s, const TCGLabelQemuLdst *ldst, break; case TCG_CALL_ARG_BY_REF: - tcg_debug_assert(TCG_TARGET_REG_BITS == 64); tcg_debug_assert(data_type == TCG_TYPE_I128); tcg_out_st(s, TCG_TYPE_I64, HOST_BIG_ENDIAN ? ldst->datahi_reg : ldst->datalo_reg, TCG_REG_CALL_STACK, arg_slot_stk_ofs(loc[0].ref_slot)); @@ -6323,12 +6055,6 @@ static void tcg_out_st_helper_args(TCGContext *s, const TCGLabelQemuLdst *ldst, g_assert_not_reached(); } - if (TCG_TARGET_REG_BITS == 32) { - /* Zero extend the address by loading a zero for the high part. */ - loc = &info->in[1 + !HOST_BIG_ENDIAN]; - tcg_out_helper_load_imm(s, loc->arg_slot, TCG_TYPE_I32, 0, parm); - } - tcg_out_helper_load_common_args(s, ldst, parm, info, next_arg); } @@ -6430,7 +6156,6 @@ int tcg_gen_code(TCGContext *s, TranslationBlock *tb, uint64_t pc_start) { switch (opc) { case INDEX_op_extrl_i64_i32: - assert(TCG_TARGET_REG_BITS == 64); /* * If TCG_TYPE_I32 is represented in some canonical form, * e.g. zero or sign-extended, then emit as a unary op. @@ -6488,11 +6213,6 @@ int tcg_gen_code(TCGContext *s, TranslationBlock *tb, uint64_t pc_start) { case INDEX_op_mb: tcg_out_mb(s, op->args[0]); break; - case INDEX_op_dup2_vec: - if (tcg_reg_alloc_dup2(s, op)) { - break; - } - /* fall through */ default: do_default: /* Sanity check that we've not introduced any unhandled opcodes. */ diff --git a/libtcg/src/i386/tcg-target-con-set.h b/libtcg/src/x86_64/tcg-target-con-set.h similarity index 100% rename from libtcg/src/i386/tcg-target-con-set.h rename to libtcg/src/x86_64/tcg-target-con-set.h diff --git a/libtcg/src/i386/tcg-target-con-str.h b/libtcg/src/x86_64/tcg-target-con-str.h similarity index 100% rename from libtcg/src/i386/tcg-target-con-str.h rename to libtcg/src/x86_64/tcg-target-con-str.h diff --git a/libtcg/src/i386/tcg-target.c.inc b/libtcg/src/x86_64/tcg-target.c.inc similarity index 88% rename from libtcg/src/i386/tcg-target.c.inc rename to libtcg/src/x86_64/tcg-target.c.inc index 06e7c875c..72e063448 100644 --- a/libtcg/src/i386/tcg-target.c.inc +++ b/libtcg/src/x86_64/tcg-target.c.inc @@ -34,31 +34,20 @@ #if defined(_WIN64) #define TCG_TARGET_CALL_ARG_I128 TCG_CALL_ARG_BY_REF #define TCG_TARGET_CALL_RET_I128 TCG_CALL_RET_BY_VEC -#elif TCG_TARGET_REG_BITS == 64 -#define TCG_TARGET_CALL_ARG_I128 TCG_CALL_ARG_NORMAL -#define TCG_TARGET_CALL_RET_I128 TCG_CALL_RET_NORMAL #else #define TCG_TARGET_CALL_ARG_I128 TCG_CALL_ARG_NORMAL -#define TCG_TARGET_CALL_RET_I128 TCG_CALL_RET_BY_REF +#define TCG_TARGET_CALL_RET_I128 TCG_CALL_RET_NORMAL #endif #ifdef CONFIG_DEBUG_TCG static const char *const tcg_target_reg_names[TCG_TARGET_NB_REGS] = { -#if TCG_TARGET_REG_BITS == 64 - "%rax", "%rcx", "%rdx", "%rbx", "%rsp", "%rbp", "%rsi", "%rdi", -#else - "%eax", "%ecx", "%edx", "%ebx", "%esp", "%ebp", "%esi", "%edi", -#endif - "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", - "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7", -#if TCG_TARGET_REG_BITS == 64 - "%xmm8", "%xmm9", "%xmm10", "%xmm11", "%xmm12", "%xmm13", "%xmm14", "%xmm15", -#endif + "%rax", "%rcx", "%rdx", "%rbx", "%rsp", "%rbp", "%rsi", "%rdi", "%r8", "%r9", "%r10", + "%r11", "%r12", "%r13", "%r14", "%r15", "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", + "%xmm6", "%xmm7", "%xmm8", "%xmm9", "%xmm10", "%xmm11", "%xmm12", "%xmm13", "%xmm14", "%xmm15", }; #endif static const int tcg_target_reg_alloc_order[] = { -#if TCG_TARGET_REG_BITS == 64 TCG_REG_RBP, TCG_REG_RBX, TCG_REG_R12, @@ -74,9 +63,6 @@ static const int tcg_target_reg_alloc_order[] = { TCG_REG_RSI, TCG_REG_RDI, TCG_REG_RAX, -#else - TCG_REG_EBX, TCG_REG_ESI, TCG_REG_EDI, TCG_REG_EBP, TCG_REG_ECX, TCG_REG_EDX, TCG_REG_EAX, -#endif TCG_REG_XMM0, TCG_REG_XMM1, TCG_REG_XMM2, @@ -88,7 +74,6 @@ static const int tcg_target_reg_alloc_order[] = { any of them. Therefore only allow xmm0-xmm5 to be allocated. */ TCG_REG_XMM6, TCG_REG_XMM7, -#if TCG_TARGET_REG_BITS == 64 TCG_REG_XMM8, TCG_REG_XMM9, TCG_REG_XMM10, @@ -98,13 +83,11 @@ static const int tcg_target_reg_alloc_order[] = { TCG_REG_XMM14, TCG_REG_XMM15, #endif -#endif }; #define TCG_TMP_VEC TCG_REG_XMM5 static const int tcg_target_call_iarg_regs[] = { -#if TCG_TARGET_REG_BITS == 64 #if defined(_WIN64) TCG_REG_RCX, TCG_REG_RDX, @@ -113,9 +96,6 @@ static const int tcg_target_call_iarg_regs[] = { #endif TCG_REG_R8, TCG_REG_R9, -#else -/* 32 bit mode uses stack based calling convention (GCC default). */ -#endif }; static TCGReg tcg_target_call_oarg_reg(TCGCallReturnKind kind, int slot) { @@ -141,26 +121,13 @@ static TCGReg tcg_target_call_oarg_reg(TCGCallReturnKind kind, int slot) { #define TCG_CT_CONST_TST 0x1000 #define TCG_CT_CONST_ZERO 0x2000 -/* Registers used with L constraint, which are the first argument - registers on x86_64, and two random call clobbered registers on - i386. */ -#if TCG_TARGET_REG_BITS == 64 +/* Registers used with L constraint. */ #define TCG_REG_L0 tcg_target_call_iarg_regs[0] #define TCG_REG_L1 tcg_target_call_iarg_regs[1] -#else -#define TCG_REG_L0 TCG_REG_EAX -#define TCG_REG_L1 TCG_REG_EDX -#endif -#if TCG_TARGET_REG_BITS == 64 -#define ALL_GENERAL_REGS 0x0000ffffu -#define ALL_VECTOR_REGS 0xffff0000u -#define ALL_BYTEL_REGS ALL_GENERAL_REGS -#else -#define ALL_GENERAL_REGS 0x000000ffu -#define ALL_VECTOR_REGS 0x00ff0000u -#define ALL_BYTEL_REGS 0x0000000fu -#endif +#define ALL_GENERAL_REGS 0x0000ffffu +#define ALL_VECTOR_REGS 0xffff0000u +#define ALL_BYTEL_REGS ALL_GENERAL_REGS #define SOFTMMU_RESERVE_REGS (tcg_use_softmmu ? (1 << TCG_REG_L0) | (1 << TCG_REG_L1) : 0) #define have_bmi2 (cpuinfo & CPUINFO_BMI2) @@ -176,8 +143,6 @@ static bool patch_reloc(tcg_insn_unit *code_ptr, int type, intptr_t value, intpt if (value != (int32_t) value) { return false; } - /* FALLTHRU */ - case R_386_32: tcg_patch32(code_ptr, value); break; case R_386_PC8: @@ -233,26 +198,19 @@ static bool tcg_target_const_match(int64_t val, int ct, TCGType type, TCGCond co #define LOWREGMASK(x) ((x) & 7) -#define P_EXT 0x100 /* 0x0f opcode prefix */ -#define P_EXT38 0x200 /* 0x0f 0x38 opcode prefix */ -#define P_DATA16 0x400 /* 0x66 opcode prefix */ -#define P_VEXW 0x1000 /* Set VEX.W = 1 */ -#if TCG_TARGET_REG_BITS == 64 -#define P_REXW P_VEXW /* Set REX.W = 1; match VEXW */ -#define P_REXB_R 0x2000 /* REG field as byte register */ -#define P_REXB_RM 0x4000 /* R/M field as byte register */ -#define P_GS 0x8000 /* gs segment override */ -#else -#define P_REXW 0 -#define P_REXB_R 0 -#define P_REXB_RM 0 -#define P_GS 0 -#endif -#define P_EXT3A 0x10000 /* 0x0f 0x3a opcode prefix */ -#define P_SIMDF3 0x20000 /* 0xf3 opcode prefix */ -#define P_SIMDF2 0x40000 /* 0xf2 opcode prefix */ -#define P_VEXL 0x80000 /* Set VEX.L = 1 */ -#define P_EVEX 0x100000 /* Requires EVEX encoding */ +#define P_EXT 0x100 /* 0x0f opcode prefix */ +#define P_EXT38 0x200 /* 0x0f 0x38 opcode prefix */ +#define P_DATA16 0x400 /* 0x66 opcode prefix */ +#define P_VEXW 0x1000 /* Set VEX.W = 1 */ +#define P_REXW P_VEXW /* Set REX.W = 1; match VEXW */ +#define P_REXB_R 0x2000 /* REG field as byte register */ +#define P_REXB_RM 0x4000 /* R/M field as byte register */ +#define P_GS 0x8000 /* gs segment override */ +#define P_EXT3A 0x10000 /* 0x0f 0x3a opcode prefix */ +#define P_SIMDF3 0x20000 /* 0xf3 opcode prefix */ +#define P_SIMDF2 0x40000 /* 0xf2 opcode prefix */ +#define P_VEXL 0x80000 /* Set VEX.L = 1 */ +#define P_EVEX 0x100000 /* Requires EVEX encoding */ #define OPC_ARITH_EbIb (0x80) #define OPC_ARITH_EvIz (0x81) @@ -543,7 +501,6 @@ static const uint8_t tcg_cond_to_jcc[] = { [TCG_COND_LEU] = JCC_JBE, [TCG_COND_GTU] = JCC_JA, [TCG_COND_TSTEQ] = JCC_JE, [TCG_COND_TSTNE] = JCC_JNE, }; -#if TCG_TARGET_REG_BITS == 64 static void tcg_out_opc(TCGContext *s, int opc, int r, int rm, int x) { int rex; @@ -590,31 +547,6 @@ static void tcg_out_opc(TCGContext *s, int opc, int r, int rm, int x) { tcg_out8(s, opc); } -#else -static void tcg_out_opc(TCGContext *s, int opc) { - if (opc & P_DATA16) { - tcg_out8(s, 0x66); - } - if (opc & P_SIMDF3) { - tcg_out8(s, 0xf3); - } else if (opc & P_SIMDF2) { - tcg_out8(s, 0xf2); - } - if (opc & (P_EXT | P_EXT38 | P_EXT3A)) { - tcg_out8(s, 0x0f); - if (opc & P_EXT38) { - tcg_out8(s, 0x38); - } else if (opc & P_EXT3A) { - tcg_out8(s, 0x3a); - } - } - tcg_out8(s, opc); -} -/* Discard the register arguments to tcg_out_opc early, so as not to penalize - the 32-bit compilation paths. This method works with all versions of gcc, - whereas relying on optimization may not be able to exclude them. */ -#define tcg_out_opc(s, opc, r, rm, x) (tcg_out_opc)(s, opc) -#endif static void tcg_out_modrm(TCGContext *s, int opc, int r, int rm) { tcg_out_opc(s, opc, r, rm, 0); @@ -747,35 +679,32 @@ static void tcg_out_sib_offset(TCGContext *s, int r, int rm, int index, int shif int mod, len; if (index < 0 && rm < 0) { - if (TCG_TARGET_REG_BITS == 64) { - /* Try for a rip-relative addressing mode. This has replaced - the 32-bit-mode absolute addressing encoding. */ - intptr_t pc = (intptr_t) s->code_ptr + 5 + ~rm; - intptr_t disp = offset - pc; - if (disp == (int32_t) disp) { - tcg_out8(s, (LOWREGMASK(r) << 3) | 5); - tcg_out32(s, disp); - return; - } - - /* Try for an absolute address encoding. This requires the - use of the MODRM+SIB encoding and is therefore larger than - rip-relative addressing. */ - if (offset == (int32_t) offset) { - tcg_out8(s, (LOWREGMASK(r) << 3) | 4); - tcg_out8(s, (4 << 3) | 5); - tcg_out32(s, offset); - return; - } + /* + * Try for a rip-relative addressing mode. This has replaced + * the 32-bit-mode absolute addressing encoding. + */ + intptr_t pc = (intptr_t) s->code_ptr + 5 + ~rm; + intptr_t disp = offset - pc; + if (disp == (int32_t) disp) { + tcg_out8(s, (LOWREGMASK(r) << 3) | 5); + tcg_out32(s, disp); + return; + } - /* ??? The memory isn't directly addressable. */ - g_assert_not_reached(); - } else { - /* Absolute address. */ - tcg_out8(s, (r << 3) | 5); + /* + * Try for an absolute address encoding. This requires the + * use of the MODRM+SIB encoding and is therefore larger than + * rip-relative addressing. + */ + if (offset == (int32_t) offset) { + tcg_out8(s, (LOWREGMASK(r) << 3) | 4); + tcg_out8(s, (4 << 3) | 5); tcg_out32(s, offset); return; } + + /* ??? The memory isn't directly addressable. */ + g_assert_not_reached(); } /* Find the length of the immediate addend. Note that the encoding @@ -985,27 +914,14 @@ static void tcg_out_dupi_vec(TCGContext *s, TCGType type, unsigned vece, TCGReg return; } - if (TCG_TARGET_REG_BITS == 32 && vece < MO_64) { - if (have_avx2) { - tcg_out_vex_modrm_pool(s, OPC_VPBROADCASTD + vex_l, ret); - } else { - tcg_out_vex_modrm_pool(s, OPC_VBROADCASTSS, ret); - } - new_pool_label(s, arg, R_386_32, s->code_ptr - 4, 0); + if (type == TCG_TYPE_V64) { + tcg_out_vex_modrm_pool(s, OPC_MOVQ_VqWq, ret); + } else if (have_avx2) { + tcg_out_vex_modrm_pool(s, OPC_VPBROADCASTQ + vex_l, ret); } else { - if (type == TCG_TYPE_V64) { - tcg_out_vex_modrm_pool(s, OPC_MOVQ_VqWq, ret); - } else if (have_avx2) { - tcg_out_vex_modrm_pool(s, OPC_VPBROADCASTQ + vex_l, ret); - } else { - tcg_out_vex_modrm_pool(s, OPC_MOVDDUP, ret); - } - if (TCG_TARGET_REG_BITS == 64) { - new_pool_label(s, arg, R_386_PC32, s->code_ptr - 4, -4); - } else { - new_pool_l2(s, R_386_32, s->code_ptr - 4, 0, arg, arg >> 32); - } + tcg_out_vex_modrm_pool(s, OPC_MOVDDUP, ret); } + new_pool_label(s, arg, R_386_PC32, s->code_ptr - 4, -4); } static void tcg_out_movi_vec(TCGContext *s, TCGType type, TCGReg ret, tcg_target_long arg) { @@ -1020,11 +936,7 @@ static void tcg_out_movi_vec(TCGContext *s, TCGType type, TCGReg ret, tcg_target int rexw = (type == TCG_TYPE_I32 ? 0 : P_REXW); tcg_out_vex_modrm_pool(s, OPC_MOVD_VyEy + rexw, ret); - if (TCG_TARGET_REG_BITS == 64) { - new_pool_label(s, arg, R_386_PC32, s->code_ptr - 4, -4); - } else { - new_pool_label(s, arg, R_386_32, s->code_ptr - 4, 0); - } + new_pool_label(s, arg, R_386_PC32, s->code_ptr - 4, -4); } static void tcg_out_movi_int(TCGContext *s, TCGType type, TCGReg ret, tcg_target_long arg) { @@ -1061,9 +973,7 @@ static void tcg_out_movi_int(TCGContext *s, TCGType type, TCGReg ret, tcg_target static void tcg_out_movi(TCGContext *s, TCGType type, TCGReg ret, tcg_target_long arg) { switch (type) { case TCG_TYPE_I32: -#if TCG_TARGET_REG_BITS == 64 case TCG_TYPE_I64: -#endif if (ret < 16) { tcg_out_movi_int(s, type, ret, arg); } else { @@ -1211,7 +1121,7 @@ static void tcg_out_st(TCGContext *s, TCGType type, TCGReg arg, TCGReg arg1, int static bool tcg_out_sti(TCGContext *s, TCGType type, TCGArg val, TCGReg base, intptr_t ofs) { int rexw = 0; - if (TCG_TARGET_REG_BITS == 64 && type == TCG_TYPE_I64) { + if (type == TCG_TYPE_I64) { if (val != (int32_t) val) { return false; } @@ -1246,30 +1156,11 @@ static inline void tcg_out_rolw_8(TCGContext *s, int reg) { } static void tcg_out_ext8u(TCGContext *s, TCGReg dest, TCGReg src) { - if (TCG_TARGET_REG_BITS == 32 && src >= 4) { - tcg_out_mov(s, TCG_TYPE_I32, dest, src); - if (dest >= 4) { - tcg_out_modrm(s, OPC_ARITH_EvIz, ARITH_AND, dest); - tcg_out32(s, 0xff); - return; - } - src = dest; - } tcg_out_modrm(s, OPC_MOVZBL + P_REXB_RM, dest, src); } static void tcg_out_ext8s(TCGContext *s, TCGType type, TCGReg dest, TCGReg src) { int rexw = type == TCG_TYPE_I32 ? 0 : P_REXW; - - if (TCG_TARGET_REG_BITS == 32 && src >= 4) { - tcg_out_mov(s, TCG_TYPE_I32, dest, src); - if (dest >= 4) { - tcg_out_shifti(s, SHIFT_SHL, dest, 24); - tcg_out_shifti(s, SHIFT_SAR, dest, 24); - return; - } - src = dest; - } tcg_out_modrm(s, OPC_MOVSBL + P_REXB_RM + rexw, dest, src); } @@ -1290,7 +1181,6 @@ static void tcg_out_ext32u(TCGContext *s, TCGReg dest, TCGReg src) { } static void tcg_out_ext32s(TCGContext *s, TCGReg dest, TCGReg src) { - tcg_debug_assert(TCG_TARGET_REG_BITS == 64); tcg_out_modrm(s, OPC_MOVSLQ, dest, src); } @@ -1313,12 +1203,9 @@ static inline void tcg_out_bswap64(TCGContext *s, int reg) { } static void tgen_arithi(TCGContext *s, int c, int r0, tcg_target_long val, int cf) { - int rexw = 0; + int rexw = c & -8; - if (TCG_TARGET_REG_BITS == 64) { - rexw = c & -8; - c &= 7; - } + c &= 7; switch (c) { case ARITH_ADD: @@ -1331,15 +1218,11 @@ static void tgen_arithi(TCGContext *s, int c, int r0, tcg_target_long val, int c */ if (val == 1 || val == -1) { int is_inc = (c == ARITH_ADD) ^ (val < 0); - if (TCG_TARGET_REG_BITS == 64) { - /* - * The single-byte increment encodings are re-tasked - * as the REX prefixes. Use the MODRM encoding. - */ - tcg_out_modrm(s, OPC_GRP5 + rexw, (is_inc ? EXT5_INC_Ev : EXT5_DEC_Ev), r0); - } else { - tcg_out8(s, (is_inc ? OPC_INC_r32 : OPC_DEC_r32) + r0); - } + /* + * The single-byte increment encodings are re-tasked + * as the REX prefixes. Use the MODRM encoding. + */ + tcg_out_modrm(s, OPC_GRP5 + rexw, (is_inc ? EXT5_INC_Ev : EXT5_DEC_Ev), r0); return; } if (val == 128) { @@ -1354,17 +1237,15 @@ static void tgen_arithi(TCGContext *s, int c, int r0, tcg_target_long val, int c break; case ARITH_AND: - if (TCG_TARGET_REG_BITS == 64) { - if (val == 0xffffffffu) { - tcg_out_ext32u(s, r0, r0); - return; - } - if (val == (uint32_t) val) { - /* AND with no high bits set can use a 32-bit operation. */ - rexw = 0; - } + if (val == 0xffffffffu) { + tcg_out_ext32u(s, r0, r0); + return; + } + if (val == (uint32_t) val) { + /* AND with no high bits set can use a 32-bit operation. */ + rexw = 0; } - if (val == 0xffu && (r0 < 4 || TCG_TARGET_REG_BITS == 64)) { + if (val == 0xffu) { tcg_out_ext8u(s, r0, r0); return; } @@ -1376,7 +1257,7 @@ static void tgen_arithi(TCGContext *s, int c, int r0, tcg_target_long val, int c case ARITH_OR: case ARITH_XOR: - if (val >= 0x80 && val <= 0xff && (r0 < 4 || TCG_TARGET_REG_BITS == 64)) { + if (val >= 0x80 && val <= 0xff) { tcg_out_modrm(s, OPC_ARITH_EbIb + P_REXB_RM, c, r0); tcg_out8(s, val); return; @@ -1474,7 +1355,7 @@ static int tcg_out_cmp(TCGContext *s, TCGCond cond, TCGArg arg1, TCGArg arg2, in return jz; } - if (arg2 <= 0xff && (TCG_TARGET_REG_BITS == 64 || arg1 < 4)) { + if (arg2 <= 0xff) { if (arg2 == 0x80) { tcg_out_modrm(s, OPC_TESTB | P_REXB_R, arg1, arg1); return js; @@ -1561,45 +1442,6 @@ static const TCGOutOpBrcond outop_brcond = { .out_ri = tgen_brcondi, }; -static void tcg_out_brcond2(TCGContext *s, TCGCond cond, TCGReg al, TCGReg ah, TCGArg bl, bool blconst, TCGArg bh, - bool bhconst, TCGLabel *label_this, bool small) { - TCGLabel *label_next = gen_new_label(); - - switch (cond) { - case TCG_COND_EQ: - case TCG_COND_TSTEQ: - tcg_out_brcond(s, 0, tcg_invert_cond(cond), al, bl, blconst, label_next, true); - tcg_out_brcond(s, 0, cond, ah, bh, bhconst, label_this, small); - break; - - case TCG_COND_NE: - case TCG_COND_TSTNE: - tcg_out_brcond(s, 0, cond, al, bl, blconst, label_this, small); - tcg_out_brcond(s, 0, cond, ah, bh, bhconst, label_this, small); - break; - - default: - tcg_out_brcond(s, 0, tcg_high_cond(cond), ah, bh, bhconst, label_this, small); - tcg_out_jxx(s, JCC_JNE, label_next, 1); - tcg_out_brcond(s, 0, tcg_unsigned_cond(cond), al, bl, blconst, label_this, small); - break; - } - tcg_out_label(s, label_next); -} - -static void tgen_brcond2(TCGContext *s, TCGCond cond, TCGReg al, TCGReg ah, TCGArg bl, bool blconst, TCGArg bh, - bool bhconst, TCGLabel *l) { - tcg_out_brcond2(s, cond, al, ah, bl, blconst, bh, bhconst, l, false); -} - -#if TCG_TARGET_REG_BITS != 32 -__attribute__((unused)) -#endif -static const TCGOutOpBrcond2 outop_brcond2 = { - .base.static_constraint = C_O0_I4(r, r, ri, ri), - .out = tgen_brcond2, -}; - static void tcg_out_setcond(TCGContext *s, TCGType type, TCGCond cond, TCGReg dest, TCGReg arg1, TCGArg arg2, bool const_arg2, bool neg) { int rexw = type == TCG_TYPE_I32 ? 0 : P_REXW; @@ -1741,47 +1583,6 @@ static const TCGOutOpSetcond outop_negsetcond = { .out_rri = tgen_negsetcondi, }; -static void tgen_setcond2(TCGContext *s, TCGCond cond, TCGReg ret, TCGReg al, TCGReg ah, TCGArg bl, bool const_bl, - TCGArg bh, bool const_bh) { - TCGLabel *label_over = gen_new_label(); - - if (ret == al || ret == ah || (!const_bl && ret == bl) || (!const_bh && ret == bh)) { - /* - * When the destination overlaps with one of the argument - * registers, don't do anything tricky. - */ - TCGLabel *label_true = gen_new_label(); - - tcg_out_brcond2(s, cond, al, ah, bl, const_bl, bh, const_bh, label_true, true); - - tcg_out_movi(s, TCG_TYPE_I32, ret, 0); - tcg_out_jxx(s, JCC_JMP, label_over, 1); - tcg_out_label(s, label_true); - - tcg_out_movi(s, TCG_TYPE_I32, ret, 1); - } else { - /* - * When the destination does not overlap one of the arguments, - * clear the destination first, jump if cond false, and emit an - * increment in the true case. This results in smaller code. - */ - tcg_out_movi(s, TCG_TYPE_I32, ret, 0); - - tcg_out_brcond2(s, tcg_invert_cond(cond), al, ah, bl, const_bl, bh, const_bh, label_over, true); - - tgen_arithi(s, ARITH_ADD, ret, 1, 0); - } - tcg_out_label(s, label_over); -} - -#if TCG_TARGET_REG_BITS != 32 -__attribute__((unused)) -#endif -static const TCGOutOpSetcond2 outop_setcond2 = { - .base.static_constraint = C_O1_I4(r, r, r, ri, ri), - .out = tgen_setcond2, -}; - static void tcg_out_cmov(TCGContext *s, int jcc, int rexw, TCGReg dest, TCGReg v1) { tcg_out_modrm(s, OPC_CMOVCC | jcc | rexw, dest, v1); } @@ -1818,22 +1619,6 @@ static void tcg_out_branch(TCGContext *s, int call, const tcg_insn_unit *dest) { static void tcg_out_call(TCGContext *s, const tcg_insn_unit *dest, const TCGHelperInfo *info) { tcg_out_branch(s, 1, dest); - -#ifndef _WIN32 - if (TCG_TARGET_REG_BITS == 32 && info->out_kind == TCG_CALL_RET_BY_REF) { - /* - * The sysv i386 abi for struct return places a reference as the - * first argument of the stack, and pops that argument with the - * return statement. Since we want to retain the aligned stack - * pointer for the callee, we do not want to actually push that - * argument before the call but rely on the normal store to the - * stack slot. But we do need to compensate for the pop in order - * to reset our correct stack pointer value. - * Pushing a garbage value back onto the stack is quickest. - */ - tcg_out_push(s, TCG_REG_EAX); - } -#endif } static void tcg_out_jmp(TCGContext *s, const tcg_insn_unit *dest) { @@ -1876,20 +1661,18 @@ bool tcg_target_has_memory_bswap(MemOp memop) { * Reject 16-byte memop with 16-byte atomicity, i.e. VMOVDQA, * but do allow a pair of 64-bit operations, i.e. MOVBEQ. */ - aa = atom_and_align_for_opc(tcg_ctx, memop, MO_ATOM_IFALIGN, true); + aa = atom_and_align_for_opc(tcg_ctx, memop, MO_ATOM_WITHIN16, true); return aa.atom < MO_128; } /* - * Because i686 has no register parameters and because x86_64 has xchg - * to handle addr/data register overlap, we have placed all input arguments - * before we need might need a scratch reg. + * Because x86_64 has xchg to handle addr/data register overlap, we have + * placed all input arguments before we need might need a scratch reg. * * Even then, a scratch is only needed for l->raddr. Rather than expose * a general-purpose scratch when we don't actually know it's available, * use the ra_gen hook to load into RAX if needed. */ -#if TCG_TARGET_REG_BITS == 64 static TCGReg ldst_ra_gen(TCGContext *s, const TCGLabelQemuLdst *l, int arg) { if (arg < 0) { arg = TCG_REG_RAX; @@ -1897,10 +1680,8 @@ static TCGReg ldst_ra_gen(TCGContext *s, const TCGLabelQemuLdst *l, int arg) { tcg_out_movi(s, TCG_TYPE_PTR, arg, (uintptr_t) l->raddr); return arg; } + static const TCGLdstHelperParam ldst_helper_param = {.ra_gen = ldst_ra_gen}; -#else -static const TCGLdstHelperParam ldst_helper_param = {}; -#endif static void tcg_out_vec_to_pair(TCGContext *s, TCGType type, TCGReg l, TCGReg h, TCGReg v) { int rexw = type == TCG_TYPE_I32 ? 0 : P_REXW; @@ -1966,7 +1747,7 @@ static bool tcg_out_qemu_st_slow_path(TCGContext *s, TCGLabelQemuLdst *l) { #ifdef CONFIG_USER_ONLY static HostAddress x86_guest_base = {.index = -1}; -#if defined(__x86_64__) && defined(__linux__) +#if defined(__linux__) #include #include int arch_prctl(int code, unsigned long addr); @@ -1977,7 +1758,7 @@ static inline int setup_guest_base_seg(void) { return 0; } #define setup_guest_base_seg setup_guest_base_seg -#elif defined(__x86_64__) && (defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) #include static inline int setup_guest_base_seg(void) { if (sysarch(AMD64_SET_GSBASE, &guest_base) == 0) { @@ -2020,7 +1801,7 @@ static TCGLabelQemuLdst *prepare_host_addr(TCGContext *s, HostAddress *h, TCGReg *h = x86_guest_base; } h->base = addr; - h->aa = atom_and_align_for_opc(s, opc, MO_ATOM_IFALIGN, s_bits == MO_128); + h->aa = atom_and_align_for_opc(s, opc, MO_ATOM_WITHIN16, s_bits == MO_128); a_mask = (1 << h->aa.align) - 1; if (tcg_use_softmmu) { @@ -2038,14 +1819,12 @@ static TCGLabelQemuLdst *prepare_host_addr(TCGContext *s, HostAddress *h, TCGReg ldst->oi = oi; ldst->addr_reg = addr; - if (TCG_TARGET_REG_BITS == 64) { - ttype = s->addr_type; - trexw = (ttype == TCG_TYPE_I32 ? 0 : P_REXW); - if (TCG_TYPE_PTR == TCG_TYPE_I64) { - hrexw = P_REXW; - tlbtype = TCG_TYPE_I64; - tlbrexw = P_REXW; - } + ttype = s->addr_type; + trexw = (ttype == TCG_TYPE_I32 ? 0 : P_REXW); + if (TCG_TYPE_PTR == TCG_TYPE_I64) { + hrexw = P_REXW; + tlbtype = TCG_TYPE_I64; + tlbrexw = P_REXW; } tcg_out_mov(s, tlbtype, TCG_REG_L0, addr); @@ -2147,7 +1926,6 @@ static void tcg_out_qemu_ld_direct(TCGContext *s, TCGReg datalo, TCGReg datahi, case MO_UL: tcg_out_modrm_sib_offset(s, movop + h.seg, datalo, h.base, h.index, 0, h.ofs); break; -#if TCG_TARGET_REG_BITS == 64 case MO_SL: if (use_movbe) { tcg_out_modrm_sib_offset(s, OPC_MOVBE_GyMy + h.seg, datalo, h.base, h.index, 0, h.ofs); @@ -2156,30 +1934,11 @@ static void tcg_out_qemu_ld_direct(TCGContext *s, TCGReg datalo, TCGReg datahi, tcg_out_modrm_sib_offset(s, OPC_MOVSLQ + h.seg, datalo, h.base, h.index, 0, h.ofs); } break; -#endif case MO_UQ: - if (TCG_TARGET_REG_BITS == 64) { - tcg_out_modrm_sib_offset(s, movop + P_REXW + h.seg, datalo, h.base, h.index, 0, h.ofs); - break; - } - if (use_movbe) { - TCGReg t = datalo; - datalo = datahi; - datahi = t; - } - if (h.base == datalo || h.index == datalo) { - tcg_out_modrm_sib_offset(s, OPC_LEA, datahi, h.base, h.index, 0, h.ofs); - tcg_out_modrm_offset(s, movop + h.seg, datalo, datahi, 0); - tcg_out_modrm_offset(s, movop + h.seg, datahi, datahi, 4); - } else { - tcg_out_modrm_sib_offset(s, movop + h.seg, datalo, h.base, h.index, 0, h.ofs); - tcg_out_modrm_sib_offset(s, movop + h.seg, datahi, h.base, h.index, 0, h.ofs + 4); - } + tcg_out_modrm_sib_offset(s, movop + P_REXW + h.seg, datalo, h.base, h.index, 0, h.ofs); break; case MO_128: - tcg_debug_assert(TCG_TARGET_REG_BITS == 64); - /* * Without 16-byte atomicity, use integer regs. * That is where we want the data, and it allows bswaps. @@ -2291,8 +2050,6 @@ static void tcg_out_qemu_st_direct(TCGContext *s, TCGReg datalo, TCGReg datahi, switch (memop & MO_SIZE) { case MO_8: - /* This is handled with constraints in cset_qemu_st(). */ - tcg_debug_assert(TCG_TARGET_REG_BITS == 64 || datalo < 4); tcg_out_modrm_sib_offset(s, OPC_MOVB_EvGv + P_REXB_R + h.seg, datalo, h.base, h.index, 0, h.ofs); break; case MO_16: @@ -2302,22 +2059,10 @@ static void tcg_out_qemu_st_direct(TCGContext *s, TCGReg datalo, TCGReg datahi, tcg_out_modrm_sib_offset(s, movop + h.seg, datalo, h.base, h.index, 0, h.ofs); break; case MO_64: - if (TCG_TARGET_REG_BITS == 64) { - tcg_out_modrm_sib_offset(s, movop + P_REXW + h.seg, datalo, h.base, h.index, 0, h.ofs); - } else { - if (use_movbe) { - TCGReg t = datalo; - datalo = datahi; - datahi = t; - } - tcg_out_modrm_sib_offset(s, movop + h.seg, datalo, h.base, h.index, 0, h.ofs); - tcg_out_modrm_sib_offset(s, movop + h.seg, datahi, h.base, h.index, 0, h.ofs + 4); - } + tcg_out_modrm_sib_offset(s, movop + P_REXW + h.seg, datalo, h.base, h.index, 0, h.ofs); break; case MO_128: - tcg_debug_assert(TCG_TARGET_REG_BITS == 64); - /* * Without 16-byte atomicity, use integer regs. * That is where we have the data, and it allows bswaps. @@ -2382,13 +2127,8 @@ static void tgen_qemu_st(TCGContext *s, TCGType type, TCGReg data, TCGReg addr, } } -static TCGConstraintSetIndex cset_qemu_st(TCGType type, unsigned flags) { - return flags == MO_8 ? C_O0_I2(s, L) : C_O0_I2(L, L); -} - static const TCGOutOpQemuLdSt outop_qemu_st = { - .base.static_constraint = TCG_TARGET_REG_BITS == 32 ? C_Dynamic : C_O0_I2(L, L), - .base.dynamic_constraint = TCG_TARGET_REG_BITS == 32 ? cset_qemu_st : NULL, + .base.static_constraint = C_O0_I2(L, L), .out = tgen_qemu_st, }; @@ -2693,7 +2433,6 @@ static const TCGOutOpBinary outop_eqv = { .base.static_constraint = C_NotImplemented, }; -#if TCG_TARGET_REG_BITS == 64 static void tgen_extrh_i64_i32(TCGContext *s, TCGType t, TCGReg a0, TCGReg a1) { tcg_out_shifti(s, SHIFT_SHR + P_REXW, a0, 32); } @@ -2702,7 +2441,6 @@ static const TCGOutOpUnary outop_extrh_i64_i32 = { .base.static_constraint = C_O1_I1(r, 0), .out_rr = tgen_extrh_i64_i32, }; -#endif /* TCG_TARGET_REG_BITS == 64 */ static void tgen_mul(TCGContext *s, TCGType type, TCGReg a0, TCGReg a1, TCGReg a2) { int rexw = type == TCG_TYPE_I32 ? 0 : P_REXW; @@ -3004,7 +2742,6 @@ static const TCGOutOpBswap outop_bswap32 = { .out_rr = tgen_bswap32, }; -#if TCG_TARGET_REG_BITS == 64 static void tgen_bswap64(TCGContext *s, TCGType type, TCGReg a0, TCGReg a1) { tcg_out_bswap64(s, a0); } @@ -3013,7 +2750,6 @@ static const TCGOutOpUnary outop_bswap64 = { .base.static_constraint = C_O1_I1(r, 0), .out_rr = tgen_bswap64, }; -#endif static void tgen_neg(TCGContext *s, TCGType type, TCGReg a0, TCGReg a1) { int rexw = type == TCG_TYPE_I32 ? 0 : P_REXW; @@ -3040,8 +2776,6 @@ static void tgen_deposit(TCGContext *s, TCGType type, TCGReg a0, TCGReg a1, TCGR tcg_out_modrm(s, OPC_MOVB_EvGv | P_REXB_R | P_REXB_RM, a2, a0); } else if (ofs == 0 && len == 16) { tcg_out_modrm(s, OPC_MOVL_EvGv | P_DATA16, a2, a0); - } else if (TCG_TARGET_REG_BITS == 32 && ofs == 8 && len == 8) { - tcg_out_modrm(s, OPC_MOVB_EvGv, a2, a0 + 4); } else { g_assert_not_reached(); } @@ -3055,9 +2789,6 @@ static void tgen_depositi(TCGContext *s, TCGType type, TCGReg a0, TCGReg a1, tcg } else if (ofs == 0 && len == 16) { tcg_out_opc(s, OPC_MOVL_Iv | P_DATA16 | LOWREGMASK(a0), 0, a0, 0); tcg_out16(s, a2); - } else if (TCG_TARGET_REG_BITS == 32 && ofs == 8 && len == 8) { - tcg_out8(s, OPC_MOVB_Ib + a0 + 4); - tcg_out8(s, a2); } else { g_assert_not_reached(); } @@ -3082,7 +2813,7 @@ static void tgen_extract(TCGContext *s, TCGType type, TCGReg a0, TCGReg a1, unsi tcg_out_ext32u(s, a0, a1); return; } - } else if (TCG_TARGET_REG_BITS == 64 && ofs + len == 32) { + } else if (ofs + len == 32) { /* This is a 32-bit zero-extending right shift. */ tcg_out_mov(s, TCG_TYPE_I32, a0, a1); tcg_out_shifti(s, SHIFT_SHR, a0, ofs); @@ -3093,7 +2824,7 @@ static void tgen_extract(TCGContext *s, TCGType type, TCGReg a0, TCGReg a1, unsi * Otherwise we emit the same ext16 + shift pattern that we * would have gotten from the normal tcg-op.c expansion. */ - if (a1 < 4 && (TCG_TARGET_REG_BITS == 32 || a0 < 8)) { + if (a1 < 4 && a0 < 8) { tcg_out_modrm(s, OPC_MOVZBL, a0, a1 + 4); } else { tcg_out_ext16u(s, a0, a1); @@ -3190,7 +2921,6 @@ static const TCGOutOpLoad outop_ld16s = { .out = tgen_ld16s, }; -#if TCG_TARGET_REG_BITS == 64 static void tgen_ld32u(TCGContext *s, TCGType type, TCGReg dest, TCGReg base, ptrdiff_t offset) { tcg_out_modrm_offset(s, OPC_MOVL_GvEv, dest, base, offset); } @@ -3208,7 +2938,6 @@ static const TCGOutOpLoad outop_ld32s = { .base.static_constraint = C_O1_I1(r, r), .out = tgen_ld32s, }; -#endif static void tgen_st8_r(TCGContext *s, TCGType type, TCGReg data, TCGReg base, ptrdiff_t offset) { tcg_out_modrm_offset(s, OPC_MOVB_EvGv | P_REXB_R, data, base, offset); @@ -3545,16 +3274,6 @@ static void tcg_out_vec_op(TCGContext *s, TCGOpcode opc, unsigned vecl, unsigned a1 = a2; a2 = args[3]; goto gen_simd; -#if TCG_TARGET_REG_BITS == 32 - case INDEX_op_dup2_vec: - /* First merge the two 32-bit inputs to a single 64-bit element. */ - tcg_out_vex_modrm(s, OPC_PUNPCKLDQ, a0, a1, a2); - /* Then replicate the 64-bit elements across the rest of the vector. */ - if (type != TCG_TYPE_V64) { - tcg_out_dup_vec(s, type, MO_64, a0, a0); - } - break; -#endif case INDEX_op_abs_vec: insn = abs_insn[vece]; a2 = a1; @@ -3746,9 +3465,6 @@ static TCGConstraintSetIndex tcg_target_op_def(TCGOpcode op, TCGType type, unsig case INDEX_op_x86_punpckh_vec: case INDEX_op_x86_vpshldi_vec: case INDEX_op_x86_vgf2p8affineqb_vec: -#if TCG_TARGET_REG_BITS == 32 - case INDEX_op_dup2_vec: -#endif return C_O1_I2(x, x, x); case INDEX_op_abs_vec: @@ -4233,25 +3949,18 @@ void tcg_expand_vec_op(TCGOpcode opc, TCGType type, unsigned vece, TCGArg a0, .. } static const int tcg_target_callee_save_regs[] = { -#if TCG_TARGET_REG_BITS == 64 TCG_REG_RBP, TCG_REG_RBX, #if defined(_WIN64) TCG_REG_RDI, TCG_REG_RSI, #endif TCG_REG_R12, TCG_REG_R13, TCG_REG_R14, /* Currently used for the global env. */ TCG_REG_R15, -#else - TCG_REG_EBP, /* Currently used for the global env. */ - TCG_REG_EBX, - TCG_REG_ESI, - TCG_REG_EDI, -#endif }; /* Compute frame size via macros, to share between tcg_target_qemu_prologue and tcg_register_jit. */ -#define PUSH_SIZE ((1 + ARRAY_SIZE(tcg_target_callee_save_regs)) * (TCG_TARGET_REG_BITS / 8)) +#define PUSH_SIZE ((1 + ARRAY_SIZE(tcg_target_callee_save_regs)) * sizeof(tcg_target_long)) #define FRAME_SIZE \ ((PUSH_SIZE + TCG_STATIC_CALL_ARGS_SIZE + CPU_TEMP_BUF_NLONGS * sizeof(long) + TCG_TARGET_STACK_ALIGN - 1) & \ @@ -4279,7 +3988,6 @@ static void tcg_target_qemu_prologue(TCGContext *s) { } else if (guest_base == (int32_t) guest_base) { x86_guest_base.ofs = guest_base; } else { - assert(TCG_TARGET_REG_BITS == 64); /* Choose R12 because, as a base, it requires a SIB byte. */ x86_guest_base.index = TCG_REG_R12; tcg_out_movi(s, TCG_TYPE_PTR, x86_guest_base.index, guest_base); @@ -4287,18 +3995,10 @@ static void tcg_target_qemu_prologue(TCGContext *s) { } } - if (TCG_TARGET_REG_BITS == 32) { - tcg_out_ld(s, TCG_TYPE_PTR, TCG_AREG0, TCG_REG_ESP, (ARRAY_SIZE(tcg_target_callee_save_regs) + 1) * 4); - tcg_out_addi(s, TCG_REG_ESP, -stack_addend); - /* jmp *tb. */ - tcg_out_modrm_offset(s, OPC_GRP5, EXT5_JMPN_Ev, TCG_REG_ESP, - (ARRAY_SIZE(tcg_target_callee_save_regs) + 2) * 4 + stack_addend); - } else { - tcg_out_mov(s, TCG_TYPE_PTR, TCG_AREG0, tcg_target_call_iarg_regs[0]); - tcg_out_addi(s, TCG_REG_ESP, -stack_addend); - /* jmp *tb. */ - tcg_out_modrm(s, OPC_GRP5, EXT5_JMPN_Ev, tcg_target_call_iarg_regs[1]); - } + tcg_out_mov(s, TCG_TYPE_PTR, TCG_AREG0, tcg_target_call_iarg_regs[0]); + tcg_out_addi(s, TCG_REG_ESP, -stack_addend); + /* jmp *tb. */ + tcg_out_modrm(s, OPC_GRP5, EXT5_JMPN_Ev, tcg_target_call_iarg_regs[1]); /* * Return path for goto_ptr. Set return value to 0, a-la exit_tb, @@ -4331,9 +4031,7 @@ static void tcg_out_nop_fill(tcg_insn_unit *p, int count) { static void tcg_target_init(TCGContext *s) { tcg_target_available_regs[TCG_TYPE_I32] = ALL_GENERAL_REGS; - if (TCG_TARGET_REG_BITS == 64) { - tcg_target_available_regs[TCG_TYPE_I64] = ALL_GENERAL_REGS; - } + tcg_target_available_regs[TCG_TYPE_I64] = ALL_GENERAL_REGS; if (have_avx1) { tcg_target_available_regs[TCG_TYPE_V64] = ALL_VECTOR_REGS; tcg_target_available_regs[TCG_TYPE_V128] = ALL_VECTOR_REGS; @@ -4346,16 +4044,14 @@ static void tcg_target_init(TCGContext *s) { tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_EAX); tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_EDX); tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_ECX); - if (TCG_TARGET_REG_BITS == 64) { #if !defined(_WIN64) - tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_RDI); - tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_RSI); + tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_RDI); + tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_RSI); #endif - tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_R8); - tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_R9); - tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_R10); - tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_R11); - } + tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_R8); + tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_R9); + tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_R10); + tcg_regset_set_reg(tcg_target_call_clobber_regs, TCG_REG_R11); s->reserved_regs = 0; tcg_regset_set_reg(s->reserved_regs, TCG_REG_CALL_STACK); @@ -4384,10 +4080,9 @@ typedef struct { /* We're expecting a 2 byte uleb128 encoded value. */ QEMU_BUILD_BUG_ON(FRAME_SIZE >= (1 << 14)); -#if !defined(__ELF__) -/* Host machine without ELF. */ -#elif TCG_TARGET_REG_BITS == 64 +#ifdef __ELF__ #define ELF_HOST_MACHINE EM_X86_64 + static const DebugFrame debug_frame = {.h.cie.len = sizeof(DebugFrameCIE) - 4, /* length after .len member */ .h.cie.id = -1, .h.cie.version = 1, @@ -4411,32 +4106,7 @@ static const DebugFrame debug_frame = {.h.cie.len = sizeof(DebugFrameCIE) - 4, / 0x8e, 6, /* DW_CFA_offset, %r14, -48 */ 0x8f, 7, /* DW_CFA_offset, %r15, -56 */ }}; -#else -#define ELF_HOST_MACHINE EM_386 -static const DebugFrame debug_frame = {.h.cie.len = sizeof(DebugFrameCIE) - 4, /* length after .len member */ - .h.cie.id = -1, - .h.cie.version = 1, - .h.cie.code_align = 1, - .h.cie.data_align = 0x7c, /* sleb128 -4 */ - .h.cie.return_column = 8, - - /* Total FDE size does not include the "len" member. */ - .h.fde.len = sizeof(DebugFrame) - offsetof(DebugFrame, h.fde.cie_offset), - - .fde_def_cfa = {12, 4, /* DW_CFA_def_cfa %esp, ... */ - (FRAME_SIZE & 0x7f) | 0x80, /* ... uleb128 FRAME_SIZE */ - (FRAME_SIZE >> 7)}, - .fde_reg_ofs = { - 0x88, 1, /* DW_CFA_offset, %eip, -4 */ - /* The following ordering must match tcg_target_callee_save_regs. */ - 0x85, 2, /* DW_CFA_offset, %ebp, -8 */ - 0x83, 3, /* DW_CFA_offset, %ebx, -12 */ - 0x86, 4, /* DW_CFA_offset, %esi, -16 */ - 0x87, 5, /* DW_CFA_offset, %edi, -20 */ - }}; -#endif -#if defined(ELF_HOST_MACHINE) void tcg_register_jit(const void *buf, size_t buf_size) { tcg_register_jit_int(buf, buf_size, &debug_frame, sizeof(debug_frame)); } From cb8652c1fb2a1a12de343d0ff3fe6b7275c43264 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Tue, 18 Aug 2026 15:13:23 +0000 Subject: [PATCH 04/52] libcpu: adjusted for the qemu 11.1 tcg api qemu 11.1 removed TARGET_INSN_START_EXTRA_WORDS and gave tcg_gen_insn_start a single fixed form taking INSN_START_WORDS arguments, with callers padding out the unused slots. i386 only uses one extra word, so pass a trailing zero. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- libcpu/CMakeLists.txt | 2 -- libcpu/src/target-i386/translate.c | 5 +++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/libcpu/CMakeLists.txt b/libcpu/CMakeLists.txt index aef9f2e44..83d49ed36 100644 --- a/libcpu/CMakeLists.txt +++ b/libcpu/CMakeLists.txt @@ -76,12 +76,10 @@ message(STATUS "WITH_TARGET: ${WITH_TARGET}") if(WITH_TARGET MATCHES "i386") file(APPEND ${CONFIG_TARGET_H} "#define TARGET_ARCH \"i386\"\n") file(APPEND ${CONFIG_TARGET_H} "#define TARGET_LONG_ALIGNMENT 4\n") - file(APPEND ${CONFIG_TARGET_H} "#define TARGET_INSN_START_EXTRA_WORDS 1\n") elseif(WITH_TARGET MATCHES "x86_64") file(APPEND ${CONFIG_TARGET_H} "#define TARGET_ARCH \"x86_64\"\n") file(APPEND ${CONFIG_TARGET_H} "#define TARGET_X86_64 1\n") file(APPEND ${CONFIG_TARGET_H} "#define TARGET_LONG_ALIGNMENT 8\n") - file(APPEND ${CONFIG_TARGET_H} "#define TARGET_INSN_START_EXTRA_WORDS 1\n") else() message(FATAL_ERROR "Incorrect target ${WITH_TARGET}") endif() diff --git a/libcpu/src/target-i386/translate.c b/libcpu/src/target-i386/translate.c index 91fc70226..74b47d437 100644 --- a/libcpu/src/target-i386/translate.c +++ b/libcpu/src/target-i386/translate.c @@ -4062,8 +4062,9 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start) { target_ulong next_eip, tval; int rex_w, rex_r; - // This is required for precise pc generation - tcg_gen_insn_start(pc_start, s->cc_op); + // This is required for precise pc generation. The trailing zero pads out + // the fixed INSN_START_WORDS-wide slot; i386 only uses one extra word. + tcg_gen_insn_start(pc_start, s->cc_op, 0); #ifdef ENABLE_PRECISE_EXCEPTION_DEBUGGING tcg_gen_movi_tl(cpu_tmp0, pc_start - s->cs_base); From 7294e3ebf753879529717cf2605d69271eaacb07 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Tue, 18 Aug 2026 15:43:06 +0000 Subject: [PATCH 05/52] libtcg: upgraded softfloat to qemu 11.1 softfloat had been left at qemu v8.1.0 by the previous upgrades. The S2E delta on it turned out to be tiny, so the three-way merge from v8.1.0 was nearly clean: softfloat-parts.c.inc and softfloat-specialize.c.inc are now byte for byte upstream, and the rest differs only in include paths and the C++ linkage guards. Two structural changes were needed to fit it into libtcg: softfloat-types.h now needs FIELD() for the 3-NaN propagation rules, which lives in registerfields.h, which includes bitops.h. That creates a cycle, because bswap.h used to define the float and integer reinterpretation unions and therefore included softfloat-types.h. Upstream keeps those unions in include/qemu/cpu-float.h instead, so split them out the same way and drop the bswap.h dependency from host-utils.h, as qemu 11.1 did. float_status.float_rounding_mode is kept as a plain field rather than the bitfield upstream uses. S2E addresses the CPU state by (offset, size) so that helpers running as bitcode inside KLEE can read it back through g_sqi.regs.read_concrete(), and the RR_cpu()/WR_cpu() accessors in ops_sse.h need offsetof() and sizeof() on this field. Neither works on a bitfield, and dropping the accessors would silently read the native copy of the CPU state instead of KLEE's. FloatRoundMode is packed, so this costs one byte. Note that this changes guest visible floating point behaviour: v8.1.0 predates the canonicalization of input denormals, the explicit default NaN pattern, and the configurable flush to zero detection point. softfloat.c is compiled to softfloat.bc and interpreted by KLEE, so symbolic paths see the new semantics too. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- libtcg/include/fpu/softfloat-helpers.h | 74 +- libtcg/include/fpu/softfloat-parts.h | 213 ++ libtcg/include/fpu/softfloat-types.h | 295 ++- libtcg/include/fpu/softfloat.h | 224 +- libtcg/include/tcg/utils/bitops.h | 1 + libtcg/include/tcg/utils/bswap.h | 73 - libtcg/include/tcg/utils/cpu-float.h | 95 + libtcg/include/tcg/utils/host-utils.h | 7 +- libtcg/include/tcg/utils/osdep.h | 10 + libtcg/include/tcg/utils/registerfields.h | 215 ++ libtcg/scripts/upgrade/README.md | 14 +- libtcg/scripts/upgrade/mapping.tsv | 8 +- libtcg/src/fpu/softfloat-parts-addsub.c.inc | 22 +- libtcg/src/fpu/softfloat-parts.c.inc | 1117 +++++----- libtcg/src/fpu/softfloat-specialize.c.inc | 714 ++---- libtcg/src/fpu/softfloat.c | 2146 ++++++++++--------- 16 files changed, 2835 insertions(+), 2393 deletions(-) create mode 100644 libtcg/include/fpu/softfloat-parts.h create mode 100644 libtcg/include/tcg/utils/cpu-float.h create mode 100644 libtcg/include/tcg/utils/registerfields.h diff --git a/libtcg/include/fpu/softfloat-helpers.h b/libtcg/include/fpu/softfloat-helpers.h index 380056204..01e71be74 100644 --- a/libtcg/include/fpu/softfloat-helpers.h +++ b/libtcg/include/fpu/softfloat-helpers.h @@ -65,7 +65,7 @@ static inline void set_float_rounding_mode(FloatRoundMode val, float_status *sta status->float_rounding_mode = val; } -static inline void set_float_exception_flags(int val, float_status *status) { +static inline void set_float_exception_flags(FloatExceptionFlags val, float_status *status) { status->float_exception_flags = val; } @@ -73,6 +73,26 @@ static inline void set_floatx80_rounding_precision(FloatX80RoundPrec val, float_ status->floatx80_rounding_precision = val; } +static inline void set_floatx80_behaviour(FloatX80Behaviour b, float_status *status) { + status->floatx80_behaviour = b; +} + +static inline void set_float_2nan_prop_rule(Float2NaNPropRule rule, float_status *status) { + status->float_2nan_prop_rule = rule; +} + +static inline void set_float_3nan_prop_rule(Float3NaNPropRule rule, float_status *status) { + status->float_3nan_prop_rule = rule; +} + +static inline void set_float_infzeronan_rule(FloatInfZeroNaNRule rule, float_status *status) { + status->float_infzeronan_rule = rule; +} + +static inline void set_float_default_nan_pattern(uint8_t dnan_pattern, float_status *status) { + status->default_nan_pattern = dnan_pattern; +} + static inline void set_flush_to_zero(bool val, float_status *status) { status->flush_to_zero = val; } @@ -81,50 +101,74 @@ static inline void set_flush_inputs_to_zero(bool val, float_status *status) { status->flush_inputs_to_zero = val; } +static inline void set_float_ftz_detection(bool val, float_status *status) { + status->ftz_before_rounding = val; +} + static inline void set_default_nan_mode(bool val, float_status *status) { status->default_nan_mode = val; } -static inline void set_snan_bit_is_one(bool val, float_status *status) { - status->snan_bit_is_one = val; +static inline void set_snan_rule(FloatSNaNRule val, float_status *status) { + status->float_snan_rule = val; } -static inline void set_use_first_nan(bool val, float_status *status) { - status->use_first_nan = val; +static inline void set_float_e4m3_nan_is_snan(bool val, float_status *status) { + status->e4m3_nan_is_snan = val; } -static inline void set_no_signaling_nans(bool val, float_status *status) { - status->no_signaling_nans = val; +static inline void set_float_rebias_overflow(bool val, float_status *status) { + status->rebias_overflow = val; } -static inline bool get_float_detect_tininess(float_status *status) { - return status->tininess_before_rounding; +static inline void set_float_rebias_underflow(bool val, float_status *status) { + status->rebias_underflow = val; } -static inline FloatRoundMode get_float_rounding_mode(float_status *status) { +static inline FloatRoundMode get_float_rounding_mode(const float_status *status) { return status->float_rounding_mode; } -static inline int get_float_exception_flags(float_status *status) { +static inline FloatExceptionFlags get_float_exception_flags(const float_status *status) { return status->float_exception_flags; } -static inline FloatX80RoundPrec get_floatx80_rounding_precision(float_status *status) { +static inline FloatX80RoundPrec get_floatx80_rounding_precision(const float_status *status) { return status->floatx80_rounding_precision; } -static inline bool get_flush_to_zero(float_status *status) { +static inline FloatX80Behaviour get_floatx80_behaviour(const float_status *status) { + return status->floatx80_behaviour; +} + +static inline Float2NaNPropRule get_float_2nan_prop_rule(const float_status *status) { + return status->float_2nan_prop_rule; +} + +static inline Float3NaNPropRule get_float_3nan_prop_rule(const float_status *status) { + return status->float_3nan_prop_rule; +} + +static inline FloatInfZeroNaNRule get_float_infzeronan_rule(const float_status *status) { + return status->float_infzeronan_rule; +} + +static inline bool get_flush_to_zero(const float_status *status) { return status->flush_to_zero; } -static inline bool get_flush_inputs_to_zero(float_status *status) { +static inline bool get_flush_inputs_to_zero(const float_status *status) { return status->flush_inputs_to_zero; } -static inline bool get_default_nan_mode(float_status *status) { +static inline bool get_default_nan_mode(const float_status *status) { return status->default_nan_mode; } +static inline FloatSNaNRule get_snan_rule(float_status *status) { + return status->float_snan_rule; +} + #ifdef __cplusplus } #endif diff --git a/libtcg/include/fpu/softfloat-parts.h b/libtcg/include/fpu/softfloat-parts.h new file mode 100644 index 000000000..524b2ed3d --- /dev/null +++ b/libtcg/include/fpu/softfloat-parts.h @@ -0,0 +1,213 @@ +/* + * Floating point intermediate representation + * + * The code in this source file is derived from release 2a of the SoftFloat + * IEC/IEEE Floating-point Arithmetic Package. Those parts of the code (and + * some later contributions) are provided under that license, as detailed below. + * It has subsequently been modified by contributors to the QEMU Project, + * so some portions are provided under: + * the SoftFloat-2a license + * the BSD license + * GPL-v2-or-later + * + * Any future contributions to this file after December 1st 2014 will be + * taken to be licensed under the Softfloat-2a license unless specifically + * indicated otherwise. + */ + +#ifndef SOFTFLOAT_PARTS_H +#define SOFTFLOAT_PARTS_H + +#include +#include + +#include + +/* Format-specific handling of exp == exp_max */ +typedef enum __attribute__((__packed__)) { + /* exp==max, frac==0 ? infinity : nan; this is ieee standard. */ + float_expmax_ieee, + /* exp==max is a normal number; no infinity or nan representation. */ + float_expmax_normal, + /* exp==max, frac==max ? nan : normal; no infinity representation. */ + float_expmax_e4m3, +} FloatFmtExpMaxKind; + +/* + * Structure holding all of the relevant parameters for a format. + * exp_size: the size of the exponent field + * exp_bias: the offset applied to the exponent field + * exp_max: the maximum normalised exponent + * frac_size: the size of the fraction field + * frac_shift: shift to normalise the fraction with DECOMPOSED_BINARY_POINT + * The following are computed based the size of fraction + * round_mask: bits below lsb which must be rounded + * The following optional modifiers are available: + * exp_max_kind: affects how exp == exp_max is interpreted + * has_explicit_bit: has an explicit integer bit; this affects whether + * the float_status floatx80_behaviour handling applies + * overflow_raises_invalid: for float_expmax_normal, raise invalid + * instead of overflow. + */ +typedef struct { + int exp_size; + int exp_bias; + int exp_re_bias; + int exp_max; + int frac_size; + int frac_shift; + FloatFmtExpMaxKind exp_max_kind; + bool has_explicit_bit; + bool overflow_raises_invalid; + uint64_t round_mask; +} FloatFmt; + +extern const FloatFmt float4_e2m1_params; +extern const FloatFmt float8_e4m3_params; +extern const FloatFmt float8_e5m2_params; +extern const FloatFmt float16_params; +extern const FloatFmt bfloat16_params; +extern const FloatFmt float32_params; +extern const FloatFmt float64_params; +extern const FloatFmt float128_params; + +/* + * Classify a floating point number. Everything above float_class_qnan + * is a NaN so cls >= float_class_qnan is any NaN. + * + * Note that we canonicalize denormals, so most code should treat + * class_normal and class_denormal identically. + */ + +typedef enum __attribute__((__packed__)) { + float_class_unclassified, + float_class_zero, + float_class_normal, + float_class_denormal, /* input was a non-squashed denormal */ + float_class_inf, + float_class_qnan, /* all NaNs from here */ + float_class_snan, +} FloatClass; + +#define float_cmask(bit) (1u << (bit)) + +enum { + float_cmask_zero = float_cmask(float_class_zero), + float_cmask_normal = float_cmask(float_class_normal), + float_cmask_denormal = float_cmask(float_class_denormal), + float_cmask_inf = float_cmask(float_class_inf), + float_cmask_qnan = float_cmask(float_class_qnan), + float_cmask_snan = float_cmask(float_class_snan), + + float_cmask_infzero = float_cmask_zero | float_cmask_inf, + float_cmask_anynan = float_cmask_qnan | float_cmask_snan, + float_cmask_anynorm = float_cmask_normal | float_cmask_denormal, +}; + +/* + * Structure holding all of the decomposed parts of a float. + * The exponent is unbiased and the fraction is normalized. + * + * The fraction words are stored in big-endian word ordering, + * so that truncation from a larger format to a smaller format + * can be done simply by ignoring subsequent elements. + */ + +typedef struct { + FloatClass cls; + bool sign; + int32_t exp; + union { + /* Routines that know the structure may reference the singular name. */ + uint64_t frac; + /* + * Routines expanded with multiple structures reference "hi" and "lo" + * depending on the operation. In FloatParts64, "hi" and "lo" are + * both the same word and aliased here. + */ + uint64_t frac_hi; + uint64_t frac_lo; + }; +} FloatParts64; + +typedef struct { + FloatClass cls; + bool sign; + int32_t exp; + uint64_t frac_hi; + uint64_t frac_lo; +} FloatParts128; + +/* + * Unpack routines from a specific floating-point format. + */ + +FloatParts64 float4_e2m1_unpack_canonical(float4_e2m1 f, float_status *s); +FloatParts64 float8_e4m3_unpack_canonical(float8_e4m3 f, float_status *s); +FloatParts64 float8_e5m2_unpack_canonical(float8_e5m2 f, float_status *s); +FloatParts64 float16_unpack_canonical(float16 f, float_status *s); +FloatParts64 bfloat16_unpack_canonical(bfloat16 f, float_status *s); +FloatParts64 float32_unpack_canonical(float32 f, float_status *s); +FloatParts64 float64_unpack_canonical(float64 f, float_status *s); +FloatParts128 float128_unpack_canonical(float128 f, float_status *s); +/* Returns false if the encoding is invalid. */ +bool floatx80_unpack_canonical(FloatParts128 *p, floatx80 f, float_status *s); + +/* + * Pack routines to a specific floating-point format. + */ + +float8_e4m3 float8_e4m3_round_pack_canonical(FloatParts64 *p, float_status *s, bool saturate); +float8_e5m2 float8_e5m2_round_pack_canonical(FloatParts64 *p, float_status *s, bool saturate); +float16 float16_round_pack_canonical(FloatParts64 *p, float_status *s); +bfloat16 bfloat16_round_pack_canonical(FloatParts64 *p, float_status *s); +float32 float32_round_pack_canonical(FloatParts64 *p, float_status *s); +float64 float64_round_pack_canonical(FloatParts64 *p, float_status *s); +float128 float128_round_pack_canonical(FloatParts128 *p, float_status *s); +floatx80 floatx80_round_pack_canonical(FloatParts128 *p, float_status *s); + +/* + * NaN handling + */ + +FloatParts64 parts64_default_nan(float_status *status); +FloatParts128 parts128_default_nan(float_status *status); + +FloatParts64 parts64_pick_nan(const FloatParts64 *, const FloatParts64 *, float_status *); +FloatParts128 parts128_pick_nan(const FloatParts128 *, const FloatParts128 *, float_status *); + +FloatParts64 parts64_return_nan(const FloatParts64 *a, float_status *s); +FloatParts128 parts128_return_nan(const FloatParts128 *a, float_status *s); + +/* + * Operations + */ + +FloatParts64 parts64_addsub(const FloatParts64 *a, const FloatParts64 *b, float_status *s, bool subtract); +FloatParts128 parts128_addsub(const FloatParts128 *a, const FloatParts128 *b, float_status *s, bool subtract); + +FloatRelation parts64_compare(const FloatParts64 *a, const FloatParts64 *b, float_status *s, bool quiet); +FloatRelation parts128_compare(const FloatParts128 *a, const FloatParts128 *b, float_status *s, bool quiet); + +FloatParts64 parts64_div(const FloatParts64 *a, const FloatParts64 *b, float_status *s); +FloatParts128 parts128_div(const FloatParts128 *a, const FloatParts128 *b, float_status *s); + +FloatParts64 parts64_mul(const FloatParts64 *a, const FloatParts64 *b, float_status *s); +FloatParts128 parts128_mul(const FloatParts128 *a, const FloatParts128 *b, float_status *s); + +FloatParts64 parts64_muladd(const FloatParts64 *a, const FloatParts64 *b, const FloatParts64 *c, int flags, + float_status *s); +FloatParts128 parts128_muladd(const FloatParts128 *a, const FloatParts128 *b, const FloatParts128 *c, int flags, + float_status *s); + +FloatParts64 parts64_round_to_int(const FloatParts64 *a, FloatRoundMode rmode, int scale, float_status *s, + const FloatFmt *fmt); +FloatParts128 parts128_round_to_int(const FloatParts128 *a, FloatRoundMode rmode, int scale, float_status *s, + const FloatFmt *fmt); + +FloatParts64 parts64_round_to_fmt(const FloatParts64 *p, float_status *s, const FloatFmt *fmt); + +FloatParts64 parts64_scalbn(const FloatParts64 *a, int n, float_status *s); +FloatParts128 parts128_scalbn(const FloatParts128 *a, int n, float_status *s); + +#endif diff --git a/libtcg/include/fpu/softfloat-types.h b/libtcg/include/fpu/softfloat-types.h index f8610762c..da1bd9eee 100644 --- a/libtcg/include/fpu/softfloat-types.h +++ b/libtcg/include/fpu/softfloat-types.h @@ -83,6 +83,8 @@ this code that are retained. #include #include +#include + #ifdef __cplusplus extern "C" { #endif @@ -124,6 +126,13 @@ typedef struct { */ typedef uint16_t bfloat16; +/* + * Open Compute Project (OCP) Microscaling Formats + */ +typedef uint8_t float4_e2m1; +typedef uint8_t float8_e4m3; +typedef uint8_t float8_e5m2; + /* * Software IEC/IEEE floating-point underflow tininess-detection mode. */ @@ -145,6 +154,8 @@ typedef enum __attribute__((__packed__)) { float_round_to_odd = 5, /* Not an IEEE rounding mode: round to closest odd, overflow to inf */ float_round_to_odd_inf = 6, + /* Not an IEEE rounding mode: round to nearest even, overflow to max */ + float_round_nearest_even_max = 7, } FloatRoundMode; /* @@ -157,8 +168,10 @@ enum { float_flag_overflow = 0x0004, float_flag_underflow = 0x0008, float_flag_inexact = 0x0010, - float_flag_input_denormal = 0x0020, - float_flag_output_denormal = 0x0040, + /* We flushed an input denormal to 0 (because of flush_inputs_to_zero) */ + float_flag_input_denormal_flushed = 0x0020, + /* We flushed an output denormal to 0 (because of flush_to_zero) */ + float_flag_output_denormal_flushed = 0x0040, float_flag_invalid_isi = 0x0080, /* inf - inf */ float_flag_invalid_imz = 0x0100, /* inf * 0 */ float_flag_invalid_idi = 0x0200, /* inf / inf */ @@ -166,8 +179,17 @@ enum { float_flag_invalid_sqrt = 0x0800, /* sqrt(-x) */ float_flag_invalid_cvti = 0x1000, /* non-nan to integer */ float_flag_invalid_snan = 0x2000, /* any operand was snan */ + /* + * An input was denormal and we used it (without flushing it to zero). + * Not set if we do not actually use the denormal input (e.g. + * because some other input was a NaN, or because the operation + * wasn't actually carried out (divide-by-zero; invalid)) + */ + float_flag_input_denormal_used = 0x4000, }; +typedef uint16_t FloatExceptionFlags; + /* * Rounding precision for floatx80. */ @@ -177,6 +199,207 @@ typedef enum __attribute__((__packed__)) { floatx80_precision_s, } FloatX80RoundPrec; +/* + * Define how the architecture discriminates signaling NaNs. + * This done with the most significant bit of the fraction. + * + * In IEEE 754-1985 this was implementation defined, but in IEEE 754-2008 + * the msb must be 0. But setting the msb to 1 got baked into HPPA, SH4, + * and pre-2008 MIPS. + * + * Further, some architectures (or modes of architectures) do not detect + * signaling NaNs at all. + */ +typedef enum __attribute__((__packed__)) { + float_snan_bit_is_zero, + float_snan_bit_is_one, + float_snan_never, +} FloatSNaNRule; + +/* + * 2-input NaN propagation rule. Individual architectures have + * different rules for which input NaN is propagated to the output + * when there is more than one NaN on the input. + * + * If default_nan_mode is enabled then it is valid not to set a + * NaN propagation rule, because the softfloat code guarantees + * not to try to pick a NaN to propagate in default NaN mode. + * When not in default-NaN mode, it is an error for the target + * not to set the rule in float_status, and we will assert if + * we need to handle an input NaN and no rule was selected. + */ +typedef enum __attribute__((__packed__)) { + /* No propagation rule specified */ + float_2nan_prop_none = 0, + /* Prefer SNaN over QNaN, then operand A over B */ + float_2nan_prop_s_ab, + /* Prefer SNaN over QNaN, then operand B over A */ + float_2nan_prop_s_ba, + /* Prefer A over B regardless of SNaN vs QNaN */ + float_2nan_prop_ab, + /* Prefer B over A regardless of SNaN vs QNaN */ + float_2nan_prop_ba, + /* + * This implements x87 NaN propagation rules: + * SNaN + QNaN => return the QNaN + * two SNaNs => return the one with the larger significand, silenced + * two QNaNs => return the one with the larger significand + * SNaN and a non-NaN => return the SNaN, silenced + * QNaN and a non-NaN => return the QNaN + * + * If we get down to comparing significands and they are the same, + * return the NaN with the positive sign bit (if any). + */ + float_2nan_prop_x87, +} Float2NaNPropRule; + +/* + * 3-input NaN propagation rule, for fused multiply-add. Individual + * architectures have different rules for which input NaN is + * propagated to the output when there is more than one NaN on the + * input. + * + * If default_nan_mode is enabled then it is valid not to set a NaN + * propagation rule, because the softfloat code guarantees not to try + * to pick a NaN to propagate in default NaN mode. When not in + * default-NaN mode, it is an error for the target not to set the rule + * in float_status if it uses a muladd, and we will assert if we need + * to handle an input NaN and no rule was selected. + * + * The naming scheme for Float3NaNPropRule values is: + * float_3nan_prop_s_abc: + * = "Prefer SNaN over QNaN, then operand A over B over C" + * float_3nan_prop_abc: + * = "Prefer A over B over C regardless of SNaN vs QNAN" + * + * For QEMU, the multiply-add operation is A * B + C. + */ + +/* + * We set the Float3NaNPropRule enum values up so we can select the + * right value in pickNaNMulAdd in a data driven way. + */ +FIELD(3NAN, 1ST, 0, 2) /* which operand is most preferred ? */ +FIELD(3NAN, 2ND, 2, 2) /* which operand is next most preferred ? */ +FIELD(3NAN, 3RD, 4, 2) /* which operand is least preferred ? */ +FIELD(3NAN, SNAN, 6, 1) /* do we prefer SNaN over QNaN ? */ + +#define PROPRULE(X, Y, Z) ((X << R_3NAN_1ST_SHIFT) | (Y << R_3NAN_2ND_SHIFT) | (Z << R_3NAN_3RD_SHIFT)) + +typedef enum __attribute__((__packed__)) { + float_3nan_prop_none = 0, /* No propagation rule specified */ + float_3nan_prop_abc = PROPRULE(0, 1, 2), + float_3nan_prop_acb = PROPRULE(0, 2, 1), + float_3nan_prop_bac = PROPRULE(1, 0, 2), + float_3nan_prop_bca = PROPRULE(1, 2, 0), + float_3nan_prop_cab = PROPRULE(2, 0, 1), + float_3nan_prop_cba = PROPRULE(2, 1, 0), + float_3nan_prop_s_abc = float_3nan_prop_abc | R_3NAN_SNAN_MASK, + float_3nan_prop_s_acb = float_3nan_prop_acb | R_3NAN_SNAN_MASK, + float_3nan_prop_s_bac = float_3nan_prop_bac | R_3NAN_SNAN_MASK, + float_3nan_prop_s_bca = float_3nan_prop_bca | R_3NAN_SNAN_MASK, + float_3nan_prop_s_cab = float_3nan_prop_cab | R_3NAN_SNAN_MASK, + float_3nan_prop_s_cba = float_3nan_prop_cba | R_3NAN_SNAN_MASK, +} Float3NaNPropRule; + +#undef PROPRULE + +/* + * Rule for result of fused multiply-add 0 * Inf + NaN. + * This must be a NaN, but implementations differ on whether this + * is the input NaN or the default NaN. + * + * You don't need to set this if default_nan_mode is enabled. + * When not in default-NaN mode, it is an error for the target + * not to set the rule in float_status if it uses muladd, and we + * will assert if we need to handle an input NaN and no rule was + * selected. + */ +typedef enum __attribute__((__packed__)) { + /* No propagation rule specified */ + float_infzeronan_none = 0, + /* Result is never the default NaN (so always the input NaN) */ + float_infzeronan_dnan_never = 1, + /* Result is always the default NaN */ + float_infzeronan_dnan_always = 2, + /* Result is the default NaN if the input NaN is quiet */ + float_infzeronan_dnan_if_qnan = 3, + /* + * Don't raise Invalid for 0 * Inf + NaN. Default is to raise. + * IEEE 754-2008 section 7.2 makes it implementation defined whether + * 0 * Inf + QNaN raises Invalid or not. Note that 0 * Inf + SNaN will + * raise the Invalid flag for the SNaN anyway. + * + * This is a flag which can be ORed in with any of the above + * DNaN behaviour options. + */ + float_infzeronan_suppress_invalid = (1 << 2), +} FloatInfZeroNaNRule; + +/* + * When flush_to_zero is set, should we detect denormal results to + * be flushed before or after rounding? For most architectures this + * should be set to match the tininess_before_rounding setting, + * but a few architectures, e.g. MIPS MSA, detect FTZ before + * rounding but tininess after rounding. + * + * This enum is arranged so that the default if the target doesn't + * configure it matches the default for tininess_before_rounding + * (i.e. "after rounding"). + */ +#define float_ftz_after_rounding false +#define float_ftz_before_rounding true + +/* + * floatx80 is primarily used by x86 and m68k, and there are + * differences in the handling, largely related to the explicit + * Integer bit which floatx80 has and the other float formats do not. + * These flag values allow specification of the target's requirements + * and can be ORed together to set floatx80_behaviour. + */ +typedef enum __attribute__((__packed__)) { + /* In the default Infinity value, is the Integer bit 0 ? */ + floatx80_default_inf_int_bit_is_zero = 1, + /* + * Are Pseudo-infinities (Inf with the Integer bit zero) valid? + * If so, floatx80_is_infinity() will return true for them. + * If not, floatx80_invalid_encoding will return false for them, + * and using them as inputs to a float op will raise Invalid. + */ + floatx80_pseudo_inf_valid = 2, + /* + * Are Pseudo-NaNs (NaNs where the Integer bit is zero) valid? + * If not, floatx80_invalid_encoding() will return false for them, + * and using them as inputs to a float op will raise Invalid. + */ + floatx80_pseudo_nan_valid = 4, + /* + * Are Unnormals (0 < exp < 0x7fff, Integer bit zero) valid? + * If not, floatx80_invalid_encoding() will return false for them, + * and using them as inputs to a float op will raise Invalid. + */ + floatx80_unnormal_valid = 8, + + /* + * If the exponent is 0 and the Integer bit is set, Intel call + * this a "pseudo-denormal"; x86 supports that only on input + * (treating them as denormals by ignoring the Integer bit). + * For m68k, the integer bit is considered validly part of the + * input value when the exponent is 0, and may be 0 or 1, + * giving extra range. They may also be generated as outputs. + * (The m68k manual actually calls these values part of the + * normalized number range, not the denormalized number range.) + * + * By default you get the Intel behaviour where the Integer + * bit is ignored; if this is set then the Integer bit value + * is honoured, m68k-style. + * + * Either way, floatx80_invalid_encoding() will always accept + * pseudo-denormals. + */ + floatx80_pseudo_denormal_valid = 16, +} FloatX80Behaviour; + /* * Floating Point Status. Individual architectures may maintain * several versions of float_status for different functions. The @@ -185,27 +408,61 @@ typedef enum __attribute__((__packed__)) { */ typedef struct float_status { - uint16_t float_exception_flags; - FloatRoundMode float_rounding_mode; - FloatX80RoundPrec floatx80_rounding_precision; - bool tininess_before_rounding; - /* should denormalised results go to zero and set the inexact flag? */ - bool flush_to_zero; - /* should denormalised inputs go to zero and set the input_denormal flag? */ - bool flush_inputs_to_zero; - bool default_nan_mode; + FloatExceptionFlags float_exception_flags : 16; + + /* + * Floating point status controls. + * Items that, in general, may be updated by writes to an architectural + * floating point control register. + */ /* - * The flags below are not used on all specializations and may - * constant fold away (see snan_bit_is_one()/no_signalling_nans() in - * softfloat-specialize.inc.c) + * Not a bitfield, unlike upstream: S2E addresses the CPU state by + * (offset, size) so that helpers running as bitcode inside KLEE can read + * it back through g_sqi.regs.read_concrete(). RR_cpu()/WR_cpu() therefore + * need offsetof() and sizeof() on this field, neither of which a bitfield + * supports. FloatRoundMode is packed, so this costs one byte. */ - bool snan_bit_is_one; - bool use_first_nan; - bool no_signaling_nans; + FloatRoundMode float_rounding_mode; + FloatX80RoundPrec floatx80_rounding_precision : 2; + /* should denormalised results go to zero and set output_denormal_flushed? */ + bool flush_to_zero : 1; + /* should denormalised inputs go to zero and set input_denormal_flushed? */ + bool flush_inputs_to_zero : 1; + /* should default nans be produced instead of propagating an input nan? */ + bool default_nan_mode : 1; /* should overflowed results subtract re_bias to its exponent? */ - bool rebias_overflow; + bool rebias_overflow : 1; /* should underflowed results add re_bias to its exponent? */ - bool rebias_underflow; + bool rebias_underflow : 1; + + /* + * Floating point behaviour controls. + * Items that, in general, will be set at cpu realization because + * the behaviour is baked into the specific hardware implementation. + */ + bool tininess_before_rounding : 1; + /* do we detect and flush denormal results before or after rounding? */ + bool ftz_before_rounding : 1; + FloatSNaNRule float_snan_rule : 2; + /* + * Overriding float_snan_rule, is the single NaN representation for + * the OCP E4M3 format an SNaN or QNaN? + */ + bool e4m3_nan_is_snan : 1; + Float2NaNPropRule float_2nan_prop_rule : 3; + Float3NaNPropRule float_3nan_prop_rule : 7; + FloatInfZeroNaNRule float_infzeronan_rule : 3; + FloatX80Behaviour floatx80_behaviour : 5; + /* + * The pattern to use for the default NaN. Here the high bit specifies + * the default NaN's sign bit, and bits 6..0 specify the high bits of the + * fractional part. The low bits of the fractional part are copies of bit 0. + * The exponent of the default NaN is (as for any NaN) always all 1s. + * Note that a value of 0 here is not a valid NaN. The target must set + * this to the correct non-zero value, or we will assert when trying to + * create a default NaN. + */ + unsigned default_nan_pattern : 8; } float_status; #ifdef __cplusplus diff --git a/libtcg/include/fpu/softfloat.h b/libtcg/include/fpu/softfloat.h index cf8b92868..dfebf31fc 100644 --- a/libtcg/include/fpu/softfloat.h +++ b/libtcg/include/fpu/softfloat.h @@ -105,7 +105,7 @@ typedef enum { | Routine to raise any or all of the software IEC/IEEE floating-point | exception flags. *----------------------------------------------------------------------------*/ -static inline void float_raise(uint16_t flags, float_status *status) { +static inline void float_raise(FloatExceptionFlags flags, float_status *status) { status->float_exception_flags |= flags; } @@ -123,14 +123,35 @@ bfloat16 bfloat16_squash_input_denormal(bfloat16 a, float_status *status); | Using these differs from negating an input or output before calling | the muladd function in that this means that a NaN doesn't have its | sign bit inverted before it is propagated. -| We also support halving the result before rounding, as a special -| case to support the ARM fused-sqrt-step instruction FRSQRTS. +| +| With float_muladd_suppress_add_product_zero, if A or B is zero +| such that the product is a true zero, then return C without addition. +| This preserves the sign of C when C is +/- 0. Used for Hexagon. *----------------------------------------------------------------------------*/ enum { float_muladd_negate_c = 1, float_muladd_negate_product = 2, float_muladd_negate_result = 4, - float_muladd_halve_result = 8, + float_muladd_suppress_add_product_zero = 8, +}; + +/*---------------------------------------------------------------------------- +| Options to indicate which negations to perform in float*_minmax() +*----------------------------------------------------------------------------*/ + +/* Flags for parts_minmax. */ +enum { + /* Set for minimum; clear for maximum. */ + float_minmax_ismin = 1, + /* Set for the IEEE 754-2008 minNum() and maxNum() operations. */ + float_minmax_isnum = 2, + /* Set for the IEEE 754-2008 minNumMag() and minNumMag() operations. */ + float_minmax_ismag = 4, + /* + * Set for the IEEE 754-2019 minimumNumber() and maximumNumber() + * operations. + */ + float_minmax_isnumber = 8, }; /*---------------------------------------------------------------------------- @@ -190,6 +211,20 @@ float128 int128_to_float128(Int128, float_status *status); float128 uint64_to_float128(uint64_t, float_status *status); float128 uint128_to_float128(Int128, float_status *status); +/*---------------------------------------------------------------------------- +| OCP FP{4,8} conversion routines. +*----------------------------------------------------------------------------*/ + +float8_e4m3 float4_e2m1_to_float8_e4m3(float4_e2m1, float_status *status); + +bfloat16 float8_e4m3_to_bfloat16(float8_e4m3, float_status *status); +float8_e4m3 bfloat16_to_float8_e4m3(bfloat16, bool sat, float_status *status); +float8_e4m3 float32_to_float8_e4m3(float32, bool sat, float_status *status); + +bfloat16 float8_e5m2_to_bfloat16(float8_e5m2, float_status *status); +float8_e5m2 bfloat16_to_float8_e5m2(bfloat16, bool sat, float_status *status); +float8_e5m2 float32_to_float8_e5m2(float32, bool sat, float_status *status); + /*---------------------------------------------------------------------------- | Software half-precision conversion routines. *----------------------------------------------------------------------------*/ @@ -236,16 +271,10 @@ float16 float16_add(float16, float16, float_status *status); float16 float16_sub(float16, float16, float_status *status); float16 float16_mul(float16, float16, float_status *status); float16 float16_muladd(float16, float16, float16, int, float_status *status); +float16 float16_muladd_scalbn(float16, float16, float16, int, int, float_status *status); float16 float16_div(float16, float16, float_status *status); float16 float16_scalbn(float16, int, float_status *status); -float16 float16_min(float16, float16, float_status *status); -float16 float16_max(float16, float16, float_status *status); -float16 float16_minnum(float16, float16, float_status *status); -float16 float16_maxnum(float16, float16, float_status *status); -float16 float16_minnummag(float16, float16, float_status *status); -float16 float16_maxnummag(float16, float16, float_status *status); -float16 float16_minimum_number(float16, float16, float_status *status); -float16 float16_maximum_number(float16, float16, float_status *status); +float16 float16_minmax(float16, float16, float_status *status, int flags); float16 float16_sqrt(float16, float_status *status); FloatRelation float16_compare(float16, float16, float_status *status); FloatRelation float16_compare_quiet(float16, float16, float_status *status); @@ -346,40 +375,50 @@ float32 bfloat16_to_float32(bfloat16, float_status *status); bfloat16 float64_to_bfloat16(float64 a, float_status *status); float64 bfloat16_to_float64(bfloat16 a, float_status *status); +int8_t bfloat16_to_int8_scalbn(bfloat16, FloatRoundMode, int, float_status *status); int16_t bfloat16_to_int16_scalbn(bfloat16, FloatRoundMode, int, float_status *status); int32_t bfloat16_to_int32_scalbn(bfloat16, FloatRoundMode, int, float_status *status); int64_t bfloat16_to_int64_scalbn(bfloat16, FloatRoundMode, int, float_status *status); +int8_t bfloat16_to_int8(bfloat16, float_status *status); int16_t bfloat16_to_int16(bfloat16, float_status *status); int32_t bfloat16_to_int32(bfloat16, float_status *status); int64_t bfloat16_to_int64(bfloat16, float_status *status); +int8_t bfloat16_to_int8_round_to_zero(bfloat16, float_status *status); int16_t bfloat16_to_int16_round_to_zero(bfloat16, float_status *status); int32_t bfloat16_to_int32_round_to_zero(bfloat16, float_status *status); int64_t bfloat16_to_int64_round_to_zero(bfloat16, float_status *status); +uint8_t bfloat16_to_uint8_scalbn(bfloat16 a, FloatRoundMode, int, float_status *status); uint16_t bfloat16_to_uint16_scalbn(bfloat16 a, FloatRoundMode, int, float_status *status); uint32_t bfloat16_to_uint32_scalbn(bfloat16 a, FloatRoundMode, int, float_status *status); uint64_t bfloat16_to_uint64_scalbn(bfloat16 a, FloatRoundMode, int, float_status *status); +uint8_t bfloat16_to_uint8(bfloat16 a, float_status *status); uint16_t bfloat16_to_uint16(bfloat16 a, float_status *status); uint32_t bfloat16_to_uint32(bfloat16 a, float_status *status); uint64_t bfloat16_to_uint64(bfloat16 a, float_status *status); +uint8_t bfloat16_to_uint8_round_to_zero(bfloat16 a, float_status *status); uint16_t bfloat16_to_uint16_round_to_zero(bfloat16 a, float_status *status); uint32_t bfloat16_to_uint32_round_to_zero(bfloat16 a, float_status *status); uint64_t bfloat16_to_uint64_round_to_zero(bfloat16 a, float_status *status); +bfloat16 int8_to_bfloat16_scalbn(int8_t a, int, float_status *status); bfloat16 int16_to_bfloat16_scalbn(int16_t a, int, float_status *status); bfloat16 int32_to_bfloat16_scalbn(int32_t a, int, float_status *status); bfloat16 int64_to_bfloat16_scalbn(int64_t a, int, float_status *status); +bfloat16 uint8_to_bfloat16_scalbn(uint8_t a, int, float_status *status); bfloat16 uint16_to_bfloat16_scalbn(uint16_t a, int, float_status *status); bfloat16 uint32_to_bfloat16_scalbn(uint32_t a, int, float_status *status); bfloat16 uint64_to_bfloat16_scalbn(uint64_t a, int, float_status *status); +bfloat16 int8_to_bfloat16(int8_t a, float_status *status); bfloat16 int16_to_bfloat16(int16_t a, float_status *status); bfloat16 int32_to_bfloat16(int32_t a, float_status *status); bfloat16 int64_to_bfloat16(int64_t a, float_status *status); +bfloat16 uint8_to_bfloat16(uint8_t a, float_status *status); bfloat16 uint16_to_bfloat16(uint16_t a, float_status *status); bfloat16 uint32_to_bfloat16(uint32_t a, float_status *status); bfloat16 uint64_to_bfloat16(uint64_t a, float_status *status); @@ -394,14 +433,7 @@ bfloat16 bfloat16_mul(bfloat16, bfloat16, float_status *status); bfloat16 bfloat16_div(bfloat16, bfloat16, float_status *status); bfloat16 bfloat16_muladd(bfloat16, bfloat16, bfloat16, int, float_status *status); float16 bfloat16_scalbn(bfloat16, int, float_status *status); -bfloat16 bfloat16_min(bfloat16, bfloat16, float_status *status); -bfloat16 bfloat16_max(bfloat16, bfloat16, float_status *status); -bfloat16 bfloat16_minnum(bfloat16, bfloat16, float_status *status); -bfloat16 bfloat16_maxnum(bfloat16, bfloat16, float_status *status); -bfloat16 bfloat16_minnummag(bfloat16, bfloat16, float_status *status); -bfloat16 bfloat16_maxnummag(bfloat16, bfloat16, float_status *status); -bfloat16 bfloat16_minimum_number(bfloat16, bfloat16, float_status *status); -bfloat16 bfloat16_maximum_number(bfloat16, bfloat16, float_status *status); +bfloat16 bfloat16_minmax(bfloat16, bfloat16, float_status *status, int flags); bfloat16 bfloat16_sqrt(bfloat16, float_status *status); FloatRelation bfloat16_compare(bfloat16, bfloat16, float_status *status); FloatRelation bfloat16_compare_quiet(bfloat16, bfloat16, float_status *status); @@ -540,19 +572,13 @@ float32 float32_mul(float32, float32, float_status *status); float32 float32_div(float32, float32, float_status *status); float32 float32_rem(float32, float32, float_status *status); float32 float32_muladd(float32, float32, float32, int, float_status *status); +float32 float32_muladd_scalbn(float32, float32, float32, int, int, float_status *status); float32 float32_sqrt(float32, float_status *status); float32 float32_exp2(float32, float_status *status); float32 float32_log2(float32, float_status *status); FloatRelation float32_compare(float32, float32, float_status *status); FloatRelation float32_compare_quiet(float32, float32, float_status *status); -float32 float32_min(float32, float32, float_status *status); -float32 float32_max(float32, float32, float_status *status); -float32 float32_minnum(float32, float32, float_status *status); -float32 float32_maxnum(float32, float32, float_status *status); -float32 float32_minnummag(float32, float32, float_status *status); -float32 float32_maxnummag(float32, float32, float_status *status); -float32 float32_minimum_number(float32, float32, float_status *status); -float32 float32_maximum_number(float32, float32, float_status *status); +float32 float32_minmax(float32, float32, float_status *status, int flags); bool float32_is_quiet_nan(float32, float_status *status); bool float32_is_signaling_nan(float32, float_status *status); float32 float32_silence_nan(float32, float_status *status); @@ -713,18 +739,12 @@ float64 float64_mul(float64, float64, float_status *status); float64 float64_div(float64, float64, float_status *status); float64 float64_rem(float64, float64, float_status *status); float64 float64_muladd(float64, float64, float64, int, float_status *status); +float64 float64_muladd_scalbn(float64, float64, float64, int, int, float_status *status); float64 float64_sqrt(float64, float_status *status); float64 float64_log2(float64, float_status *status); FloatRelation float64_compare(float64, float64, float_status *status); FloatRelation float64_compare_quiet(float64, float64, float_status *status); -float64 float64_min(float64, float64, float_status *status); -float64 float64_max(float64, float64, float_status *status); -float64 float64_minnum(float64, float64, float_status *status); -float64 float64_maxnum(float64, float64, float_status *status); -float64 float64_minnummag(float64, float64, float_status *status); -float64 float64_maxnummag(float64, float64, float_status *status); -float64 float64_minimum_number(float64, float64, float_status *status); -float64 float64_maximum_number(float64, float64, float_status *status); +float64 float64_minmax(float64, float64, float_status *status, int flags); bool float64_is_quiet_nan(float64 a, float_status *status); bool float64_is_signaling_nan(float64, float_status *status); float64 float64_silence_nan(float64, float_status *status); @@ -852,7 +872,7 @@ float128 floatx80_to_float128(floatx80, float_status *status); /*---------------------------------------------------------------------------- | The pattern for an extended double-precision inf. *----------------------------------------------------------------------------*/ -extern const floatx80 floatx80_infinity; +floatx80 floatx80_default_inf(bool zSign, float_status *status); /*---------------------------------------------------------------------------- | Software IEC/IEEE extended double-precision operations. @@ -869,8 +889,8 @@ floatx80 floatx80_rem(floatx80, floatx80, float_status *status); floatx80 floatx80_sqrt(floatx80, float_status *status); FloatRelation floatx80_compare(floatx80, floatx80, float_status *status); FloatRelation floatx80_compare_quiet(floatx80, floatx80, float_status *status); -int floatx80_is_quiet_nan(floatx80, float_status *status); -int floatx80_is_signaling_nan(floatx80, float_status *status); +bool floatx80_is_quiet_nan(floatx80, float_status *status); +bool floatx80_is_signaling_nan(floatx80, float_status *status); floatx80 floatx80_silence_nan(floatx80, float_status *status); floatx80 floatx80_scalbn(floatx80, int, float_status *status); @@ -884,12 +904,17 @@ static inline floatx80 floatx80_chs(floatx80 a) { return a; } -static inline bool floatx80_is_infinity(floatx80 a) { -#if defined(TARGET_M68K) - return (a.high & 0x7fff) == floatx80_infinity.high && !(a.low << 1); -#else - return (a.high & 0x7fff) == floatx80_infinity.high && a.low == floatx80_infinity.low; -#endif +static inline bool floatx80_is_infinity(floatx80 a, float_status *status) { + /* + * It's target-specific whether the Integer bit is permitted + * to be 0 in a valid Infinity value. (x86 says no, m68k says yes). + */ + bool intbit = a.low >> 63; + + if (!intbit && !(get_floatx80_behaviour(status) & floatx80_pseudo_inf_valid)) { + return false; + } + return (a.high & 0x7fff) == 0x7fff && !(a.low << 1); } static inline bool floatx80_is_neg(floatx80 a) { @@ -942,40 +967,46 @@ static inline bool floatx80_unordered_quiet(floatx80 a, floatx80 b, float_status /*---------------------------------------------------------------------------- | Return whether the given value is an invalid floatx80 encoding. -| Invalid floatx80 encodings arise when the integer bit is not set, but -| the exponent is not zero. The only times the integer bit is permitted to -| be zero is in subnormal numbers and the value zero. -| This includes what the Intel software developer's manual calls pseudo-NaNs, -| pseudo-infinities and un-normal numbers. It does not include -| pseudo-denormals, which must still be correctly handled as inputs even -| if they are never generated as outputs. +| Invalid floatx80 encodings may arise when the integer bit is not set +| correctly; this is target-specific. In Intel terminology the +| categories are: +| exp == 0, int = 0, mantissa == 0 : zeroes +| exp == 0, int = 0, mantissa != 0 : denormals +| exp == 0, int = 1 : pseudo-denormals +| 0 < exp < 0x7fff, int = 0 : unnormals +| 0 < exp < 0x7fff, int = 1 : normals +| exp == 0x7fff, int = 0, mantissa == 0 : pseudo-infinities +| exp == 0x7fff, int = 1, mantissa == 0 : infinities +| exp == 0x7fff, int = 0, mantissa != 0 : pseudo-NaNs +| exp == 0x7fff, int = 1, mantissa == 0 : NaNs +| +| The usual IEEE cases of zero, denormal, normal, inf and NaN are always valid. +| x87 permits as input also pseudo-denormals. +| m68k permits all those and also pseudo-infinities, pseudo-NaNs and unnormals. +| +| Since we don't have a target that handles floatx80 but prohibits +| pseudo-denormals in input, we don't currently have a floatx80_behaviour +| flag for that case, but instead always accept it. Conveniently this +| means that all cases with either exponent 0 or the integer bit set are +| valid for all targets. *----------------------------------------------------------------------------*/ -static inline bool floatx80_invalid_encoding(floatx80 a) { -#if defined(TARGET_M68K) - /*------------------------------------------------------------------------- - | With m68k, the explicit integer bit can be zero in the case of: - | - zeros (exp == 0, mantissa == 0) - | - denormalized numbers (exp == 0, mantissa != 0) - | - unnormalized numbers (exp != 0, exp < 0x7FFF) - | - infinities (exp == 0x7FFF, mantissa == 0) - | - not-a-numbers (exp == 0x7FFF, mantissa != 0) - | - | For infinities and NaNs, the explicit integer bit can be either one or - | zero. - | - | The IEEE 754 standard does not define a zero integer bit. Such a number - | is an unnormalized number. Hardware does not directly support - | denormalized and unnormalized numbers, but implicitly supports them by - | trapping them as unimplemented data types, allowing efficient conversion - | in software. - | - | See "M68000 FAMILY PROGRAMMER’S REFERENCE MANUAL", - | "1.6 FLOATING-POINT DATA TYPES" - *------------------------------------------------------------------------*/ - return false; -#else - return (a.low & (1ULL << 63)) == 0 && (a.high & 0x7FFF) != 0; -#endif +static inline bool floatx80_invalid_encoding(floatx80 a, float_status *s) { + FloatX80Behaviour rule = get_floatx80_behaviour(s); + + if ((a.low >> 63) || (a.high & 0x7fff) == 0) { + /* Anything with the Integer bit set or the exponent 0 is valid */ + return false; + } + + if ((a.high & 0x7fff) == 0x7fff) { + if (a.low) { + return !(rule & floatx80_pseudo_nan_valid); + } else { + return !(rule & floatx80_pseudo_inf_valid); + } + } else { + return !(rule & floatx80_unnormal_valid); + } } #define floatx80_zero make_floatx80(0x0000, 0x0000000000000000LL) @@ -1118,14 +1149,7 @@ float128 float128_rem(float128, float128, float_status *status); float128 float128_sqrt(float128, float_status *status); FloatRelation float128_compare(float128, float128, float_status *status); FloatRelation float128_compare_quiet(float128, float128, float_status *status); -float128 float128_min(float128, float128, float_status *status); -float128 float128_max(float128, float128, float_status *status); -float128 float128_minnum(float128, float128, float_status *status); -float128 float128_maxnum(float128, float128, float_status *status); -float128 float128_minnummag(float128, float128, float_status *status); -float128 float128_maxnummag(float128, float128, float_status *status); -float128 float128_minimum_number(float128, float128, float_status *status); -float128 float128_maximum_number(float128, float128, float_status *status); +float128 float128_minmax(float128, float128, float_status *status, int flags); bool float128_is_quiet_nan(float128, float_status *status); bool float128_is_signaling_nan(float128, float_status *status); float128 float128_silence_nan(float128, float_status *status); @@ -1208,6 +1232,34 @@ static inline bool float128_unordered_quiet(float128 a, float128 b, float_status *----------------------------------------------------------------------------*/ float128 float128_default_nan(float_status *status); +/*---------------------------------------------------------------------------- +| Minumum and maximum functions. +*----------------------------------------------------------------------------*/ + +#define MINMAX_1(type, name, flags) \ + static inline type type##_##name(type a, type b, float_status *s) { \ + return type##_minmax(a, b, s, flags); \ + } + +#define MINMAX_2(type) \ + MINMAX_1(type, max, 0) \ + MINMAX_1(type, maxnum, float_minmax_isnum) \ + MINMAX_1(type, maxnummag, float_minmax_isnum | float_minmax_ismag) \ + MINMAX_1(type, maximum_number, float_minmax_isnumber) \ + MINMAX_1(type, min, float_minmax_ismin) \ + MINMAX_1(type, minnum, float_minmax_ismin | float_minmax_isnum) \ + MINMAX_1(type, minnummag, float_minmax_ismin | float_minmax_isnum | float_minmax_ismag) \ + MINMAX_1(type, minimum_number, float_minmax_ismin | float_minmax_isnumber) + +MINMAX_2(float16) +MINMAX_2(bfloat16) +MINMAX_2(float32) +MINMAX_2(float64) +MINMAX_2(float128) + +#undef MINMAX_1 +#undef MINMAX_2 + #ifdef __cplusplus } #endif diff --git a/libtcg/include/tcg/utils/bitops.h b/libtcg/include/tcg/utils/bitops.h index 293213273..33be69150 100644 --- a/libtcg/include/tcg/utils/bitops.h +++ b/libtcg/include/tcg/utils/bitops.h @@ -12,6 +12,7 @@ #ifndef BITOPS_H #define BITOPS_H +#include #include #include "atomic.h" diff --git a/libtcg/include/tcg/utils/bswap.h b/libtcg/include/tcg/utils/bswap.h index 1bbb1f871..9db21834c 100644 --- a/libtcg/include/tcg/utils/bswap.h +++ b/libtcg/include/tcg/utils/bswap.h @@ -21,7 +21,6 @@ // #include -#include #include #ifdef __cplusplus @@ -182,62 +181,6 @@ static inline void cpu_to_be32wu(uint32_t *p, uint32_t v) { #undef le_bswaps #undef be_bswaps -typedef union { - float32 f; - uint32_t l; -} CPU_FloatU; - -typedef union { - float64 d; -#if defined(HOST_WORDS_BIGENDIAN) - struct { - uint32_t upper; - uint32_t lower; - } l; -#else - struct { - uint32_t lower; - uint32_t upper; - } l; -#endif - uint64_t ll; -} CPU_DoubleU; - -typedef union { - floatx80 d; - struct { - uint64_t lower; - uint16_t upper; - } l; -} CPU_LDoubleU; - -typedef union { - float128 q; -#if defined(HOST_WORDS_BIGENDIAN) - struct { - uint32_t upmost; - uint32_t upper; - uint32_t lower; - uint32_t lowest; - } l; - struct { - uint64_t upper; - uint64_t lower; - } ll; -#else - struct { - uint32_t lowest; - uint32_t lower; - uint32_t upper; - uint32_t upmost; - } l; - struct { - uint64_t lower; - uint64_t upper; - } ll; -#endif -} CPU_QuadU; - static inline int ldub_p(const void *ptr) { return *(uint8_t *) ptr; } @@ -280,22 +223,6 @@ static inline void stq_le_p(void *ptr, uint64_t v) { /* float access */ -static inline float32 ldfl_le_p(const void *ptr) { - return *(float32 *) ptr; -} - -static inline float64 ldfq_le_p(const void *ptr) { - return *(float64 *) ptr; -} - -static inline void stfl_le_p(void *ptr, float32 v) { - *(float32 *) ptr = v; -} - -static inline void stfq_le_p(void *ptr, float64 v) { - *(float64 *) ptr = v; -} - /* some important defines: * * WORDS_ALIGNED : if defined, the host cpu can only make word aligned diff --git a/libtcg/include/tcg/utils/cpu-float.h b/libtcg/include/tcg/utils/cpu-float.h new file mode 100644 index 000000000..48578d891 --- /dev/null +++ b/libtcg/include/tcg/utils/cpu-float.h @@ -0,0 +1,95 @@ +// Unions for reinterpreting between floats and integers. +// +// Upstream QEMU keeps these in include/qemu/cpu-float.h rather than in +// bswap.h: they are the only part that needs softfloat types, and leaving +// them in bswap.h creates an include cycle now that softfloat-types.h pulls +// in registerfields.h -> bitops.h -> host-utils.h -> bswap.h. + +#ifndef TCG_CPU_FLOAT_H +#define TCG_CPU_FLOAT_H + +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef union { + float32 f; + uint32_t l; +} CPU_FloatU; + +typedef union { + float64 d; +#if defined(HOST_WORDS_BIGENDIAN) + struct { + uint32_t upper; + uint32_t lower; + } l; +#else + struct { + uint32_t lower; + uint32_t upper; + } l; +#endif + uint64_t ll; +} CPU_DoubleU; + +typedef union { + floatx80 d; + struct { + uint64_t lower; + uint16_t upper; + } l; +} CPU_LDoubleU; + +typedef union { + float128 q; +#if defined(HOST_WORDS_BIGENDIAN) + struct { + uint32_t upmost; + uint32_t upper; + uint32_t lower; + uint32_t lowest; + } l; + struct { + uint64_t upper; + uint64_t lower; + } ll; +#else + struct { + uint32_t lowest; + uint32_t lower; + uint32_t upper; + uint32_t upmost; + } l; + struct { + uint64_t lower; + uint64_t upper; + } ll; +#endif +} CPU_QuadU; + +static inline float32 ldfl_le_p(const void *ptr) { + return *(float32 *) ptr; +} + +static inline float64 ldfq_le_p(const void *ptr) { + return *(float64 *) ptr; +} + +static inline void stfl_le_p(void *ptr, float32 v) { + *(float32 *) ptr = v; +} + +static inline void stfq_le_p(void *ptr, float64 v) { + *(float64 *) ptr = v; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libtcg/include/tcg/utils/host-utils.h b/libtcg/include/tcg/utils/host-utils.h index a3f0a5e7e..11105f758 100644 --- a/libtcg/include/tcg/utils/host-utils.h +++ b/libtcg/include/tcg/utils/host-utils.h @@ -32,7 +32,6 @@ #include -#include "bswap.h" #include "int128.h" #ifdef __cplusplus @@ -324,7 +323,7 @@ static inline uint16_t revbit16(uint16_t x) { return __builtin_bitreverse16(x); #else /* Assign the correct byte position. */ - x = bswap16(x); + x = __builtin_bswap16(x); /* Assign the correct nibble position. */ x = ((x & 0xf0f0) >> 4) | ((x & 0x0f0f) << 4); /* Assign the correct bit position. */ @@ -342,7 +341,7 @@ static inline uint32_t revbit32(uint32_t x) { return __builtin_bitreverse32(x); #else /* Assign the correct byte position. */ - x = bswap32(x); + x = __builtin_bswap32(x); /* Assign the correct nibble position. */ x = ((x & 0xf0f0f0f0u) >> 4) | ((x & 0x0f0f0f0fu) << 4); /* Assign the correct bit position. */ @@ -360,7 +359,7 @@ static inline uint64_t revbit64(uint64_t x) { return __builtin_bitreverse64(x); #else /* Assign the correct byte position. */ - x = bswap64(x); + x = __builtin_bswap64(x); /* Assign the correct nibble position. */ x = ((x & 0xf0f0f0f0f0f0f0f0ull) >> 4) | ((x & 0x0f0f0f0f0f0f0f0full) << 4); /* Assign the correct bit position. */ diff --git a/libtcg/include/tcg/utils/osdep.h b/libtcg/include/tcg/utils/osdep.h index 168b0a597..fcff9c033 100644 --- a/libtcg/include/tcg/utils/osdep.h +++ b/libtcg/include/tcg/utils/osdep.h @@ -94,6 +94,16 @@ extern "C" { #define QEMU_FLATTEN #endif +/* + * If __attribute__((always_inline)) is available, use it to force inlining + * where softfloat relies on constant folding of its format parameters. + */ +#if __has_attribute(always_inline) || !defined(__clang__) +#define QEMU_ALWAYS_INLINE __attribute__((always_inline)) +#else +#define QEMU_ALWAYS_INLINE +#endif + /* * If __attribute__((error)) is present, use it to produce an error at * compile time. Otherwise, one must wait for the linker to diagnose diff --git a/libtcg/include/tcg/utils/registerfields.h b/libtcg/include/tcg/utils/registerfields.h new file mode 100644 index 000000000..5ef2261b7 --- /dev/null +++ b/libtcg/include/tcg/utils/registerfields.h @@ -0,0 +1,215 @@ +/* + * Register Definition API: field macros + * + * Copyright (c) 2016 Xilinx Inc. + * Copyright (c) 2013 Peter Crosthwaite + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + */ + +#ifndef REGISTERFIELDS_H +#define REGISTERFIELDS_H + +#include + +/* Define constants for a 32 bit register */ + +/* This macro will define A_FOO, for the byte address of a register + * as well as R_FOO for the uint32_t[] register number (A_FOO / 4). + */ +#define REG32(reg, addr) \ + enum { A_##reg = (addr) }; \ + enum { R_##reg = (addr) / 4 }; + +#define REG8(reg, addr) \ + enum { A_##reg = (addr) }; \ + enum { R_##reg = (addr) }; + +#define REG16(reg, addr) \ + enum { A_##reg = (addr) }; \ + enum { R_##reg = (addr) / 2 }; + +#define REG64(reg, addr) \ + enum { A_##reg = (addr) }; \ + enum { R_##reg = (addr) / 8 }; + +/* Define SHIFT, LENGTH and MASK constants for a field within a register */ + +/* This macro will define R_FOO_BAR_MASK, R_FOO_BAR_SHIFT and R_FOO_BAR_LENGTH + * constants for field BAR in register FOO. + */ +#define FIELD(reg, field, shift, length) \ + enum { R_##reg##_##field##_SHIFT = (shift) }; \ + enum { R_##reg##_##field##_LENGTH = (length) }; \ + enum { R_##reg##_##field##_MASK = MAKE_64BIT_MASK(shift, length) }; + +/* Extract a field from a register */ +#define FIELD_EX8(storage, reg, field) extract8((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH) +#define FIELD_EX16(storage, reg, field) extract16((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH) +#define FIELD_EX32(storage, reg, field) extract32((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH) +#define FIELD_EX64(storage, reg, field) extract64((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH) + +#define FIELD_SEX8(storage, reg, field) sextract8((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH) +#define FIELD_SEX16(storage, reg, field) sextract16((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH) +#define FIELD_SEX32(storage, reg, field) sextract32((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH) +#define FIELD_SEX64(storage, reg, field) sextract64((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH) + +/* Extract a field from an array of registers */ +#define ARRAY_FIELD_EX32(regs, reg, field) FIELD_EX32((regs)[R_##reg], reg, field) +#define ARRAY_FIELD_EX64(regs, reg, field) FIELD_EX64((regs)[R_##reg], reg, field) + +/* Deposit a register field. + * Assigning values larger then the target field will result in + * compilation warnings. + */ +#define FIELD_DP8(storage, reg, field, val) \ + ({ \ + struct { \ + unsigned int v : R_##reg##_##field##_LENGTH; \ + } _v = {.v = val}; \ + uint8_t _d; \ + _d = deposit32((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH, _v.v); \ + _d; \ + }) +#define FIELD_DP16(storage, reg, field, val) \ + ({ \ + struct { \ + unsigned int v : R_##reg##_##field##_LENGTH; \ + } _v = {.v = val}; \ + uint16_t _d; \ + _d = deposit32((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH, _v.v); \ + _d; \ + }) +#define FIELD_DP32(storage, reg, field, val) \ + ({ \ + struct { \ + unsigned int v : R_##reg##_##field##_LENGTH; \ + } _v = {.v = val}; \ + uint32_t _d; \ + _d = deposit32((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH, _v.v); \ + _d; \ + }) +#define FIELD_DP64(storage, reg, field, val) \ + ({ \ + struct { \ + uint64_t v : R_##reg##_##field##_LENGTH; \ + } _v = {.v = val}; \ + uint64_t _d; \ + _d = deposit64((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH, _v.v); \ + _d; \ + }) + +#define FIELD_SDP8(storage, reg, field, val) \ + ({ \ + struct { \ + signed int v : R_##reg##_##field##_LENGTH; \ + } _v = {.v = val}; \ + uint8_t _d; \ + _d = deposit32((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH, _v.v); \ + _d; \ + }) +#define FIELD_SDP16(storage, reg, field, val) \ + ({ \ + struct { \ + signed int v : R_##reg##_##field##_LENGTH; \ + } _v = {.v = val}; \ + uint16_t _d; \ + _d = deposit32((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH, _v.v); \ + _d; \ + }) +#define FIELD_SDP32(storage, reg, field, val) \ + ({ \ + struct { \ + signed int v : R_##reg##_##field##_LENGTH; \ + } _v = {.v = val}; \ + uint32_t _d; \ + _d = deposit32((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH, _v.v); \ + _d; \ + }) +#define FIELD_SDP64(storage, reg, field, val) \ + ({ \ + struct { \ + int64_t v : R_##reg##_##field##_LENGTH; \ + } _v = {.v = val}; \ + uint64_t _d; \ + _d = deposit64((storage), R_##reg##_##field##_SHIFT, R_##reg##_##field##_LENGTH, _v.v); \ + _d; \ + }) + +/* Deposit a field to array of registers. */ +#define ARRAY_FIELD_DP32(regs, reg, field, val) (regs)[R_##reg] = FIELD_DP32((regs)[R_##reg], reg, field, val); +#define ARRAY_FIELD_DP64(regs, reg, field, val) (regs)[R_##reg] = FIELD_DP64((regs)[R_##reg], reg, field, val); + +/* + * These macros can be used for defining and extracting fields that have the + * same bit position across multiple registers. + */ + +/* Define shared SHIFT, LENGTH, and MASK constants */ +#define SHARED_FIELD(name, shift, length) \ + enum { name##_##SHIFT = (shift) }; \ + enum { name##_##LENGTH = (length) }; \ + enum { name##_##MASK = MAKE_64BIT_MASK(shift, length) }; + +/* Extract a shared field */ +#define SHARED_FIELD_EX8(storage, field) extract8((storage), field##_SHIFT, field##_LENGTH) + +#define SHARED_FIELD_EX16(storage, field) extract16((storage), field##_SHIFT, field##_LENGTH) + +#define SHARED_FIELD_EX32(storage, field) extract32((storage), field##_SHIFT, field##_LENGTH) + +#define SHARED_FIELD_EX64(storage, field) extract64((storage), field##_SHIFT, field##_LENGTH) + +/* Extract a shared field from a register array */ +#define SHARED_ARRAY_FIELD_EX32(regs, offset, field) SHARED_FIELD_EX32((regs)[(offset)], field) +#define SHARED_ARRAY_FIELD_EX64(regs, offset, field) SHARED_FIELD_EX64((regs)[(offset)], field) + +/* Deposit a shared field */ +#define SHARED_FIELD_DP8(storage, field, val) \ + ({ \ + struct { \ + unsigned int v : field##_LENGTH; \ + } _v = {.v = val}; \ + uint8_t _d; \ + _d = deposit32((storage), field##_SHIFT, field##_LENGTH, _v.v); \ + _d; \ + }) + +#define SHARED_FIELD_DP16(storage, field, val) \ + ({ \ + struct { \ + unsigned int v : field##_LENGTH; \ + } _v = {.v = val}; \ + uint16_t _d; \ + _d = deposit32((storage), field##_SHIFT, field##_LENGTH, _v.v); \ + _d; \ + }) + +#define SHARED_FIELD_DP32(storage, field, val) \ + ({ \ + struct { \ + unsigned int v : field##_LENGTH; \ + } _v = {.v = val}; \ + uint32_t _d; \ + _d = deposit32((storage), field##_SHIFT, field##_LENGTH, _v.v); \ + _d; \ + }) + +#define SHARED_FIELD_DP64(storage, field, val) \ + ({ \ + struct { \ + uint64_t v : field##_LENGTH; \ + } _v = {.v = val}; \ + uint64_t _d; \ + _d = deposit64((storage), field##_SHIFT, field##_LENGTH, _v.v); \ + _d; \ + }) + +/* Deposit a shared field to a register array */ +#define SHARED_ARRAY_FIELD_DP32(regs, offset, field, val) \ + (regs)[(offset)] = SHARED_FIELD_DP32((regs)[(offset)], field, val); +#define SHARED_ARRAY_FIELD_DP64(regs, offset, field, val) \ + (regs)[(offset)] = SHARED_FIELD_DP64((regs)[(offset)], field, val); + +#endif diff --git a/libtcg/scripts/upgrade/README.md b/libtcg/scripts/upgrade/README.md index c08edced3..64a9404b6 100644 --- a/libtcg/scripts/upgrade/README.md +++ b/libtcg/scripts/upgrade/README.md @@ -41,10 +41,22 @@ which need a human decision. Not every libtcg file tracks upstream closely. Several utility files (`utils/osdep.h`, `utils/cutils.c`, `utils/log.c`, `utils/bitmap.h`) are heavily -reduced S2E-specific subsets, and the `fpu/` tree still sits at QEMU v8.1.0. +reduced S2E-specific subsets, and most of `utils/` still sits at QEMU v8.1.0. These are listed in `mapping.tsv` for reference but normally want a manual look rather than a mechanical merge. +Two S2E deviations in the merged code are deliberate and must survive future +merges: + +- `float_status.float_rounding_mode` is a plain field rather than a bitfield. + S2E addresses the CPU state by (offset, size) so helpers running as bitcode + inside KLEE can read it back, which `offsetof`/`sizeof` on a bitfield cannot + express. +- `utils/cpu-float.h` holds the float/integer reinterpretation unions that + upstream keeps in `include/qemu/cpu-float.h`. Leaving them in `bswap.h`, as + older libtcg did, creates an include cycle through `softfloat-types.h` -> + `registerfields.h` -> `bitops.h` -> `host-utils.h` -> `bswap.h`. + ## After merging Re-run `run-clang-format.sh` from the S2E source root so the tree stays diff --git a/libtcg/scripts/upgrade/mapping.tsv b/libtcg/scripts/upgrade/mapping.tsv index c2610f244..5f8388006 100644 --- a/libtcg/scripts/upgrade/mapping.tsv +++ b/libtcg/scripts/upgrade/mapping.tsv @@ -68,7 +68,8 @@ include/tcg/utils/host/generic/load-extract-al16-al8.h host/include/generic/host include/tcg/utils/host/generic/store-insert-al16.h host/include/generic/host/store-insert-al16.h.inc src/utils/cpuinfo-i386.c util/cpuinfo-i386.c # --- utilities ---------------------------------------------------------- -# Still at QEMU v8.1.0; upgrade deliberately lags the TCG core. +# Mostly still at QEMU v8.1.0; the upgrade deliberately lags the TCG core, +# and only what newer TCG or softfloat actually needs has been pulled in. include/tcg/utils/atomic.h include/qemu/atomic.h include/tcg/utils/atomic128.h include/qemu/atomic128.h include/tcg/utils/bitops.h include/qemu/bitops.h @@ -81,6 +82,8 @@ include/tcg/utils/interval-tree.h include/qemu/interval-tree.h include/tcg/utils/memalign.h include/qemu/memalign.h include/tcg/utils/qtree.h include/qemu/qtree.h include/tcg/utils/units.h include/qemu/units.h +include/tcg/utils/registerfields.h include/hw/core/registerfields.h +include/tcg/utils/cpu-float.h include/qemu/cpu-float.h src/utils/host-utils.c util/host-utils.c src/utils/interval-tree.c util/interval-tree.c src/utils/memalign.c util/memalign.c @@ -95,12 +98,11 @@ src/utils/cutils.c util/cutils.c src/utils/log.c util/log.c src/utils/osdep.c util/osdep.c # --- fpu ---------------------------------------------------------------- -# Still at QEMU v8.1.0. Upgrading softfloat changes float semantics that -# KLEE interprets symbolically via softfloat.bc; treat as a separate task. include/fpu/softfloat.h include/fpu/softfloat.h include/fpu/softfloat-types.h include/fpu/softfloat-types.h include/fpu/softfloat-macros.h include/fpu/softfloat-macros.h include/fpu/softfloat-helpers.h include/fpu/softfloat-helpers.h +include/fpu/softfloat-parts.h include/fpu/softfloat-parts.h src/fpu/softfloat.c fpu/softfloat.c src/fpu/softfloat-parts.c.inc fpu/softfloat-parts.c.inc src/fpu/softfloat-parts-addsub.c.inc fpu/softfloat-parts-addsub.c.inc diff --git a/libtcg/src/fpu/softfloat-parts-addsub.c.inc b/libtcg/src/fpu/softfloat-parts-addsub.c.inc index f0a2fa7da..f8fe80498 100644 --- a/libtcg/src/fpu/softfloat-parts-addsub.c.inc +++ b/libtcg/src/fpu/softfloat-parts-addsub.c.inc @@ -19,14 +19,14 @@ static void partsN(add_normal)(FloatPartsN *a, FloatPartsN *b) { int exp_diff = a->exp - b->exp; if (exp_diff > 0) { - frac_shrjam(b, exp_diff); + fracN(shrjam)(b, exp_diff); } else if (exp_diff < 0) { - frac_shrjam(a, -exp_diff); + fracN(shrjam)(a, -exp_diff); a->exp = b->exp; } - if (frac_add(a, a, b)) { - frac_shrjam(a, 1); + if (fracN(add)(a, a, b)) { + fracN(shrjam)(a, 1); a->frac_hi |= DECOMPOSED_IMPLICIT_BIT; a->exp += 1; } @@ -37,20 +37,20 @@ static bool partsN(sub_normal)(FloatPartsN *a, FloatPartsN *b) { int shift; if (exp_diff > 0) { - frac_shrjam(b, exp_diff); - frac_sub(a, a, b); + fracN(shrjam)(b, exp_diff); + fracN(sub)(a, a, b); } else if (exp_diff < 0) { a->exp = b->exp; a->sign ^= 1; - frac_shrjam(a, -exp_diff); - frac_sub(a, b, a); - } else if (frac_sub(a, a, b)) { + fracN(shrjam)(a, -exp_diff); + fracN(sub)(a, b, a); + } else if (fracN(sub)(a, a, b)) { /* Overflow means that A was less than B. */ - frac_neg(a); + fracN(neg)(a); a->sign ^= 1; } - shift = frac_normalize(a); + shift = fracN(normalize)(a); if (likely(shift < N)) { a->exp -= shift; return true; diff --git a/libtcg/src/fpu/softfloat-parts.c.inc b/libtcg/src/fpu/softfloat-parts.c.inc index fbd8fd544..6720e00d2 100644 --- a/libtcg/src/fpu/softfloat-parts.c.inc +++ b/libtcg/src/fpu/softfloat-parts.c.inc @@ -15,84 +15,171 @@ * indicated otherwise. */ -static void partsN(return_nan)(FloatPartsN *a, float_status *s) { +FloatPartsN partsN(return_nan)(const FloatPartsN *a, float_status *s) { switch (a->cls) { case float_class_snan: float_raise(float_flag_invalid | float_flag_invalid_snan, s); - if (s->default_nan_mode) { - parts_default_nan(a, s); + if (get_default_nan_mode(s)) { + return partsN(default_nan)(s); } else { - parts_silence_nan(a, s); + return partsN(silence_nan)(a, s); } break; case float_class_qnan: - if (s->default_nan_mode) { - parts_default_nan(a, s); + if (get_default_nan_mode(s)) { + return partsN(default_nan)(s); } break; default: g_assert_not_reached(); } + return *a; } -static FloatPartsN *partsN(pick_nan)(FloatPartsN *a, FloatPartsN *b, float_status *s) { +FloatPartsN partsN(pick_nan)(const FloatPartsN *a, const FloatPartsN *b, float_status *s) { + bool have_snan = false; + const FloatPartsN *ret; + int cmp; + if (is_snan(a->cls) || is_snan(b->cls)) { float_raise(float_flag_invalid | float_flag_invalid_snan, s); + have_snan = true; } - if (s->default_nan_mode) { - parts_default_nan(a, s); - } else { - int cmp = frac_cmp(a, b); - if (cmp == 0) { - cmp = a->sign < b->sign; - } + if (get_default_nan_mode(s)) { + return partsN(default_nan)(s); + } - if (pickNaN(a->cls, b->cls, cmp > 0, s)) { - a = b; - } - if (is_snan(a->cls)) { - parts_silence_nan(a, s); - } + switch (get_float_2nan_prop_rule(s)) { + case float_2nan_prop_s_ab: + if (have_snan) { + ret = is_snan(a->cls) ? a : b; + break; + } + /* fall through */ + case float_2nan_prop_ab: + ret = is_nan(a->cls) ? a : b; + break; + case float_2nan_prop_s_ba: + if (have_snan) { + ret = is_snan(b->cls) ? b : a; + break; + } + /* fall through */ + case float_2nan_prop_ba: + ret = is_nan(b->cls) ? b : a; + break; + case float_2nan_prop_x87: + /* + * This implements x87 NaN propagation rules: + * SNaN + QNaN => return the QNaN + * two SNaNs => return the one with the larger significand, silenced + * two QNaNs => return the one with the larger significand + * SNaN and a non-NaN => return the SNaN, silenced + * QNaN and a non-NaN => return the QNaN + * + * If we get down to comparing significands and they are the same, + * return the NaN with the positive sign bit (if any). + */ + if (is_snan(a->cls)) { + if (!is_snan(b->cls)) { + ret = is_qnan(b->cls) ? b : a; + break; + } + } else if (is_qnan(a->cls)) { + if (is_snan(b->cls) || !is_qnan(b->cls)) { + ret = a; + break; + } + } else { + ret = b; + break; + } + cmp = fracN(cmp)(a, b); + if (cmp == 0) { + cmp = a->sign < b->sign; + } + ret = cmp > 0 ? a : b; + break; + default: + g_assert_not_reached(); } - return a; + + if (is_snan(ret->cls)) { + return partsN(silence_nan)(ret, s); + } + return *ret; } -static FloatPartsN *partsN(pick_nan_muladd)(FloatPartsN *a, FloatPartsN *b, FloatPartsN *c, float_status *s, - int ab_mask, int abc_mask) { - int which; +static FloatPartsN partsN(pick_nan_muladd)(const FloatPartsN *a, const FloatPartsN *b, const FloatPartsN *c, + float_status *s, int ab_mask, int abc_mask) { + bool infzero = (ab_mask == float_cmask_infzero); + bool have_snan = (abc_mask & float_cmask_snan); + FloatInfZeroNaNRule izn_rule = get_float_infzeronan_rule(s); + const FloatPartsN *ret; - if (unlikely(abc_mask & float_cmask_snan)) { + if (unlikely(have_snan)) { float_raise(float_flag_invalid | float_flag_invalid_snan, s); } - which = pickNaNMulAdd(a->cls, b->cls, c->cls, ab_mask == float_cmask_infzero, s); + if (infzero && !(izn_rule & float_infzeronan_suppress_invalid)) { + /* This is (0 * inf) + NaN or (inf * 0) + NaN */ + float_raise(float_flag_invalid | float_flag_invalid_imz, s); + } - if (s->default_nan_mode || which == 3) { + if (get_default_nan_mode(s)) { /* - * Note that this check is after pickNaNMulAdd so that function - * has an opportunity to set the Invalid flag for infzero. + * We guarantee not to require the target to tell us how to + * pick a NaN if we're always returning the default NaN. + * But if we're not in default-NaN mode then the target must + * specify. */ - parts_default_nan(a, s); - return a; + goto default_nan; + } else if (infzero) { + /* + * Inf * 0 + NaN -- some implementations return the + * default NaN here, and some return the input NaN. + */ + switch (izn_rule & ~float_infzeronan_suppress_invalid) { + case float_infzeronan_dnan_never: + break; + case float_infzeronan_dnan_always: + goto default_nan; + case float_infzeronan_dnan_if_qnan: + if (is_qnan(c->cls)) { + goto default_nan; + } + break; + default: + g_assert_not_reached(); + } + ret = c; + } else { + const FloatPartsN *val[R_3NAN_1ST_MASK + 1] = {a, b, c}; + Float3NaNPropRule rule = get_float_3nan_prop_rule(s); + + assert(rule != float_3nan_prop_none); + if (have_snan && (rule & R_3NAN_SNAN_MASK)) { + /* We have at least one SNaN input and should prefer it */ + do { + ret = val[rule & R_3NAN_1ST_MASK]; + rule >>= R_3NAN_1ST_LENGTH; + } while (!is_snan(ret->cls)); + } else { + do { + ret = val[rule & R_3NAN_1ST_MASK]; + rule >>= R_3NAN_1ST_LENGTH; + } while (!is_nan(ret->cls)); + } } - switch (which) { - case 0: - break; - case 1: - a = b; - break; - case 2: - a = c; - break; - default: - g_assert_not_reached(); - } - if (is_snan(a->cls)) { - parts_silence_nan(a, s); + if (is_snan(ret->cls)) { + return partsN(silence_nan)(ret, s); } - return a; + return *ret; + +default_nan: + return partsN(default_nan)(s); } /* @@ -100,29 +187,68 @@ static FloatPartsN *partsN(pick_nan_muladd)(FloatPartsN *a, FloatPartsN *b, Floa * unbias the exponent, and normalize the fraction. */ static void partsN(canonicalize)(FloatPartsN *p, float_status *status, const FloatFmt *fmt) { + /* + * It's target-dependent how to handle the case of exponent 0 + * and Integer bit set. Intel calls these "pseudodenormals", + * and treats them as if the integer bit was 0, and never + * produces them on output. This is the default behaviour for QEMU. + * For m68k, the integer bit is considered validly part of the + * input value when the exponent is 0, and may be 0 or 1, + * giving extra range. They may also be generated as outputs. + * (The m68k manual actually calls these values part of the + * normalized number range, not the denormalized number range, + * but that distinction is not important for us, because + * m68k doesn't care about the input_denormal_used status flag.) + * floatx80_pseudo_denormal_valid selects the m68k behaviour, + * which changes both how we canonicalize such a value and + * how we uncanonicalize results. + */ + bool has_pseudo_denormals = + fmt->has_explicit_bit && (get_floatx80_behaviour(status) & floatx80_pseudo_denormal_valid); + if (unlikely(p->exp == 0)) { - if (likely(frac_eqz(p))) { + if (likely(fracN(eqz)(p))) { p->cls = float_class_zero; - } else if (status->flush_inputs_to_zero) { - float_raise(float_flag_input_denormal, status); + } else if (get_flush_inputs_to_zero(status)) { + float_raise(float_flag_input_denormal_flushed, status); p->cls = float_class_zero; - frac_clear(p); + fracN(clear)(p); } else { - int shift = frac_normalize(p); - p->cls = float_class_normal; - p->exp = fmt->frac_shift - fmt->exp_bias - shift + 1; + int shift = fracN(normalize)(p); + p->cls = float_class_denormal; + p->exp = fmt->frac_shift - fmt->exp_bias - shift + !has_pseudo_denormals; } - } else if (likely(p->exp < fmt->exp_max) || fmt->arm_althp) { - p->cls = float_class_normal; - p->exp -= fmt->exp_bias; - frac_shl(p, fmt->frac_shift); - p->frac_hi |= DECOMPOSED_IMPLICIT_BIT; - } else if (likely(frac_eqz(p))) { - p->cls = float_class_inf; - } else { - frac_shl(p, fmt->frac_shift); - p->cls = (parts_is_snan_frac(p->frac_hi, status) ? float_class_snan : float_class_qnan); + return; } + if (unlikely(p->exp == fmt->exp_max)) { + switch (fmt->exp_max_kind) { + case float_expmax_ieee: + if (likely(fracN(eqz)(p))) { + p->cls = float_class_inf; + } else { + fracN(shl)(p, fmt->frac_shift); + p->cls = (parts_is_snan_frac(p->frac_hi, status) ? float_class_snan : float_class_qnan); + } + return; + case float_expmax_normal: + break; + case float_expmax_e4m3: + if (p->frac_hi == 0b111) { + fracN(shl)(p, fmt->frac_shift); + p->cls = (get_float_e4m3_nan_is_snan(status) ? float_class_snan : float_class_qnan); + return; + } + /* otherwise normal */ + break; + default: + g_assert_not_reached(); + } + } + + p->cls = float_class_normal; + p->exp -= fmt->exp_bias; + fracN(shl)(p, fmt->frac_shift); + p->frac_hi |= DECOMPOSED_IMPLICIT_BIT; } /* @@ -130,8 +256,28 @@ static void partsN(canonicalize)(FloatPartsN *p, float_status *status, const Flo * are FRAC_SHIFT bits that may require rounding at the bottom of the * fraction; these bits will be removed. The exponent will be biased * by EXP_BIAS and must be bounded by [EXP_MAX-1, 0]. + * + * The saturate parameter controls saturation behavior for formats that + * support it -- when true, overflow produces max normal instead of infinity. */ -static void partsN(uncanon_normal)(FloatPartsN *p, float_status *s, const FloatFmt *fmt) { + +/* Helper for uncanon_normal and uncanon, for FP8 E4M3. */ +static void partsN(uncanon_e4m3_overflow)(FloatPartsN *p, float_status *s, const FloatFmt *fmt, bool saturate) { + assert(N == 64); + p->exp = fmt->exp_max; + if (saturate) { + p->frac_hi = E4M3_NORMAL_FRAC_MAX; + } else { + /* + * The class isn't actually used after this point in uncanon, + * but for clarity while debugging, don't leave it set to normal. + */ + p->cls = float_class_qnan; + p->frac_hi = E4M3_NAN_FRAC; + } +} + +static void partsN(uncanon_normal)(FloatPartsN *p, float_status *s, const FloatFmt *fmt, bool saturate) { const int exp_max = fmt->exp_max; const int frac_shift = fmt->frac_shift; const uint64_t round_mask = fmt->round_mask; @@ -139,10 +285,14 @@ static void partsN(uncanon_normal)(FloatPartsN *p, float_status *s, const FloatF const uint64_t frac_lsbm1 = round_mask ^ (round_mask >> 1); const uint64_t roundeven_mask = round_mask | frac_lsb; uint64_t inc; - bool overflow_norm = false; - int exp, flags = 0; + bool overflow_norm = saturate; + int exp; + FloatExceptionFlags flags = 0; - switch (s->float_rounding_mode) { + switch (get_float_rounding_mode(s)) { + case float_round_nearest_even_max: + overflow_norm = true; + /* fall through */ case float_round_nearest_even: if (N > 64 && frac_lsb == 0) { inc = ((p->frac_hi & 1) || (p->frac_lo & round_mask) != frac_lsbm1 ? frac_lsbm1 : 0); @@ -159,11 +309,11 @@ static void partsN(uncanon_normal)(FloatPartsN *p, float_status *s, const FloatF break; case float_round_up: inc = p->sign ? 0 : round_mask; - overflow_norm = p->sign; + overflow_norm |= p->sign; break; case float_round_down: inc = p->sign ? round_mask : 0; - overflow_norm = !p->sign; + overflow_norm |= !p->sign; break; case float_round_to_odd: overflow_norm = true; @@ -183,72 +333,92 @@ static void partsN(uncanon_normal)(FloatPartsN *p, float_status *s, const FloatF if (likely(exp > 0)) { if (p->frac_lo & round_mask) { flags |= float_flag_inexact; - if (frac_addi(p, p, inc)) { - frac_shr(p, 1); + if (fracN(addi)(p, p, inc)) { + fracN(shr)(p, 1); p->frac_hi |= DECOMPOSED_IMPLICIT_BIT; exp++; } p->frac_lo &= ~round_mask; } - if (fmt->arm_althp) { - /* ARM Alt HP eschews Inf and NaN for a wider exponent. */ - if (unlikely(exp > exp_max)) { - /* Overflow. Return the maximum normal. */ - flags = float_flag_invalid; - exp = exp_max; - frac_allones(p); - p->frac_lo &= ~round_mask; - } - } else if (unlikely(exp >= exp_max)) { - flags |= float_flag_overflow; - if (s->rebias_overflow) { - exp -= fmt->exp_re_bias; - } else if (overflow_norm) { - flags |= float_flag_inexact; - exp = exp_max - 1; - frac_allones(p); - p->frac_lo &= ~round_mask; - } else { - flags |= float_flag_inexact; - p->cls = float_class_inf; - exp = exp_max; - frac_clear(p); + if (unlikely(exp >= exp_max)) { + switch (fmt->exp_max_kind) { + case float_expmax_ieee: + flags |= float_flag_overflow; + if (get_float_rebias_overflow(s)) { + exp -= fmt->exp_re_bias; + } else if (overflow_norm) { + flags |= float_flag_inexact; + exp = exp_max - 1; + fracN(allones)(p); + p->frac_lo &= ~round_mask; + } else { + flags |= float_flag_inexact; + p->cls = float_class_inf; + exp = exp_max; + fracN(clear)(p); + } + break; + + case float_expmax_normal: + if (unlikely(exp > exp_max)) { + /* Overflow. Return the maximum normal. */ + flags = (fmt->overflow_raises_invalid ? float_flag_invalid + : float_flag_overflow | float_flag_inexact); + exp = exp_max; + fracN(allones)(p); + p->frac_lo &= ~round_mask; + } + break; + + case float_expmax_e4m3: + if (exp > exp_max || p->frac_hi > E4M3_NORMAL_FRAC_MAX) { + partsN(uncanon_e4m3_overflow)(p, s, fmt, overflow_norm); + exp = p->exp; + flags |= (float_flag_overflow | float_flag_inexact); + } + break; + + default: + g_assert_not_reached(); } } - frac_shr(p, frac_shift); - } else if (unlikely(s->rebias_underflow)) { + fracN(shr)(p, frac_shift); + } else if (unlikely(get_float_rebias_underflow(s))) { flags |= float_flag_underflow; exp += fmt->exp_re_bias; if (p->frac_lo & round_mask) { flags |= float_flag_inexact; - if (frac_addi(p, p, inc)) { - frac_shr(p, 1); + if (fracN(addi)(p, p, inc)) { + fracN(shr)(p, 1); p->frac_hi |= DECOMPOSED_IMPLICIT_BIT; exp++; } p->frac_lo &= ~round_mask; } - frac_shr(p, frac_shift); - } else if (s->flush_to_zero) { - flags |= float_flag_output_denormal; + fracN(shr)(p, frac_shift); + } else if (get_flush_to_zero(s) && get_ftz_before_rounding(s)) { + flags |= float_flag_output_denormal_flushed; p->cls = float_class_zero; exp = 0; - frac_clear(p); + fracN(clear)(p); } else { - bool is_tiny = s->tininess_before_rounding || exp < 0; + bool is_tiny = get_tininess_before_rounding(s) || exp < 0; + bool has_pseudo_denormals = + fmt->has_explicit_bit && (get_floatx80_behaviour(s) & floatx80_pseudo_denormal_valid); if (!is_tiny) { FloatPartsN discard; - is_tiny = !frac_addi(&discard, p, inc); + is_tiny = !fracN(addi)(&discard, p, inc); } - frac_shrjam(p, 1 - exp); + fracN(shrjam)(p, !has_pseudo_denormals - exp); if (p->frac_lo & round_mask) { /* Need to recompute round-to-even/round-to-odd. */ - switch (s->float_rounding_mode) { + switch (get_float_rounding_mode(s)) { case float_round_nearest_even: + case float_round_nearest_even_max: if (N > 64 && frac_lsb == 0) { inc = ((p->frac_hi & 1) || (p->frac_lo & round_mask) != frac_lsbm1 ? frac_lsbm1 : 0); } else { @@ -267,43 +437,76 @@ static void partsN(uncanon_normal)(FloatPartsN *p, float_status *s, const FloatF break; } flags |= float_flag_inexact; - frac_addi(p, p, inc); + fracN(addi)(p, p, inc); p->frac_lo &= ~round_mask; } - exp = (p->frac_hi & DECOMPOSED_IMPLICIT_BIT) != 0; - frac_shr(p, frac_shift); - - if (is_tiny && (flags & float_flag_inexact)) { - flags |= float_flag_underflow; - } - if (exp == 0 && frac_eqz(p)) { - p->cls = float_class_zero; + exp = (p->frac_hi & DECOMPOSED_IMPLICIT_BIT) && !has_pseudo_denormals; + fracN(shr)(p, frac_shift); + + if (is_tiny) { + if (get_flush_to_zero(s)) { + assert(!get_ftz_before_rounding(s)); + flags |= float_flag_output_denormal_flushed; + p->cls = float_class_zero; + exp = 0; + fracN(clear)(p); + } else if (flags & float_flag_inexact) { + flags |= float_flag_underflow; + } + if (exp == 0 && fracN(eqz)(p)) { + p->cls = float_class_zero; + } } } p->exp = exp; float_raise(flags, s); } -static void partsN(uncanon)(FloatPartsN *p, float_status *s, const FloatFmt *fmt) { - if (likely(p->cls == float_class_normal)) { - parts_uncanon_normal(p, s, fmt); +static void partsN(uncanon)(FloatPartsN *p, float_status *s, const FloatFmt *fmt, bool saturate) { + if (likely(is_anynorm(p->cls))) { + partsN(uncanon_normal)(p, s, fmt, saturate); } else { switch (p->cls) { case float_class_zero: p->exp = 0; - frac_clear(p); + fracN(clear)(p); return; case float_class_inf: - g_assert(!fmt->arm_althp); - p->exp = fmt->exp_max; - frac_clear(p); + switch (fmt->exp_max_kind) { + case float_expmax_ieee: + p->exp = fmt->exp_max; + fracN(clear)(p); + break; + case float_expmax_e4m3: + partsN(uncanon_e4m3_overflow)(p, s, fmt, saturate); + fracN(shr)(p, fmt->frac_shift); + break; + case float_expmax_normal: + default: + g_assert_not_reached(); + } return; case float_class_qnan: case float_class_snan: - g_assert(!fmt->arm_althp); p->exp = fmt->exp_max; - frac_shr(p, fmt->frac_shift); + switch (fmt->exp_max_kind) { + case float_expmax_e4m3: + /* + * There is only one NaN encoding for E4M3, and with a + * conversion from another format, the input NaN fraction + * may not apply. + */ + assert(N == 64); + p->frac_hi = E4M3_NAN_FRAC; + /* fall through */ + case float_expmax_ieee: + fracN(shr)(p, fmt->frac_shift); + break; + case float_expmax_normal: + default: + g_assert_not_reached(); + } return; default: break; @@ -318,14 +521,28 @@ static void partsN(uncanon)(FloatPartsN *p, float_status *s, const FloatFmt *fmt * according to the IEC/IEEE Standard for Binary Floating-Point * Arithmetic. */ -static FloatPartsN *partsN(addsub)(FloatPartsN *a, FloatPartsN *b, float_status *s, bool subtract) { - bool b_sign = b->sign ^ subtract; - int ab_mask = float_cmask(a->cls) | float_cmask(b->cls); +FloatPartsN partsN(addsub)(const FloatPartsN *a_orig, const FloatPartsN *b_orig, float_status *s, bool subtract) { + int ab_mask = float_cmask(a_orig->cls) | float_cmask(b_orig->cls); - if (a->sign != b_sign) { + if (unlikely(ab_mask & float_cmask_anynan)) { + return partsN(pick_nan)(a_orig, b_orig, s); + } + + /* + * For addition and subtraction, we will consume an + * input denormal unless the other input is a NaN. + */ + record_denormals_used(ab_mask, s); + + FloatPartsN a = *a_orig; + FloatPartsN b = *b_orig; + + b.sign ^= subtract; + + if (a.sign != b.sign) { /* Subtraction */ - if (likely(ab_mask == float_cmask_normal)) { - if (parts_sub_normal(a, b)) { + if (likely(cmask_is_only_normals(ab_mask))) { + if (partsN(sub_normal)(&a, &b)) { return a; } /* Subtract was exact, fall through to set sign. */ @@ -333,62 +550,46 @@ static FloatPartsN *partsN(addsub)(FloatPartsN *a, FloatPartsN *b, float_status } if (ab_mask == float_cmask_zero) { - a->sign = s->float_rounding_mode == float_round_down; + /* 0 - 0 */ + a.sign = get_float_rounding_mode(s) == float_round_down; return a; } - if (unlikely(ab_mask & float_cmask_anynan)) { - goto p_nan; - } - if (ab_mask & float_cmask_inf) { - if (a->cls != float_class_inf) { + if (a.cls != float_class_inf) { /* N - Inf */ - goto return_b; + return b; } - if (b->cls != float_class_inf) { + if (b.cls != float_class_inf) { /* Inf - N */ return a; } /* Inf - Inf */ float_raise(float_flag_invalid | float_flag_invalid_isi, s); - parts_default_nan(a, s); - return a; + return partsN(default_nan)(s); } } else { /* Addition */ - if (likely(ab_mask == float_cmask_normal)) { - parts_add_normal(a, b); + if (likely(cmask_is_only_normals(ab_mask))) { + partsN(add_normal)(&a, &b); return a; } if (ab_mask == float_cmask_zero) { + /* 0 + 0 */ return a; } - if (unlikely(ab_mask & float_cmask_anynan)) { - goto p_nan; - } - if (ab_mask & float_cmask_inf) { - a->cls = float_class_inf; + /* N + Inf or Inf + N */ + a.cls = float_class_inf; return a; } } - if (b->cls == float_class_zero) { - g_assert(a->cls == float_class_normal); - return a; - } - - g_assert(a->cls == float_class_zero); - g_assert(b->cls == float_class_normal); -return_b: - b->sign = b_sign; - return b; - -p_nan: - return parts_pick_nan(a, b, s); + /* 0 +/- N or N +/- 0 */ + assert((ab_mask & float_cmask_zero) && (ab_mask & float_cmask_anynorm)); + return b.cls == float_class_zero ? a : b; } /* @@ -396,48 +597,50 @@ p_nan: * `b'. The operation is performed according to the IEC/IEEE Standard * for Binary Floating-Point Arithmetic. */ -static FloatPartsN *partsN(mul)(FloatPartsN *a, FloatPartsN *b, float_status *s) { +FloatPartsN partsN(mul)(const FloatPartsN *a, const FloatPartsN *b, float_status *s) { int ab_mask = float_cmask(a->cls) | float_cmask(b->cls); bool sign = a->sign ^ b->sign; - if (likely(ab_mask == float_cmask_normal)) { + if (likely(cmask_is_only_normals(ab_mask))) { FloatPartsW tmp; + FloatPartsN r = { + .cls = float_class_normal, + .sign = sign, + .exp = a->exp + b->exp + 1, + }; + + record_denormals_used(ab_mask, s); - frac_mulw(&tmp, a, b); - frac_truncjam(a, &tmp); + fracN(mulw)(&tmp, a, b); + fracN(truncjam)(&r, &tmp); - a->exp += b->exp + 1; - if (!(a->frac_hi & DECOMPOSED_IMPLICIT_BIT)) { - frac_add(a, a, a); - a->exp -= 1; + if (!(r.frac_hi & DECOMPOSED_IMPLICIT_BIT)) { + fracN(add)(&r, &r, &r); + r.exp -= 1; } - a->sign = sign; - return a; + return r; } /* Inf * Zero == NaN */ if (unlikely(ab_mask == float_cmask_infzero)) { float_raise(float_flag_invalid | float_flag_invalid_imz, s); - parts_default_nan(a, s); - return a; + return partsN(default_nan)(s); } if (unlikely(ab_mask & float_cmask_anynan)) { - return parts_pick_nan(a, b, s); + return partsN(pick_nan)(a, b, s); } /* Multiply by 0 or Inf */ + record_denormals_used(ab_mask, s); + if (ab_mask & float_cmask_inf) { - a->cls = float_class_inf; - a->sign = sign; - return a; + return (FloatPartsN) {.cls = float_class_inf, .sign = sign}; } g_assert(ab_mask & float_cmask_zero); - a->cls = float_class_zero; - a->sign = sign; - return a; + return (FloatPartsN) {.cls = float_class_zero, .sign = sign}; } /* @@ -445,124 +648,112 @@ static FloatPartsN *partsN(mul)(FloatPartsN *a, FloatPartsN *b, float_status *s) * `b' then adding 'c', with no intermediate rounding step after the * multiplication. The operation is performed according to the * IEC/IEEE Standard for Binary Floating-Point Arithmetic 754-2008. - * The flags argument allows the caller to select negation of the - * addend, the intermediate product, or the final result. (The - * difference between this and having the caller do a separate - * negation is that negating externally will flip the sign bit on NaNs.) + * The flags argument allows the caller to select negation of the addend + * or the intermediate product. (The difference between this and having + * the caller do a separate negation is that negating externally will + * flip the sign bit on NaNs.) Note that float_muladd_negate_result + * is not applied here, and should be handled separately after rounding + * chooses the final sign of 0.0. * * Requires A and C extracted into a double-sized structure to provide the * extra space for the widening multiply. */ -static FloatPartsN *partsN(muladd)(FloatPartsN *a, FloatPartsN *b, FloatPartsN *c, int flags, float_status *s) { - int ab_mask, abc_mask; - FloatPartsW p_widen, c_widen; - - ab_mask = float_cmask(a->cls) | float_cmask(b->cls); - abc_mask = float_cmask(c->cls) | ab_mask; +FloatPartsN partsN(muladd)(const FloatPartsN *a, const FloatPartsN *b, const FloatPartsN *c, int flags, + float_status *s) { + int ab_mask = float_cmask(a->cls) | float_cmask(b->cls); + int c_mask = float_cmask(c->cls); + int abc_mask = ab_mask | c_mask; + bool c_sign = c->sign ^ !!(flags & float_muladd_negate_c); + bool p_sign = a->sign ^ b->sign ^ !!(flags & float_muladd_negate_product); /* - * It is implementation-defined whether the cases of (0,inf,qnan) - * and (inf,0,qnan) raise InvalidOperation or not (and what QNaN - * they return if they do), so we have to hand this information - * off to the target-specific pick-a-NaN routine. + * The "likely" case is A and B normal, so that the product is normal, + * and C normal or zero so that the result is normal. */ - if (unlikely(abc_mask & float_cmask_anynan)) { - return parts_pick_nan_muladd(a, b, c, s, ab_mask, abc_mask); - } - - if (flags & float_muladd_negate_c) { - c->sign ^= 1; - } - - /* Compute the sign of the product into A. */ - a->sign ^= b->sign; - if (flags & float_muladd_negate_product) { - a->sign ^= 1; - } - - if (unlikely(ab_mask != float_cmask_normal)) { - if (unlikely(ab_mask == float_cmask_infzero)) { - float_raise(float_flag_invalid | float_flag_invalid_imz, s); - goto d_nan; + int likely_mask = ab_mask | (c_mask & ~float_cmask_zero); + if (likely(cmask_is_only_normals(likely_mask))) { + record_denormals_used(abc_mask, s); + + /* Perform the multiplication step. */ + FloatPartsW p_widen = {.sign = p_sign, .exp = a->exp + b->exp + 1}; + fracN(mulw)(&p_widen, a, b); + if (!(p_widen.frac_hi & DECOMPOSED_IMPLICIT_BIT)) { + fracW(add)(&p_widen, &p_widen, &p_widen); + p_widen.exp -= 1; } - if (ab_mask & float_cmask_inf) { - if (c->cls == float_class_inf && a->sign != c->sign) { - float_raise(float_flag_invalid | float_flag_invalid_isi, s); - goto d_nan; - } - goto return_inf; - } + /* Perform the addition step. */ + if (!(c_mask & float_cmask_zero)) { + /* Zero-extend C to less significant bits. */ + FloatPartsW c_widen = {.sign = c_sign, .exp = c->exp}; + fracN(widen)(&c_widen, c); - g_assert(ab_mask & float_cmask_zero); - if (c->cls == float_class_normal) { - *a = *c; - goto return_normal; - } - if (c->cls == float_class_zero) { - if (a->sign != c->sign) { + if (p_sign == c_sign) { + partsW(add_normal)(&p_widen, &c_widen); + } else if (!partsW(sub_normal)(&p_widen, &c_widen)) { goto return_sub_zero; } - goto return_zero; } - g_assert(c->cls == float_class_inf); - } - if (unlikely(c->cls == float_class_inf)) { - a->sign = c->sign; - goto return_inf; + /* Narrow with sticky bit, for proper rounding later. */ + FloatPartsN r = { + .sign = p_widen.sign, + .exp = p_widen.exp, + .cls = float_class_normal, + }; + fracN(truncjam)(&r, &p_widen); + return r; } - /* Perform the multiplication step. */ - p_widen.sign = a->sign; - p_widen.exp = a->exp + b->exp + 1; - frac_mulw(&p_widen, a, b); - if (!(p_widen.frac_hi & DECOMPOSED_IMPLICIT_BIT)) { - frac_add(&p_widen, &p_widen, &p_widen); - p_widen.exp -= 1; + /* + * It is implementation-defined whether the cases of (0,inf,qnan) + * and (inf,0,qnan) raise InvalidOperation or not (and what QNaN + * they return if they do), so we have to hand this information + * off to the target-specific pick-a-NaN routine. + */ + if (unlikely(abc_mask & float_cmask_anynan)) { + return partsN(pick_nan_muladd)(a, b, c, s, ab_mask, abc_mask); } - /* Perform the addition step. */ - if (c->cls != float_class_zero) { - /* Zero-extend C to less significant bits. */ - frac_widen(&c_widen, c); - c_widen.exp = c->exp; + if (unlikely(ab_mask == float_cmask_infzero)) { + /* Inf * Zero == NaN */ + float_raise(float_flag_invalid | float_flag_invalid_imz, s); + goto d_nan; + } - if (a->sign == c->sign) { - parts_add_normal(&p_widen, &c_widen); - } else if (!parts_sub_normal(&p_widen, &c_widen)) { - goto return_sub_zero; + if (unlikely(ab_mask & float_cmask_inf)) { + if ((c_mask & float_cmask_inf) && p_sign != c_sign) { + /* Inf - Inf == NaN */ + float_raise(float_flag_invalid | float_flag_invalid_isi, s); + goto d_nan; } + /* Inf + C == Inf */ + record_denormals_used(abc_mask, s); + return (FloatPartsN) {.sign = p_sign, .cls = float_class_inf}; } + record_denormals_used(abc_mask, s); - /* Narrow with sticky bit, for proper rounding later. */ - frac_truncjam(a, &p_widen); - a->sign = p_widen.sign; - a->exp = p_widen.exp; + /* Only remaining cases are zero product or inf addend. */ + assert((ab_mask & float_cmask_zero) | (c_mask & float_cmask_inf)); -return_normal: - if (flags & float_muladd_halve_result) { - a->exp -= 1; - } -finish_sign: - if (flags & float_muladd_negate_result) { - a->sign ^= 1; + /* + * P + Inf == Inf, or + * 0 + C == C, + * except for 0 - 0, which needs special rounding, + * except for when we want to suppress this addition step. + */ + if (!(c_mask & float_cmask_zero) || p_sign == c_sign || (flags & float_muladd_suppress_add_product_zero)) { + FloatPartsN r = *c; + r.sign = c_sign; + return r; } - return a; return_sub_zero: - a->sign = s->float_rounding_mode == float_round_down; -return_zero: - a->cls = float_class_zero; - goto finish_sign; - -return_inf: - a->cls = float_class_inf; - goto finish_sign; + /* 0 - 0 == -0 for round_down, +0 otherwise. */ + return (FloatPartsN) {.sign = get_float_rounding_mode(s) == float_round_down, .cls = float_class_zero}; d_nan: - parts_default_nan(a, s); - return a; + return partsN(default_nan)(s); } /* @@ -570,58 +761,59 @@ d_nan: * corresponding value `b'. The operation is performed according to * the IEC/IEEE Standard for Binary Floating-Point Arithmetic. */ -static FloatPartsN *partsN(div)(FloatPartsN *a, FloatPartsN *b, float_status *s) { +FloatPartsN partsN(div)(const FloatPartsN *a, const FloatPartsN *b, float_status *s) { int ab_mask = float_cmask(a->cls) | float_cmask(b->cls); - bool sign = a->sign ^ b->sign; + FloatPartsN r = *a; - if (likely(ab_mask == float_cmask_normal)) { - a->sign = sign; - a->exp -= b->exp + frac_div(a, b); - return a; + r.sign ^= b->sign; + r.exp -= b->exp; + + if (likely(cmask_is_only_normals(ab_mask))) { + record_denormals_used(ab_mask, s); + r.exp -= fracN(div)(&r, b); + return r; } /* 0/0 or Inf/Inf => NaN */ if (unlikely(ab_mask == float_cmask_zero)) { float_raise(float_flag_invalid | float_flag_invalid_zdz, s); - goto d_nan; + return partsN(default_nan)(s); } if (unlikely(ab_mask == float_cmask_inf)) { float_raise(float_flag_invalid | float_flag_invalid_idi, s); - goto d_nan; + return partsN(default_nan)(s); } /* All the NaN cases */ if (unlikely(ab_mask & float_cmask_anynan)) { - return parts_pick_nan(a, b, s); + return partsN(pick_nan)(a, b, s); } - a->sign = sign; + if (b->cls != float_class_zero) { + record_denormals_used(ab_mask, s); + } /* Inf / X */ - if (a->cls == float_class_inf) { - return a; + if (r.cls == float_class_inf) { + return r; } /* 0 / X */ - if (a->cls == float_class_zero) { - return a; + if (r.cls == float_class_zero) { + return r; } /* X / Inf */ if (b->cls == float_class_inf) { - a->cls = float_class_zero; - return a; + r.cls = float_class_zero; + return r; } /* X / 0 => Inf */ - g_assert(b->cls == float_class_zero); + assert(b->cls == float_class_zero); float_raise(float_flag_divbyzero, s); - a->cls = float_class_inf; - return a; - -d_nan: - parts_default_nan(a, s); - return a; + r.cls = float_class_inf; + return r; } /* @@ -630,8 +822,9 @@ d_nan: static FloatPartsN *partsN(modrem)(FloatPartsN *a, FloatPartsN *b, uint64_t *mod_quot, float_status *s) { int ab_mask = float_cmask(a->cls) | float_cmask(b->cls); - if (likely(ab_mask == float_cmask_normal)) { - frac_modrem(a, b, mod_quot); + if (likely(cmask_is_only_normals(ab_mask))) { + record_denormals_used(ab_mask, s); + fracN(modrem)(a, b, mod_quot); return a; } @@ -641,16 +834,19 @@ static FloatPartsN *partsN(modrem)(FloatPartsN *a, FloatPartsN *b, uint64_t *mod /* All the NaN cases */ if (unlikely(ab_mask & float_cmask_anynan)) { - return parts_pick_nan(a, b, s); + *a = partsN(pick_nan)(a, b, s); + return a; } /* Inf % N; N % 0 */ if (a->cls == float_class_inf || b->cls == float_class_zero) { float_raise(float_flag_invalid, s); - parts_default_nan(a, s); + *a = partsN(default_nan)(s); return a; } + record_denormals_used(ab_mask, s); + /* N % Inf; 0 % N */ g_assert(b->cls == float_class_inf || a->cls == float_class_zero); return a; @@ -678,9 +874,15 @@ static void partsN(sqrt)(FloatPartsN *a, float_status *status, const FloatFmt *f if (unlikely(a->cls != float_class_normal)) { switch (a->cls) { + case float_class_denormal: + if (!a->sign) { + /* -ve denormal will be InvalidOperation */ + float_raise(float_flag_input_denormal_used, status); + } + break; case float_class_snan: case float_class_qnan: - parts_return_nan(a, status); + *a = partsN(return_nan)(a, status); return; case float_class_zero: return; @@ -708,7 +910,7 @@ static void partsN(sqrt)(FloatPartsN *a, float_status *status, const FloatFmt *f exp_odd = a->exp & 1; index = extract64(a->frac_hi, 57, 6) | (!exp_odd << 6); if (!exp_odd) { - frac_shr(a, 1); + fracN(shr)(a, 1); } /* @@ -849,7 +1051,7 @@ done: /* Convert back from base 4 to base 2. */ a->exp >>= 1; if (!(a->frac_hi & DECOMPOSED_IMPLICIT_BIT)) { - frac_add(a, a, a); + fracN(add)(a, a, a); } else { a->exp += 1; } @@ -857,7 +1059,7 @@ done: d_nan: float_raise(float_flag_invalid | float_flag_invalid_sqrt, status); - parts_default_nan(a, status); + *a = partsN(default_nan)(status); } /* @@ -866,7 +1068,7 @@ d_nan: * according to the IEC/IEEE Standard for Binary Floating-Point * Arithmetic. * - * parts_round_to_int_normal is an internal helper function for + * partsN(round_to_int_normal) is an internal helper function for * normal numbers only, returning true for inexact but not directly * raising float_flag_inexact. */ @@ -874,8 +1076,7 @@ static bool partsN(round_to_int_normal)(FloatPartsN *a, FloatRoundMode rmode, in uint64_t frac_lsb, frac_lsbm1, rnd_even_mask, rnd_mask, inc; int shift_adj; - scale = MIN(MAX(scale, -0x10000), 0x10000); - a->exp += scale; + a->exp = exp_scalbn(a->exp, scale); if (a->exp < 0) { bool one; @@ -883,13 +1084,14 @@ static bool partsN(round_to_int_normal)(FloatPartsN *a, FloatRoundMode rmode, in /* All fractional */ switch (rmode) { case float_round_nearest_even: + case float_round_nearest_even_max: one = false; if (a->exp == -1) { FloatPartsN tmp; /* Shift left one, discarding DECOMPOSED_IMPLICIT_BIT */ - frac_add(&tmp, a, a); + fracN(add)(&tmp, a, a); /* Anything remaining means frac > 0.5. */ - one = !frac_eqz(&tmp); + one = !fracN(eqz)(&tmp); } break; case float_round_ties_away: @@ -905,13 +1107,14 @@ static bool partsN(round_to_int_normal)(FloatPartsN *a, FloatRoundMode rmode, in one = a->sign; break; case float_round_to_odd: + case float_round_to_odd_inf: one = true; break; default: g_assert_not_reached(); } - frac_clear(a); + fracN(clear)(a); a->exp = 0; if (one) { a->frac_hi = DECOMPOSED_IMPLICIT_BIT; @@ -921,22 +1124,22 @@ static bool partsN(round_to_int_normal)(FloatPartsN *a, FloatRoundMode rmode, in return true; } - if (a->exp >= frac_size) { - /* All integral */ - return false; - } - if (N > 64 && a->exp < N - 64) { /* * Rounding is not in the low word -- shift lsb to bit 2, * which leaves room for sticky and rounding bit. */ shift_adj = (N - 1) - (a->exp + 2); - frac_shrjam(a, shift_adj); + fracN(shrjam)(a, shift_adj); frac_lsb = 1 << 2; } else { + /* + * Rounding is in the low word -- compute the lsb offset for rounding + * and for clamping to the target precision, then map it to an offset + * within frac_lo. + */ shift_adj = 0; - frac_lsb = DECOMPOSED_IMPLICIT_BIT >> (a->exp & 63); + frac_lsb = DECOMPOSED_IMPLICIT_BIT >> (MIN(a->exp, frac_size) & 63); } frac_lsbm1 = frac_lsb >> 1; @@ -945,12 +1148,13 @@ static bool partsN(round_to_int_normal)(FloatPartsN *a, FloatRoundMode rmode, in if (!(a->frac_lo & rnd_mask)) { /* Fractional bits already clear, undo the shift above. */ - frac_shl(a, shift_adj); + fracN(shl)(a, shift_adj); return false; } switch (rmode) { case float_round_nearest_even: + case float_round_nearest_even_max: inc = ((a->frac_lo & rnd_even_mask) != frac_lsbm1 ? frac_lsbm1 : 0); break; case float_round_ties_away: @@ -966,6 +1170,7 @@ static bool partsN(round_to_int_normal)(FloatPartsN *a, FloatRoundMode rmode, in inc = a->sign ? rnd_mask : 0; break; case float_round_to_odd: + case float_round_to_odd_inf: inc = a->frac_lo & frac_lsb ? 0 : rnd_mask; break; default: @@ -973,41 +1178,43 @@ static bool partsN(round_to_int_normal)(FloatPartsN *a, FloatRoundMode rmode, in } if (shift_adj == 0) { - if (frac_addi(a, a, inc)) { - frac_shr(a, 1); + if (fracN(addi)(a, a, inc)) { + fracN(shr)(a, 1); a->frac_hi |= DECOMPOSED_IMPLICIT_BIT; a->exp++; } a->frac_lo &= ~rnd_mask; } else { - frac_addi(a, a, inc); + fracN(addi)(a, a, inc); a->frac_lo &= ~rnd_mask; /* Be careful shifting back, not to overflow */ - frac_shl(a, shift_adj - 1); + fracN(shl)(a, shift_adj - 1); if (a->frac_hi & DECOMPOSED_IMPLICIT_BIT) { a->exp++; } else { - frac_add(a, a, a); + fracN(add)(a, a, a); } } return true; } -static void partsN(round_to_int)(FloatPartsN *a, FloatRoundMode rmode, int scale, float_status *s, +FloatPartsN partsN(round_to_int)(const FloatPartsN *a, FloatRoundMode rmode, int scale, float_status *s, const FloatFmt *fmt) { switch (a->cls) { case float_class_qnan: case float_class_snan: - parts_return_nan(a, s); - break; + return partsN(return_nan)(a, s); case float_class_zero: case float_class_inf: - break; + return *a; case float_class_normal: - if (parts_round_to_int_normal(a, rmode, scale, fmt->frac_size)) { + case float_class_denormal: { + FloatPartsN r = *a; + if (partsN(round_to_int_normal)(&r, rmode, scale, fmt->frac_size)) { float_raise(float_flag_inexact, s); } - break; + return r; + } default: g_assert_not_reached(); } @@ -1025,7 +1232,7 @@ static void partsN(round_to_int)(FloatPartsN *a, FloatRoundMode rmode, int scale */ static int64_t partsN(float_to_sint)(FloatPartsN *p, FloatRoundMode rmode, int scale, int64_t min, int64_t max, float_status *s) { - int flags = 0; + FloatExceptionFlags flags = 0; uint64_t r; switch (p->cls) { @@ -1046,8 +1253,9 @@ static int64_t partsN(float_to_sint)(FloatPartsN *p, FloatRoundMode rmode, int s return 0; case float_class_normal: + case float_class_denormal: /* TODO: N - 2 is frac_size for rounding; could use input fmt. */ - if (parts_round_to_int_normal(p, rmode, scale, N - 2)) { + if (partsN(round_to_int_normal)(p, rmode, scale, N - 2)) { flags = float_flag_inexact; } @@ -1090,7 +1298,7 @@ static int64_t partsN(float_to_sint)(FloatPartsN *p, FloatRoundMode rmode, int s * flag. */ static uint64_t partsN(float_to_uint)(FloatPartsN *p, FloatRoundMode rmode, int scale, uint64_t max, float_status *s) { - int flags = 0; + FloatExceptionFlags flags = 0; uint64_t r; switch (p->cls) { @@ -1111,8 +1319,9 @@ static uint64_t partsN(float_to_uint)(FloatPartsN *p, FloatRoundMode rmode, int return 0; case float_class_normal: + case float_class_denormal: /* TODO: N - 2 is frac_size for rounding; could use input fmt. */ - if (parts_round_to_int_normal(p, rmode, scale, N - 2)) { + if (partsN(round_to_int_normal)(p, rmode, scale, N - 2)) { flags = float_flag_inexact; if (p->cls == float_class_zero) { r = 0; @@ -1143,81 +1352,6 @@ static uint64_t partsN(float_to_uint)(FloatPartsN *p, FloatRoundMode rmode, int return r; } -/* - * Like partsN(float_to_sint), except do not saturate the result. - * Instead, return the rounded unbounded precision two's compliment result, - * modulo 2**(bitsm1 + 1). - */ -static int64_t partsN(float_to_sint_modulo)(FloatPartsN *p, FloatRoundMode rmode, int bitsm1, float_status *s) { - int flags = 0; - uint64_t r; - bool overflow = false; - - switch (p->cls) { - case float_class_snan: - flags |= float_flag_invalid_snan; - /* fall through */ - case float_class_qnan: - flags |= float_flag_invalid; - r = 0; - break; - - case float_class_inf: - overflow = true; - r = 0; - break; - - case float_class_zero: - return 0; - - case float_class_normal: - /* TODO: N - 2 is frac_size for rounding; could use input fmt. */ - if (parts_round_to_int_normal(p, rmode, 0, N - 2)) { - flags = float_flag_inexact; - } - - if (p->exp <= DECOMPOSED_BINARY_POINT) { - /* - * Because we rounded to integral, and exp < 64, - * we know frac_low is zero. - */ - r = p->frac_hi >> (DECOMPOSED_BINARY_POINT - p->exp); - if (p->exp < bitsm1) { - /* Result in range. */ - } else if (p->exp == bitsm1) { - /* The only in-range value is INT_MIN. */ - overflow = !p->sign || p->frac_hi != DECOMPOSED_IMPLICIT_BIT; - } else { - overflow = true; - } - } else { - /* Overflow, but there might still be bits to return. */ - int shl = p->exp - DECOMPOSED_BINARY_POINT; - if (shl < N) { - frac_shl(p, shl); - r = p->frac_hi; - } else { - r = 0; - } - overflow = true; - } - - if (p->sign) { - r = -r; - } - break; - - default: - g_assert_not_reached(); - } - - if (overflow) { - flags = float_flag_invalid | float_flag_invalid_cvti; - } - float_raise(flags, s); - return r; -} - /* * Integer to float conversions * @@ -1283,8 +1417,9 @@ static FloatPartsN *partsN(minmax)(FloatPartsN *a, FloatPartsN *b, float_status * if one operand is a QNaN, and the other * operand is numerical, then return numerical argument. */ - if ((flags & (minmax_isnum | minmax_isnumber)) && !(ab_mask & float_cmask_snan) && + if ((flags & (float_minmax_isnum | float_minmax_isnumber)) && !(ab_mask & float_cmask_snan) && (ab_mask & ~float_cmask_qnan)) { + record_denormals_used(ab_mask, s); return is_nan(a->cls) ? b : a; } @@ -1299,20 +1434,24 @@ static FloatPartsN *partsN(minmax)(FloatPartsN *a, FloatPartsN *b, float_status * but unless both operands are NaNs, * the SNaN is otherwise ignored and not converted to a QNaN. */ - if ((flags & minmax_isnumber) && (ab_mask & float_cmask_snan) && (ab_mask & ~float_cmask_anynan)) { + if ((flags & float_minmax_isnumber) && (ab_mask & float_cmask_snan) && (ab_mask & ~float_cmask_anynan)) { float_raise(float_flag_invalid, s); return is_nan(a->cls) ? b : a; } - return parts_pick_nan(a, b, s); + *a = partsN(pick_nan)(a, b, s); + return a; } + record_denormals_used(ab_mask, s); + a_exp = a->exp; b_exp = b->exp; - if (unlikely(ab_mask != float_cmask_normal)) { + if (unlikely(!cmask_is_only_normals(ab_mask))) { switch (a->cls) { case float_class_normal: + case float_class_denormal: break; case float_class_inf: a_exp = INT16_MAX; @@ -1322,10 +1461,10 @@ static FloatPartsN *partsN(minmax)(FloatPartsN *a, FloatPartsN *b, float_status break; default: g_assert_not_reached(); - break; } switch (b->cls) { case float_class_normal: + case float_class_denormal: break; case float_class_inf: b_exp = INT16_MAX; @@ -1335,21 +1474,20 @@ static FloatPartsN *partsN(minmax)(FloatPartsN *a, FloatPartsN *b, float_status break; default: g_assert_not_reached(); - break; } } /* Compare magnitudes. */ cmp = a_exp - b_exp; if (cmp == 0) { - cmp = frac_cmp(a, b); + cmp = fracN(cmp)(a, b); } /* * Take the sign into account. * For ismag, only do this if the magnitudes are equal. */ - if (!(flags & minmax_ismag) || cmp == 0) { + if (!(flags & float_minmax_ismag) || cmp == 0) { if (a->sign != b->sign) { /* For differing signs, the negative operand is less. */ cmp = a->sign ? -1 : 1; @@ -1359,7 +1497,7 @@ static FloatPartsN *partsN(minmax)(FloatPartsN *a, FloatPartsN *b, float_status } } - if (flags & minmax_ismin) { + if (flags & float_minmax_ismin) { cmp = -cmp; } return cmp < 0 ? b : a; @@ -1368,17 +1506,19 @@ static FloatPartsN *partsN(minmax)(FloatPartsN *a, FloatPartsN *b, float_status /* * Floating point compare */ -static FloatRelation partsN(compare)(FloatPartsN *a, FloatPartsN *b, float_status *s, bool is_quiet) { +FloatRelation partsN(compare)(const FloatPartsN *a, const FloatPartsN *b, float_status *s, bool is_quiet) { int ab_mask = float_cmask(a->cls) | float_cmask(b->cls); - if (likely(ab_mask == float_cmask_normal)) { + if (likely(cmask_is_only_normals(ab_mask))) { FloatRelation cmp; + record_denormals_used(ab_mask, s); + if (a->sign != b->sign) { goto a_sign; } if (a->exp == b->exp) { - cmp = frac_cmp(a, b); + cmp = fracN(cmp)(a, b); } else if (a->exp < b->exp) { cmp = float_relation_less; } else { @@ -1399,6 +1539,8 @@ static FloatRelation partsN(compare)(FloatPartsN *a, FloatPartsN *b, float_statu return float_relation_unordered; } + record_denormals_used(ab_mask, s); + if (ab_mask & float_cmask_zero) { if (ab_mask == float_cmask_zero) { return float_relation_equal; @@ -1428,144 +1570,23 @@ b_sign: /* * Multiply A by 2 raised to the power N. */ -static void partsN(scalbn)(FloatPartsN *a, int n, float_status *s) { +FloatPartsN partsN(scalbn)(const FloatPartsN *a, int n, float_status *s) { switch (a->cls) { case float_class_snan: case float_class_qnan: - parts_return_nan(a, s); - break; + return partsN(return_nan)(a, s); case float_class_zero: case float_class_inf: - break; - case float_class_normal: - a->exp += MIN(MAX(n, -0x10000), 0x10000); - break; + return *a; + case float_class_denormal: + float_raise(float_flag_input_denormal_used, s); + /* fall through */ + case float_class_normal: { + FloatPartsN r = *a; + r.exp = exp_scalbn(r.exp, n); + return r; + } default: g_assert_not_reached(); } } - -/* - * Return log2(A) - */ -static void partsN(log2)(FloatPartsN *a, float_status *s, const FloatFmt *fmt) { - uint64_t a0, a1, r, t, ign; - FloatPartsN f; - int i, n, a_exp, f_exp; - - if (unlikely(a->cls != float_class_normal)) { - switch (a->cls) { - case float_class_snan: - case float_class_qnan: - parts_return_nan(a, s); - return; - case float_class_zero: - float_raise(float_flag_divbyzero, s); - /* log2(0) = -inf */ - a->cls = float_class_inf; - a->sign = 1; - return; - case float_class_inf: - if (unlikely(a->sign)) { - goto d_nan; - } - return; - default: - break; - } - g_assert_not_reached(); - } - if (unlikely(a->sign)) { - goto d_nan; - } - - /* TODO: This algorithm looses bits too quickly for float128. */ - g_assert(N == 64); - - a_exp = a->exp; - f_exp = -1; - - r = 0; - t = DECOMPOSED_IMPLICIT_BIT; - a0 = a->frac_hi; - a1 = 0; - - n = fmt->frac_size + 2; - if (unlikely(a_exp == -1)) { - /* - * When a_exp == -1, we're computing the log2 of a value [0.5,1.0). - * When the value is very close to 1.0, there are lots of 1's in - * the msb parts of the fraction. At the end, when we subtract - * this value from -1.0, we can see a catastrophic loss of precision, - * as 0x800..000 - 0x7ff..ffx becomes 0x000..00y, leaving only the - * bits of y in the final result. To minimize this, compute as many - * digits as we can. - * ??? This case needs another algorithm to avoid this. - */ - n = fmt->frac_size * 2 + 2; - /* Don't compute a value overlapping the sticky bit */ - n = MIN(n, 62); - } - - for (i = 0; i < n; i++) { - if (a1) { - mul128To256(a0, a1, a0, a1, &a0, &a1, &ign, &ign); - } else if (a0 & 0xffffffffull) { - mul64To128(a0, a0, &a0, &a1); - } else if (a0 & ~DECOMPOSED_IMPLICIT_BIT) { - a0 >>= 32; - a0 *= a0; - } else { - goto exact; - } - - if (a0 & DECOMPOSED_IMPLICIT_BIT) { - if (unlikely(a_exp == 0 && r == 0)) { - /* - * When a_exp == 0, we're computing the log2 of a value - * [1.0,2.0). When the value is very close to 1.0, there - * are lots of 0's in the msb parts of the fraction. - * We need to compute more digits to produce a correct - * result -- restart at the top of the fraction. - * ??? This is likely to lose precision quickly, as for - * float128; we may need another method. - */ - f_exp -= i; - t = r = DECOMPOSED_IMPLICIT_BIT; - i = 0; - } else { - r |= t; - } - } else { - add128(a0, a1, a0, a1, &a0, &a1); - } - t >>= 1; - } - - /* Set sticky for inexact. */ - r |= (a1 || a0 & ~DECOMPOSED_IMPLICIT_BIT); - -exact: - parts_sint_to_float(a, a_exp, 0, s); - if (r == 0) { - return; - } - - memset(&f, 0, sizeof(f)); - f.cls = float_class_normal; - f.frac_hi = r; - f.exp = f_exp - frac_normalize(&f); - - if (a_exp < 0) { - parts_sub_normal(a, &f); - } else if (a_exp > 0) { - parts_add_normal(a, &f); - } else { - *a = f; - } - return; - -d_nan: - float_raise(float_flag_invalid, s); - parts_default_nan(a, s); -} diff --git a/libtcg/src/fpu/softfloat-specialize.c.inc b/libtcg/src/fpu/softfloat-specialize.c.inc index 0b368cc18..088b668d6 100644 --- a/libtcg/src/fpu/softfloat-specialize.c.inc +++ b/libtcg/src/fpu/softfloat-specialize.c.inc @@ -79,33 +79,28 @@ this code that are retained. * version 2 or later. See the COPYING file in the top-level directory. */ -/* - * Define whether architecture deviates from IEEE in not supporting - * signaling NaNs (so all NaNs are treated as quiet). - */ -static inline bool no_signaling_nans(float_status *status) { -#if defined(TARGET_XTENSA) - return status->no_signaling_nans; -#else - return false; -#endif -} - -/* Define how the architecture discriminates signaling NaNs. - * This done with the most significant bit of the fraction. - * In IEEE 754-1985 this was implementation defined, but in IEEE 754-2008 - * the msb must be zero. MIPS is (so far) unique in supporting both the - * 2008 revision and backward compatibility with their original choice. - * Thus for MIPS we must make the choice at runtime. - */ -static inline bool snan_bit_is_one(float_status *status) { -#if defined(TARGET_MIPS) - return status->snan_bit_is_one; -#elif defined(TARGET_HPPA) || defined(TARGET_SH4) - return 1; -#else - return 0; -#endif +static inline bool get_tininess_before_rounding(const float_status *status) { + return status->tininess_before_rounding; +} + +static inline bool get_ftz_before_rounding(const float_status *status) { + return status->ftz_before_rounding; +} + +static inline uint8_t get_float_default_nan_pattern(const float_status *status) { + return status->default_nan_pattern; +} + +static inline bool get_float_rebias_overflow(const float_status *status) { + return status->rebias_overflow; +} + +static inline bool get_float_rebias_underflow(const float_status *status) { + return status->rebias_underflow; +} + +static inline bool get_float_e4m3_nan_is_snan(const float_status *status) { + return status->e4m3_nan_is_snan; } /*---------------------------------------------------------------------------- @@ -113,64 +108,54 @@ static inline bool snan_bit_is_one(float_status *status) { | if the fraction represents a signalling NaN; otherwise false. *----------------------------------------------------------------------------*/ -static bool parts_is_snan_frac(uint64_t frac, float_status *status) { - if (no_signaling_nans(status)) { - return false; - } else { - bool msb = extract64(frac, DECOMPOSED_BINARY_POINT - 1, 1); - return msb == snan_bit_is_one(status); +static bool frac_msb_is_snan(bool msb, float_status *status) { + switch (get_snan_rule(status)) { + case float_snan_never: + return false; + case float_snan_bit_is_one: + return msb; + case float_snan_bit_is_zero: + return !msb; } + g_assert_not_reached(); +} + +static bool parts_is_snan_frac(uint64_t frac, float_status *status) { + bool msb = extract64(frac, DECOMPOSED_BINARY_POINT - 1, 1); + return frac_msb_is_snan(msb, status); } /*---------------------------------------------------------------------------- | The pattern for a default generated deconstructed floating-point NaN. *----------------------------------------------------------------------------*/ -static void parts64_default_nan(FloatParts64 *p, float_status *status) { +FloatParts64 parts64_default_nan(float_status *status) { bool sign = 0; uint64_t frac; + uint8_t dnan_pattern = get_float_default_nan_pattern(status); -#if defined(TARGET_SPARC) || defined(TARGET_M68K) - /* !snan_bit_is_one, set all bits */ - frac = (1ULL << DECOMPOSED_BINARY_POINT) - 1; -#elif defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_MICROBLAZE) - /* !snan_bit_is_one, set sign and msb */ - frac = 1ULL << (DECOMPOSED_BINARY_POINT - 1); - sign = 1; -#elif defined(TARGET_HPPA) - /* snan_bit_is_one, set msb-1. */ - frac = 1ULL << (DECOMPOSED_BINARY_POINT - 2); -#elif defined(TARGET_HEXAGON) - sign = 1; - frac = ~0ULL; -#else + assert(dnan_pattern != 0); + + sign = dnan_pattern >> 7; /* - * This case is true for Alpha, ARM, MIPS, OpenRISC, PPC, RISC-V, - * S390, SH4, TriCore, and Xtensa. Our other supported targets, - * CRIS, Nios2, and Tile, do not have floating-point. + * Place default_nan_pattern [6:0] into bits [62:56], + * and replecate bit [0] down into [55:0] */ - if (snan_bit_is_one(status)) { - /* set all bits other than msb */ - frac = (1ULL << (DECOMPOSED_BINARY_POINT - 1)) - 1; - } else { - /* set msb */ - frac = 1ULL << (DECOMPOSED_BINARY_POINT - 1); - } -#endif + frac = deposit64(0, DECOMPOSED_BINARY_POINT - 7, 7, dnan_pattern); + frac = deposit64(frac, 0, DECOMPOSED_BINARY_POINT - 7, -(dnan_pattern & 1)); - *p = (FloatParts64) {.cls = float_class_qnan, .sign = sign, .exp = INT_MAX, .frac = frac}; + return (FloatParts64) {.cls = float_class_qnan, .sign = sign, .exp = INT_MAX, .frac = frac}; } -static void parts128_default_nan(FloatParts128 *p, float_status *status) { +FloatParts128 parts128_default_nan(float_status *status) { /* * Extrapolate from the choices made by parts64_default_nan to fill * in the quad-floating format. If the low bit is set, assume we * want to set all non-snan bits. */ - FloatParts64 p64; - parts64_default_nan(&p64, status); + FloatParts64 p64 = parts64_default_nan(status); - *p = (FloatParts128) { + return (FloatParts128) { .cls = float_class_qnan, .sign = p64.sign, .exp = INT_MAX, .frac_hi = p64.frac, .frac_lo = -(p64.frac & 1)}; } @@ -180,59 +165,76 @@ static void parts128_default_nan(FloatParts128 *p, float_status *status) { *----------------------------------------------------------------------------*/ static uint64_t parts_silence_nan_frac(uint64_t frac, float_status *status) { - g_assert(!no_signaling_nans(status)); - - /* The only snan_bit_is_one target without default_nan_mode is HPPA. */ - if (snan_bit_is_one(status)) { - frac &= ~(1ULL << (DECOMPOSED_BINARY_POINT - 1)); - frac |= 1ULL << (DECOMPOSED_BINARY_POINT - 2); - } else { - frac |= 1ULL << (DECOMPOSED_BINARY_POINT - 1); + switch (get_snan_rule(status)) { + case float_snan_bit_is_zero: + frac |= 1ULL << (DECOMPOSED_BINARY_POINT - 1); + break; + case float_snan_bit_is_one: + /* The only snan_bit_is_one target without default_nan_mode is HPPA. */ + frac &= ~(1ULL << (DECOMPOSED_BINARY_POINT - 1)); + frac |= 1ULL << (DECOMPOSED_BINARY_POINT - 2); + break; + case float_snan_never: + default: + g_assert_not_reached(); } return frac; } -static void parts64_silence_nan(FloatParts64 *p, float_status *status) { - p->frac = parts_silence_nan_frac(p->frac, status); - p->cls = float_class_qnan; +static FloatParts64 parts64_silence_nan(const FloatParts64 *p, float_status *status) { + FloatParts64 r = *p; + + r.frac = parts_silence_nan_frac(r.frac, status); + r.cls = float_class_qnan; + return r; } -static void parts128_silence_nan(FloatParts128 *p, float_status *status) { - p->frac_hi = parts_silence_nan_frac(p->frac_hi, status); - p->cls = float_class_qnan; +static FloatParts128 parts128_silence_nan(const FloatParts128 *p, float_status *status) { + FloatParts128 r = *p; + + r.frac_hi = parts_silence_nan_frac(r.frac_hi, status); + r.cls = float_class_qnan; + return r; } /*---------------------------------------------------------------------------- | The pattern for a default generated extended double-precision NaN. *----------------------------------------------------------------------------*/ floatx80 floatx80_default_nan(float_status *status) { - floatx80 r; + /* + * Extrapolate from the choices made by parts64_default_nan to fill + * in the floatx80 format. We assume that floatx80's explicit + * integer bit is always set (this is true for i386 and m68k, + * which are the only real users of this format). + */ + FloatParts64 p64 = parts64_default_nan(status); - /* None of the targets that have snan_bit_is_one use floatx80. */ - assert(!snan_bit_is_one(status)); -#if defined(TARGET_M68K) - r.low = UINT64_C(0xFFFFFFFFFFFFFFFF); - r.high = 0x7FFF; -#else - /* X86 */ - r.low = UINT64_C(0xC000000000000000); - r.high = 0xFFFF; -#endif - return r; + return (floatx80) { + .high = 0x7FFF | (p64.sign << 15), + .low = (1ULL << DECOMPOSED_BINARY_POINT) | p64.frac, + }; } /*---------------------------------------------------------------------------- | The pattern for a default generated extended double-precision inf. *----------------------------------------------------------------------------*/ -#define floatx80_infinity_high 0x7FFF -#if defined(TARGET_M68K) -#define floatx80_infinity_low UINT64_C(0x0000000000000000) -#else -#define floatx80_infinity_low UINT64_C(0x8000000000000000) -#endif +floatx80 floatx80_default_inf(bool zSign, float_status *status) { + /* + * Whether the Integer bit is set in the default Infinity is + * target dependent. + */ + bool z = get_floatx80_behaviour(status) & floatx80_default_inf_int_bit_is_zero; + return packFloatx80(zSign, 0x7fff, z ? 0 : (1ULL << 63)); +} + +/*---------------------------------------------------------------------------- +| Determine if a float16 NaN is signaling NaN. +*----------------------------------------------------------------------------*/ -const floatx80 floatx80_infinity = make_floatx80_init(floatx80_infinity_high, floatx80_infinity_low); +static bool float16_nan_is_snan(float16 a, float_status *status) { + return frac_msb_is_snan((a >> 9) & 1, status); +} /*---------------------------------------------------------------------------- | Returns 1 if the half-precision floating-point value `a' is a quiet @@ -240,397 +242,74 @@ const floatx80 floatx80_infinity = make_floatx80_init(floatx80_infinity_high, fl *----------------------------------------------------------------------------*/ bool float16_is_quiet_nan(float16 a_, float_status *status) { - if (no_signaling_nans(status)) { - return float16_is_any_nan(a_); - } else { - uint16_t a = float16_val(a_); - if (snan_bit_is_one(status)) { - return (((a >> 9) & 0x3F) == 0x3E) && (a & 0x1FF); - } else { - - return ((a >> 9) & 0x3F) == 0x3F; - } - } + return float16_is_any_nan(a_) && !float16_nan_is_snan(a_, status); } /*---------------------------------------------------------------------------- -| Returns 1 if the bfloat16 value `a' is a quiet +| Returns 1 if the half-precision floating-point value `a' is a signaling | NaN; otherwise returns 0. *----------------------------------------------------------------------------*/ -bool bfloat16_is_quiet_nan(bfloat16 a_, float_status *status) { - if (no_signaling_nans(status)) { - return bfloat16_is_any_nan(a_); - } else { - uint16_t a = a_; - if (snan_bit_is_one(status)) { - return (((a >> 6) & 0x1FF) == 0x1FE) && (a & 0x3F); - } else { - return ((a >> 6) & 0x1FF) == 0x1FF; - } - } +bool float16_is_signaling_nan(float16 a_, float_status *status) { + return float16_is_any_nan(a_) && float16_nan_is_snan(a_, status); } /*---------------------------------------------------------------------------- -| Returns 1 if the half-precision floating-point value `a' is a signaling -| NaN; otherwise returns 0. +| Determine if a bfloat16 NaN is signaling NaN. *----------------------------------------------------------------------------*/ -bool float16_is_signaling_nan(float16 a_, float_status *status) { - if (no_signaling_nans(status)) { - return 0; - } else { - uint16_t a = float16_val(a_); - if (snan_bit_is_one(status)) { - return ((a >> 9) & 0x3F) == 0x3F; - } else { - return (((a >> 9) & 0x3F) == 0x3E) && (a & 0x1FF); - } - } +static bool bfloat16_nan_is_snan(bfloat16 a, float_status *status) { + return frac_msb_is_snan((a >> 6) & 1, status); } /*---------------------------------------------------------------------------- -| Returns 1 if the bfloat16 value `a' is a signaling -| NaN; otherwise returns 0. +| Returns 1 if the bfloat16 value `a' is a quiet NaN; otherwise returns 0. +*----------------------------------------------------------------------------*/ + +bool bfloat16_is_quiet_nan(bfloat16 a_, float_status *status) { + return bfloat16_is_any_nan(a_) && !bfloat16_nan_is_snan(a_, status); +} + +/*---------------------------------------------------------------------------- +| Returns 1 if the bfloat16 value `a' is a signaling NaN; otherwise returns 0. *----------------------------------------------------------------------------*/ bool bfloat16_is_signaling_nan(bfloat16 a_, float_status *status) { - if (no_signaling_nans(status)) { - return 0; - } else { - uint16_t a = a_; - if (snan_bit_is_one(status)) { - return ((a >> 6) & 0x1FF) == 0x1FF; - } else { - return (((a >> 6) & 0x1FF) == 0x1FE) && (a & 0x3F); - } - } + return bfloat16_is_any_nan(a_) && bfloat16_nan_is_snan(a_, status); } /*---------------------------------------------------------------------------- -| Returns 1 if the single-precision floating-point value `a' is a quiet -| NaN; otherwise returns 0. +| Determine if a float32 NaN is signaling NaN. *----------------------------------------------------------------------------*/ -bool float32_is_quiet_nan(float32 a_, float_status *status) { - if (no_signaling_nans(status)) { - return float32_is_any_nan(a_); - } else { - uint32_t a = float32_val(a_); - if (snan_bit_is_one(status)) { - return (((a >> 22) & 0x1FF) == 0x1FE) && (a & 0x003FFFFF); - } else { - return ((uint32_t) (a << 1) >= 0xFF800000); - } - } +static bool float32_nan_is_snan(float32 a, float_status *status) { + return frac_msb_is_snan((a >> 22) & 1, status); } /*---------------------------------------------------------------------------- -| Returns 1 if the single-precision floating-point value `a' is a signaling +| Returns 1 if the single-precision floating-point value `a' is a quiet | NaN; otherwise returns 0. *----------------------------------------------------------------------------*/ -bool float32_is_signaling_nan(float32 a_, float_status *status) { - if (no_signaling_nans(status)) { - return 0; - } else { - uint32_t a = float32_val(a_); - if (snan_bit_is_one(status)) { - return ((uint32_t) (a << 1) >= 0xFF800000); - } else { - return (((a >> 22) & 0x1FF) == 0x1FE) && (a & 0x003FFFFF); - } - } +bool float32_is_quiet_nan(float32 a_, float_status *status) { + return float32_is_any_nan(a_) && !float32_nan_is_snan(a_, status); } /*---------------------------------------------------------------------------- -| Select which NaN to propagate for a two-input operation. -| IEEE754 doesn't specify all the details of this, so the -| algorithm is target-specific. -| The routine is passed various bits of information about the -| two NaNs and should return 0 to select NaN a and 1 for NaN b. -| Note that signalling NaNs are always squashed to quiet NaNs -| by the caller, by calling floatXX_silence_nan() before -| returning them. -| -| aIsLargerSignificand is only valid if both a and b are NaNs -| of some kind, and is true if a has the larger significand, -| or if both a and b have the same significand but a is -| positive but b is negative. It is only needed for the x87 -| tie-break rule. +| Returns 1 if the single-precision floating-point value `a' is a signaling +| NaN; otherwise returns 0. *----------------------------------------------------------------------------*/ -static int pickNaN(FloatClass a_cls, FloatClass b_cls, bool aIsLargerSignificand, float_status *status) { -#if defined(TARGET_ARM) || defined(TARGET_MIPS) || defined(TARGET_HPPA) || defined(TARGET_LOONGARCH64) || \ - defined(TARGET_S390X) - /* ARM mandated NaN propagation rules (see FPProcessNaNs()), take - * the first of: - * 1. A if it is signaling - * 2. B if it is signaling - * 3. A (quiet) - * 4. B (quiet) - * A signaling NaN is always quietened before returning it. - */ - /* According to MIPS specifications, if one of the two operands is - * a sNaN, a new qNaN has to be generated. This is done in - * floatXX_silence_nan(). For qNaN inputs the specifications - * says: "When possible, this QNaN result is one of the operand QNaN - * values." In practice it seems that most implementations choose - * the first operand if both operands are qNaN. In short this gives - * the following rules: - * 1. A if it is signaling - * 2. B if it is signaling - * 3. A (quiet) - * 4. B (quiet) - * A signaling NaN is always silenced before returning it. - */ - if (is_snan(a_cls)) { - return 0; - } else if (is_snan(b_cls)) { - return 1; - } else if (is_qnan(a_cls)) { - return 0; - } else { - return 1; - } -#elif defined(TARGET_PPC) || defined(TARGET_M68K) - /* PowerPC propagation rules: - * 1. A if it sNaN or qNaN - * 2. B if it sNaN or qNaN - * A signaling NaN is always silenced before returning it. - */ - /* M68000 FAMILY PROGRAMMER'S REFERENCE MANUAL - * 3.4 FLOATING-POINT INSTRUCTION DETAILS - * If either operand, but not both operands, of an operation is a - * nonsignaling NaN, then that NaN is returned as the result. If both - * operands are nonsignaling NaNs, then the destination operand - * nonsignaling NaN is returned as the result. - * If either operand to an operation is a signaling NaN (SNaN), then the - * SNaN bit is set in the FPSR EXC byte. If the SNaN exception enable bit - * is set in the FPCR ENABLE byte, then the exception is taken and the - * destination is not modified. If the SNaN exception enable bit is not - * set, setting the SNaN bit in the operand to a one converts the SNaN to - * a nonsignaling NaN. The operation then continues as described in the - * preceding paragraph for nonsignaling NaNs. - */ - if (is_nan(a_cls)) { - return 0; - } else { - return 1; - } -#elif defined(TARGET_XTENSA) - /* - * Xtensa has two NaN propagation modes. - * Which one is active is controlled by float_status::use_first_nan. - */ - if (status->use_first_nan) { - if (is_nan(a_cls)) { - return 0; - } else { - return 1; - } - } else { - if (is_nan(b_cls)) { - return 1; - } else { - return 0; - } - } -#else - /* This implements x87 NaN propagation rules: - * SNaN + QNaN => return the QNaN - * two SNaNs => return the one with the larger significand, silenced - * two QNaNs => return the one with the larger significand - * SNaN and a non-NaN => return the SNaN, silenced - * QNaN and a non-NaN => return the QNaN - * - * If we get down to comparing significands and they are the same, - * return the NaN with the positive sign bit (if any). - */ - if (is_snan(a_cls)) { - if (is_snan(b_cls)) { - return aIsLargerSignificand ? 0 : 1; - } - return is_qnan(b_cls) ? 1 : 0; - } else if (is_qnan(a_cls)) { - if (is_snan(b_cls) || !is_qnan(b_cls)) { - return 0; - } else { - return aIsLargerSignificand ? 0 : 1; - } - } else { - return 1; - } -#endif +bool float32_is_signaling_nan(float32 a_, float_status *status) { + return float32_is_any_nan(a_) && float32_nan_is_snan(a_, status); } /*---------------------------------------------------------------------------- -| Select which NaN to propagate for a three-input operation. -| For the moment we assume that no CPU needs the 'larger significand' -| information. -| Return values : 0 : a; 1 : b; 2 : c; 3 : default-NaN +| Determine if a float64 NaN is signaling NaN. *----------------------------------------------------------------------------*/ -static int pickNaNMulAdd(FloatClass a_cls, FloatClass b_cls, FloatClass c_cls, bool infzero, float_status *status) { -#if defined(TARGET_ARM) - /* For ARM, the (inf,zero,qnan) case sets InvalidOp and returns - * the default NaN - */ - if (infzero && is_qnan(c_cls)) { - float_raise(float_flag_invalid | float_flag_invalid_imz, status); - return 3; - } - - /* This looks different from the ARM ARM pseudocode, because the ARM ARM - * puts the operands to a fused mac operation (a*b)+c in the order c,a,b. - */ - if (is_snan(c_cls)) { - return 2; - } else if (is_snan(a_cls)) { - return 0; - } else if (is_snan(b_cls)) { - return 1; - } else if (is_qnan(c_cls)) { - return 2; - } else if (is_qnan(a_cls)) { - return 0; - } else { - return 1; - } -#elif defined(TARGET_MIPS) - if (snan_bit_is_one(status)) { - /* - * For MIPS systems that conform to IEEE754-1985, the (inf,zero,nan) - * case sets InvalidOp and returns the default NaN - */ - if (infzero) { - float_raise(float_flag_invalid | float_flag_invalid_imz, status); - return 3; - } - /* Prefer sNaN over qNaN, in the a, b, c order. */ - if (is_snan(a_cls)) { - return 0; - } else if (is_snan(b_cls)) { - return 1; - } else if (is_snan(c_cls)) { - return 2; - } else if (is_qnan(a_cls)) { - return 0; - } else if (is_qnan(b_cls)) { - return 1; - } else { - return 2; - } - } else { - /* - * For MIPS systems that conform to IEEE754-2008, the (inf,zero,nan) - * case sets InvalidOp and returns the input value 'c' - */ - if (infzero) { - float_raise(float_flag_invalid | float_flag_invalid_imz, status); - return 2; - } - /* Prefer sNaN over qNaN, in the c, a, b order. */ - if (is_snan(c_cls)) { - return 2; - } else if (is_snan(a_cls)) { - return 0; - } else if (is_snan(b_cls)) { - return 1; - } else if (is_qnan(c_cls)) { - return 2; - } else if (is_qnan(a_cls)) { - return 0; - } else { - return 1; - } - } -#elif defined(TARGET_LOONGARCH64) - /* - * For LoongArch systems that conform to IEEE754-2008, the (inf,zero,nan) - * case sets InvalidOp and returns the input value 'c' - */ - if (infzero) { - float_raise(float_flag_invalid | float_flag_invalid_imz, status); - return 2; - } - /* Prefer sNaN over qNaN, in the c, a, b order. */ - if (is_snan(c_cls)) { - return 2; - } else if (is_snan(a_cls)) { - return 0; - } else if (is_snan(b_cls)) { - return 1; - } else if (is_qnan(c_cls)) { - return 2; - } else if (is_qnan(a_cls)) { - return 0; - } else { - return 1; - } -#elif defined(TARGET_PPC) - /* For PPC, the (inf,zero,qnan) case sets InvalidOp, but we prefer - * to return an input NaN if we have one (ie c) rather than generating - * a default NaN - */ - if (infzero) { - float_raise(float_flag_invalid | float_flag_invalid_imz, status); - return 2; - } - /* If fRA is a NaN return it; otherwise if fRB is a NaN return it; - * otherwise return fRC. Note that muladd on PPC is (fRA * fRC) + frB - */ - if (is_nan(a_cls)) { - return 0; - } else if (is_nan(c_cls)) { - return 2; - } else { - return 1; - } -#elif defined(TARGET_RISCV) - /* For RISC-V, InvalidOp is set when multiplicands are Inf and zero */ - if (infzero) { - float_raise(float_flag_invalid | float_flag_invalid_imz, status); - } - return 3; /* default NaN */ -#elif defined(TARGET_XTENSA) - /* - * For Xtensa, the (inf,zero,nan) case sets InvalidOp and returns - * an input NaN if we have one (ie c). - */ - if (infzero) { - float_raise(float_flag_invalid | float_flag_invalid_imz, status); - return 2; - } - if (status->use_first_nan) { - if (is_nan(a_cls)) { - return 0; - } else if (is_nan(b_cls)) { - return 1; - } else { - return 2; - } - } else { - if (is_nan(c_cls)) { - return 2; - } else if (is_nan(b_cls)) { - return 1; - } else { - return 0; - } - } -#else - /* A default implementation: prefer a to b to c. - * This is unlikely to actually match any real implementation. - */ - if (is_nan(a_cls)) { - return 0; - } else if (is_nan(b_cls)) { - return 1; - } else { - return 2; - } -#endif +static bool float64_nan_is_snan(float64 a, float_status *status) { + return frac_msb_is_snan((a >> 51) & 1, status); } /*---------------------------------------------------------------------------- @@ -639,16 +318,7 @@ static int pickNaNMulAdd(FloatClass a_cls, FloatClass b_cls, FloatClass c_cls, b *----------------------------------------------------------------------------*/ bool float64_is_quiet_nan(float64 a_, float_status *status) { - if (no_signaling_nans(status)) { - return float64_is_any_nan(a_); - } else { - uint64_t a = float64_val(a_); - if (snan_bit_is_one(status)) { - return (((a >> 51) & 0xFFF) == 0xFFE) && (a & 0x0007FFFFFFFFFFFFULL); - } else { - return ((a << 1) >= 0xFFF0000000000000ULL); - } - } + return float64_is_any_nan(a_) && !float64_nan_is_snan(a_, status); } /*---------------------------------------------------------------------------- @@ -657,58 +327,35 @@ bool float64_is_quiet_nan(float64 a_, float_status *status) { *----------------------------------------------------------------------------*/ bool float64_is_signaling_nan(float64 a_, float_status *status) { - if (no_signaling_nans(status)) { - return 0; - } else { - uint64_t a = float64_val(a_); - if (snan_bit_is_one(status)) { - return ((a << 1) >= 0xFFF0000000000000ULL); - } else { - return (((a >> 51) & 0xFFF) == 0xFFE) && (a & UINT64_C(0x0007FFFFFFFFFFFF)); - } - } + return float64_is_any_nan(a_) && float64_nan_is_snan(a_, status); +} + +/*---------------------------------------------------------------------------- +| Determine if a floatx80 NaN is signaling NaN. +| The MSB of frac differs from the same function for other types as floatx80 +| has an explicit bit. +*----------------------------------------------------------------------------*/ + +static bool floatx80_nan_is_snan(floatx80 a, float_status *status) { + return frac_msb_is_snan((a.low >> 62) & 1, status); } /*---------------------------------------------------------------------------- | Returns 1 if the extended double-precision floating-point value `a' is a -| quiet NaN; otherwise returns 0. This slightly differs from the same -| function for other types as floatx80 has an explicit bit. +| quiet NaN; otherwise returns 0. *----------------------------------------------------------------------------*/ -int floatx80_is_quiet_nan(floatx80 a, float_status *status) { - if (no_signaling_nans(status)) { - return floatx80_is_any_nan(a); - } else { - if (snan_bit_is_one(status)) { - uint64_t aLow; - - aLow = a.low & ~0x4000000000000000ULL; - return ((a.high & 0x7FFF) == 0x7FFF) && (aLow << 1) && (a.low == aLow); - } else { - return ((a.high & 0x7FFF) == 0x7FFF) && (UINT64_C(0x8000000000000000) <= ((uint64_t) (a.low << 1))); - } - } +bool floatx80_is_quiet_nan(floatx80 a, float_status *status) { + return floatx80_is_any_nan(a) && !floatx80_nan_is_snan(a, status); } /*---------------------------------------------------------------------------- | Returns 1 if the extended double-precision floating-point value `a' is a -| signaling NaN; otherwise returns 0. This slightly differs from the same -| function for other types as floatx80 has an explicit bit. +| signaling NaN; otherwise returns 0. *----------------------------------------------------------------------------*/ -int floatx80_is_signaling_nan(floatx80 a, float_status *status) { - if (no_signaling_nans(status)) { - return 0; - } else { - if (snan_bit_is_one(status)) { - return ((a.high & 0x7FFF) == 0x7FFF) && ((a.low << 1) >= 0x8000000000000000ULL); - } else { - uint64_t aLow; - - aLow = a.low & ~UINT64_C(0x4000000000000000); - return ((a.high & 0x7FFF) == 0x7FFF) && (uint64_t) (aLow << 1) && (a.low == aLow); - } - } +bool floatx80_is_signaling_nan(floatx80 a, float_status *status) { + return floatx80_is_any_nan(a) && floatx80_nan_is_snan(a, status); } /*---------------------------------------------------------------------------- @@ -718,56 +365,17 @@ int floatx80_is_signaling_nan(floatx80 a, float_status *status) { floatx80 floatx80_silence_nan(floatx80 a, float_status *status) { /* None of the targets that have snan_bit_is_one use floatx80. */ - assert(!snan_bit_is_one(status)); + assert(get_snan_rule(status) == float_snan_bit_is_zero); a.low |= UINT64_C(0xC000000000000000); return a; } /*---------------------------------------------------------------------------- -| Takes two extended double-precision floating-point values `a' and `b', one -| of which is a NaN, and returns the appropriate NaN result. If either `a' or -| `b' is a signaling NaN, the invalid exception is raised. +| Determine if a float128 NaN is signaling NaN. *----------------------------------------------------------------------------*/ -floatx80 propagateFloatx80NaN(floatx80 a, floatx80 b, float_status *status) { - bool aIsLargerSignificand; - FloatClass a_cls, b_cls; - - /* This is not complete, but is good enough for pickNaN. */ - a_cls = (!floatx80_is_any_nan(a) ? float_class_normal - : floatx80_is_signaling_nan(a, status) ? float_class_snan - : float_class_qnan); - b_cls = (!floatx80_is_any_nan(b) ? float_class_normal - : floatx80_is_signaling_nan(b, status) ? float_class_snan - : float_class_qnan); - - if (is_snan(a_cls) || is_snan(b_cls)) { - float_raise(float_flag_invalid, status); - } - - if (status->default_nan_mode) { - return floatx80_default_nan(status); - } - - if (a.low < b.low) { - aIsLargerSignificand = 0; - } else if (b.low < a.low) { - aIsLargerSignificand = 1; - } else { - aIsLargerSignificand = (a.high < b.high) ? 1 : 0; - } - - if (pickNaN(a_cls, b_cls, aIsLargerSignificand, status)) { - if (is_snan(b_cls)) { - return floatx80_silence_nan(b, status); - } - return b; - } else { - if (is_snan(a_cls)) { - return floatx80_silence_nan(a, status); - } - return a; - } +static bool float128_nan_is_snan(float128 a, float_status *status) { + return frac_msb_is_snan((a.high >> 47) & 1, status); } /*---------------------------------------------------------------------------- @@ -776,15 +384,7 @@ floatx80 propagateFloatx80NaN(floatx80 a, floatx80 b, float_status *status) { *----------------------------------------------------------------------------*/ bool float128_is_quiet_nan(float128 a, float_status *status) { - if (no_signaling_nans(status)) { - return float128_is_any_nan(a); - } else { - if (snan_bit_is_one(status)) { - return (((a.high >> 47) & 0xFFFF) == 0xFFFE) && (a.low || (a.high & 0x00007FFFFFFFFFFFULL)); - } else { - return ((a.high << 1) >= 0xFFFF000000000000ULL) && (a.low || (a.high & 0x0000FFFFFFFFFFFFULL)); - } - } + return float128_is_any_nan(a) && !float128_nan_is_snan(a, status); } /*---------------------------------------------------------------------------- @@ -793,13 +393,5 @@ bool float128_is_quiet_nan(float128 a, float_status *status) { *----------------------------------------------------------------------------*/ bool float128_is_signaling_nan(float128 a, float_status *status) { - if (no_signaling_nans(status)) { - return 0; - } else { - if (snan_bit_is_one(status)) { - return ((a.high << 1) >= 0xFFFF000000000000ULL) && (a.low || (a.high & 0x0000FFFFFFFFFFFFULL)); - } else { - return (((a.high >> 47) & 0xFFFF) == 0xFFFE) && (a.low || (a.high & UINT64_C(0x00007FFFFFFFFFFF))); - } - } + return float128_is_any_nan(a) && float128_nan_is_snan(a, status); } diff --git a/libtcg/src/fpu/softfloat.c b/libtcg/src/fpu/softfloat.c index 4a612f241..f7ab2df18 100644 --- a/libtcg/src/fpu/softfloat.c +++ b/libtcg/src/fpu/softfloat.c @@ -85,6 +85,7 @@ this code that are retained. #include +#include #include #include #include @@ -133,7 +134,7 @@ this code that are retained. static inline void name(soft_t *a, float_status *s) { \ if (unlikely(soft_t##_is_denormal(*a))) { \ *a = soft_t##_set_sign(soft_t##_zero, soft_t##_is_neg(*a)); \ - float_raise(float_flag_input_denormal, s); \ + float_raise(float_flag_input_denormal_flushed, s); \ } \ } @@ -143,7 +144,7 @@ GEN_INPUT_FLUSH__NOCHECK(float64_input_flush__nocheck, float64) #define GEN_INPUT_FLUSH1(name, soft_t) \ static inline void name(soft_t *a, float_status *s) { \ - if (likely(!s->flush_inputs_to_zero)) { \ + if (likely(!get_flush_inputs_to_zero(s))) { \ return; \ } \ soft_t##_input_flush__nocheck(a, s); \ @@ -155,7 +156,7 @@ GEN_INPUT_FLUSH1(float64_input_flush1, float64) #define GEN_INPUT_FLUSH2(name, soft_t) \ static inline void name(soft_t *a, soft_t *b, float_status *s) { \ - if (likely(!s->flush_inputs_to_zero)) { \ + if (likely(!get_flush_inputs_to_zero(s))) { \ return; \ } \ soft_t##_input_flush__nocheck(a, s); \ @@ -168,7 +169,7 @@ GEN_INPUT_FLUSH2(float64_input_flush2, float64) #define GEN_INPUT_FLUSH3(name, soft_t) \ static inline void name(soft_t *a, soft_t *b, soft_t *c, float_status *s) { \ - if (likely(!s->flush_inputs_to_zero)) { \ + if (likely(!get_flush_inputs_to_zero(s))) { \ return; \ } \ soft_t##_input_flush__nocheck(a, s); \ @@ -218,11 +219,9 @@ GEN_INPUT_FLUSH3(float64_input_flush3, float64) * the use of hardfloat, since hardfloat relies on the inexact flag being * already set. */ -#if defined(TARGET_PPC) || defined(__FAST_MATH__) #if defined(__FAST_MATH__) #warning disabling hardfloat due to -ffast-math: hardfloat requires an exact \ IEEE implementation -#endif #define QEMU_NO_HARDFLOAT 1 #define QEMU_SOFTFLOAT_ATTR QEMU_FLATTEN #else @@ -234,7 +233,8 @@ static inline bool can_use_fpu(const float_status *s) { if (QEMU_NO_HARDFLOAT) { return false; } - return likely(s->float_exception_flags & float_flag_inexact && s->float_rounding_mode == float_round_nearest_even); + return likely(s->float_exception_flags & float_flag_inexact && + get_float_rounding_mode(s) == float_round_nearest_even); } /* @@ -377,48 +377,6 @@ static inline float64 float64_gen2(float64 xa, float64 xb, float_status *s, hard return soft(ua.s, ub.s, s); } -/* - * Classify a floating point number. Everything above float_class_qnan - * is a NaN so cls >= float_class_qnan is any NaN. - */ - -typedef enum __attribute__((__packed__)) { - float_class_unclassified, - float_class_zero, - float_class_normal, - float_class_inf, - float_class_qnan, /* all NaNs from here */ - float_class_snan, -} FloatClass; - -#define float_cmask(bit) (1u << (bit)) - -enum { - float_cmask_zero = float_cmask(float_class_zero), - float_cmask_normal = float_cmask(float_class_normal), - float_cmask_inf = float_cmask(float_class_inf), - float_cmask_qnan = float_cmask(float_class_qnan), - float_cmask_snan = float_cmask(float_class_snan), - - float_cmask_infzero = float_cmask_zero | float_cmask_inf, - float_cmask_anynan = float_cmask_qnan | float_cmask_snan, -}; - -/* Flags for parts_minmax. */ -enum { - /* Set for minimum; clear for maximum. */ - minmax_ismin = 1, - /* Set for the IEEE 754-2008 minNum() and maxNum() operations. */ - minmax_isnum = 2, - /* Set for the IEEE 754-2008 minNumMag() and minNumMag() operations. */ - minmax_ismag = 4, - /* - * Set for the IEEE 754-2019 minimumNumber() and maximumNumber() - * operations. - */ - minmax_isnumber = 8, -}; - /* Simple helpers for checking if, or what kind of, NaN we have */ static inline __attribute__((unused)) bool is_nan(FloatClass c) { return unlikely(c >= float_class_qnan); @@ -433,39 +391,25 @@ static inline __attribute__((unused)) bool is_qnan(FloatClass c) { } /* - * Structure holding all of the decomposed parts of a float. - * The exponent is unbiased and the fraction is normalized. - * - * The fraction words are stored in big-endian word ordering, - * so that truncation from a larger format to a smaller format - * can be done simply by ignoring subsequent elements. + * Return true if the float_cmask has only normals in it + * (including input denormals that were canonicalized) */ +static inline bool cmask_is_only_normals(int cmask) { + return !(cmask & ~float_cmask_anynorm); +} -typedef struct { - FloatClass cls; - bool sign; - int32_t exp; - union { - /* Routines that know the structure may reference the singular name. */ - uint64_t frac; - /* - * Routines expanded with multiple structures reference "hi" and "lo" - * depending on the operation. In FloatParts64, "hi" and "lo" are - * both the same word and aliased here. - */ - uint64_t frac_hi; - uint64_t frac_lo; - }; -} FloatParts64; +static inline bool is_anynorm(FloatClass c) { + return float_cmask(c) & float_cmask_anynorm; +} -typedef struct { - FloatClass cls; - bool sign; - int32_t exp; - uint64_t frac_hi; - uint64_t frac_lo; -} FloatParts128; +/* Record when denormals have been used. */ +static void record_denormals_used(int mask, float_status *s) { + if (unlikely(mask & float_cmask_denormal)) { + float_raise(float_flag_input_denormal_used, s); + } +} +/* FloatParts256 is entirely internal, for parts128_mul* */ typedef struct { FloatClass cls; bool sign; @@ -476,32 +420,19 @@ typedef struct { uint64_t frac_lo; } FloatParts256; +/* + * Minimum and maximum exponent for scalbn. + * These are chosen to be much larger than the true exponent for any input format, + * but also not at the bounds of INT32_{MIN,MAX} so that we can perform other + * arithmetic on the exponent without overflowing, particularly during uncanon. + */ +#define SCALBN_EXP_MAX 0x0fffffff +#define SCALBN_EXP_MIN (-SCALBN_EXP_MAX) + /* These apply to the most significant word of each FloatPartsN. */ #define DECOMPOSED_BINARY_POINT 63 #define DECOMPOSED_IMPLICIT_BIT (1ull << DECOMPOSED_BINARY_POINT) -/* Structure holding all of the relevant parameters for a format. - * exp_size: the size of the exponent field - * exp_bias: the offset applied to the exponent field - * exp_max: the maximum normalised exponent - * frac_size: the size of the fraction field - * frac_shift: shift to normalise the fraction with DECOMPOSED_BINARY_POINT - * The following are computed based the size of fraction - * round_mask: bits below lsb which must be rounded - * The following optional modifiers are available: - * arm_althp: handle ARM Alternative Half Precision - */ -typedef struct { - int exp_size; - int exp_bias; - int exp_re_bias; - int exp_max; - int frac_size; - int frac_shift; - bool arm_althp; - uint64_t round_mask; -} FloatFmt; - /* Expand fields based on the size of exponent and fraction */ #define FLOAT_PARAMS_(E) \ .exp_size = E, .exp_bias = ((1 << E) - 1) >> 1, .exp_re_bias = (1 << (E - 1)) + (1 << (E - 2)), \ @@ -510,17 +441,35 @@ typedef struct { #define FLOAT_PARAMS(E, F) \ FLOAT_PARAMS_(E), .frac_size = F, .frac_shift = (-F - 1) & 63, .round_mask = (1ull << ((-F - 1) & 63)) - 1 -static const FloatFmt float16_params = {FLOAT_PARAMS(5, 10)}; +const FloatFmt float4_e2m1_params = { + FLOAT_PARAMS(2, 1), + .exp_max_kind = float_expmax_normal, +}; + +const FloatFmt float8_e4m3_params = {FLOAT_PARAMS(4, 3), .exp_max_kind = float_expmax_e4m3}; + +/* 110 << frac_shift, with the implicit bit set */ +#define E4M3_NORMAL_FRAC_MAX 0xe000000000000000ull +/* 111 << frac_shift, no implicit bit */ +#define E4M3_NAN_FRAC 0x7000000000000000ull + +const FloatFmt float8_e5m2_params = {FLOAT_PARAMS(5, 2)}; -static const FloatFmt float16_params_ahp = {FLOAT_PARAMS(5, 10), .arm_althp = true}; +const FloatFmt float16_params = {FLOAT_PARAMS(5, 10)}; -static const FloatFmt bfloat16_params = {FLOAT_PARAMS(8, 7)}; +static const FloatFmt float16_params_ahp = { + FLOAT_PARAMS(5, 10), + .exp_max_kind = float_expmax_normal, + .overflow_raises_invalid = true, +}; + +const FloatFmt bfloat16_params = {FLOAT_PARAMS(8, 7)}; -static const FloatFmt float32_params = {FLOAT_PARAMS(8, 23)}; +const FloatFmt float32_params = {FLOAT_PARAMS(8, 23)}; -static const FloatFmt float64_params = {FLOAT_PARAMS(11, 52)}; +const FloatFmt float64_params = {FLOAT_PARAMS(11, 52)}; -static const FloatFmt float128_params = {FLOAT_PARAMS(15, 112)}; +const FloatFmt float128_params = {FLOAT_PARAMS(15, 112)}; #define FLOATX80_PARAMS(R) \ FLOAT_PARAMS_(15), .frac_size = R == 64 ? 63 : R, .frac_shift = 0, \ @@ -529,48 +478,29 @@ static const FloatFmt float128_params = {FLOAT_PARAMS(15, 112)}; static const FloatFmt floatx80_params[3] = { [floatx80_precision_s] = {FLOATX80_PARAMS(23)}, [floatx80_precision_d] = {FLOATX80_PARAMS(52)}, - [floatx80_precision_x] = {FLOATX80_PARAMS(64)}, + [floatx80_precision_x] = + { + FLOATX80_PARAMS(64), + .has_explicit_bit = true, + }, }; /* Unpack a float to parts, but do not canonicalize. */ -static void unpack_raw64(FloatParts64 *r, const FloatFmt *fmt, uint64_t raw) { +static inline QEMU_ALWAYS_INLINE FloatParts64 unpack_raw64(const FloatFmt *fmt, uint64_t raw) { const int f_size = fmt->frac_size; const int e_size = fmt->exp_size; - *r = (FloatParts64) {.cls = float_class_unclassified, - .sign = extract64(raw, f_size + e_size, 1), - .exp = extract64(raw, f_size, e_size), - .frac = extract64(raw, 0, f_size)}; -} - -static void QEMU_FLATTEN float16_unpack_raw(FloatParts64 *p, float16 f) { - unpack_raw64(p, &float16_params, f); -} - -static void QEMU_FLATTEN bfloat16_unpack_raw(FloatParts64 *p, bfloat16 f) { - unpack_raw64(p, &bfloat16_params, f); -} - -static void QEMU_FLATTEN float32_unpack_raw(FloatParts64 *p, float32 f) { - unpack_raw64(p, &float32_params, f); -} - -static void QEMU_FLATTEN float64_unpack_raw(FloatParts64 *p, float64 f) { - unpack_raw64(p, &float64_params, f); + return (FloatParts64) {.cls = float_class_unclassified, + .sign = extract64(raw, f_size + e_size, 1), + .exp = extract64(raw, f_size, e_size), + .frac = extract64(raw, 0, f_size)}; } -static void QEMU_FLATTEN floatx80_unpack_raw(FloatParts128 *p, floatx80 f) { - *p = (FloatParts128) {.cls = float_class_unclassified, - .sign = extract32(f.high, 15, 1), - .exp = extract32(f.high, 0, 15), - .frac_hi = f.low}; -} - -static void QEMU_FLATTEN float128_unpack_raw(FloatParts128 *p, float128 f) { +static FloatParts128 float128_unpack_raw(float128 f) { const int f_size = float128_params.frac_size - 64; const int e_size = float128_params.exp_size; - *p = (FloatParts128) { + return (FloatParts128) { .cls = float_class_unclassified, .sign = extract64(f.high, f_size + e_size, 1), .exp = extract64(f.high, f_size, e_size), @@ -580,7 +510,7 @@ static void QEMU_FLATTEN float128_unpack_raw(FloatParts128 *p, float128 f) { } /* Pack a float from parts, but do not canonicalize. */ -static uint64_t pack_raw64(const FloatParts64 *p, const FloatFmt *fmt) { +static inline uint64_t QEMU_ALWAYS_INLINE pack_raw64(const FloatParts64 *p, const FloatFmt *fmt) { const int f_size = fmt->frac_size; const int e_size = fmt->exp_size; uint64_t ret; @@ -591,22 +521,6 @@ static uint64_t pack_raw64(const FloatParts64 *p, const FloatFmt *fmt) { return ret; } -static float16 QEMU_FLATTEN float16_pack_raw(const FloatParts64 *p) { - return make_float16(pack_raw64(p, &float16_params)); -} - -static bfloat16 QEMU_FLATTEN bfloat16_pack_raw(const FloatParts64 *p) { - return pack_raw64(p, &bfloat16_params); -} - -static float32 QEMU_FLATTEN float32_pack_raw(const FloatParts64 *p) { - return make_float32(pack_raw64(p, &float32_params)); -} - -static float64 QEMU_FLATTEN float64_pack_raw(const FloatParts64 *p) { - return make_float64(pack_raw64(p, &float64_params)); -} - static float128 QEMU_FLATTEN float128_pack_raw(const FloatParts128 *p) { const int f_size = float128_params.frac_size - 64; const int e_size = float128_params.exp_size; @@ -628,169 +542,41 @@ static float128 QEMU_FLATTEN float128_pack_raw(const FloatParts128 *p) { *----------------------------------------------------------------------------*/ #include "softfloat-specialize.c.inc" -#define PARTS_GENERIC_64_128(NAME, P) _Generic((P), FloatParts64 *: parts64_##NAME, FloatParts128 *: parts128_##NAME) - -#define PARTS_GENERIC_64_128_256(NAME, P) \ - _Generic((P), FloatParts64 *: parts64_##NAME, FloatParts128 *: parts128_##NAME, FloatParts256 *: parts256_##NAME) - -#define parts_default_nan(P, S) PARTS_GENERIC_64_128(default_nan, P)(P, S) -#define parts_silence_nan(P, S) PARTS_GENERIC_64_128(silence_nan, P)(P, S) - -static void parts64_return_nan(FloatParts64 *a, float_status *s); -static void parts128_return_nan(FloatParts128 *a, float_status *s); - -#define parts_return_nan(P, S) PARTS_GENERIC_64_128(return_nan, P)(P, S) - -static FloatParts64 *parts64_pick_nan(FloatParts64 *a, FloatParts64 *b, float_status *s); -static FloatParts128 *parts128_pick_nan(FloatParts128 *a, FloatParts128 *b, float_status *s); - -#define parts_pick_nan(A, B, S) PARTS_GENERIC_64_128(pick_nan, A)(A, B, S) - -static FloatParts64 *parts64_pick_nan_muladd(FloatParts64 *a, FloatParts64 *b, FloatParts64 *c, float_status *s, - int ab_mask, int abc_mask); -static FloatParts128 *parts128_pick_nan_muladd(FloatParts128 *a, FloatParts128 *b, FloatParts128 *c, float_status *s, - int ab_mask, int abc_mask); - -#define parts_pick_nan_muladd(A, B, C, S, ABM, ABCM) PARTS_GENERIC_64_128(pick_nan_muladd, A)(A, B, C, S, ABM, ABCM) - -static void parts64_canonicalize(FloatParts64 *p, float_status *status, const FloatFmt *fmt); -static void parts128_canonicalize(FloatParts128 *p, float_status *status, const FloatFmt *fmt); - -#define parts_canonicalize(A, S, F) PARTS_GENERIC_64_128(canonicalize, A)(A, S, F) - -static void parts64_uncanon_normal(FloatParts64 *p, float_status *status, const FloatFmt *fmt); -static void parts128_uncanon_normal(FloatParts128 *p, float_status *status, const FloatFmt *fmt); - -#define parts_uncanon_normal(A, S, F) PARTS_GENERIC_64_128(uncanon_normal, A)(A, S, F) - -static void parts64_uncanon(FloatParts64 *p, float_status *status, const FloatFmt *fmt); -static void parts128_uncanon(FloatParts128 *p, float_status *status, const FloatFmt *fmt); - -#define parts_uncanon(A, S, F) PARTS_GENERIC_64_128(uncanon, A)(A, S, F) - -static void parts64_add_normal(FloatParts64 *a, FloatParts64 *b); -static void parts128_add_normal(FloatParts128 *a, FloatParts128 *b); -static void parts256_add_normal(FloatParts256 *a, FloatParts256 *b); - -#define parts_add_normal(A, B) PARTS_GENERIC_64_128_256(add_normal, A)(A, B) - -static bool parts64_sub_normal(FloatParts64 *a, FloatParts64 *b); -static bool parts128_sub_normal(FloatParts128 *a, FloatParts128 *b); -static bool parts256_sub_normal(FloatParts256 *a, FloatParts256 *b); - -#define parts_sub_normal(A, B) PARTS_GENERIC_64_128_256(sub_normal, A)(A, B) - -static FloatParts64 *parts64_addsub(FloatParts64 *a, FloatParts64 *b, float_status *s, bool subtract); -static FloatParts128 *parts128_addsub(FloatParts128 *a, FloatParts128 *b, float_status *s, bool subtract); - -#define parts_addsub(A, B, S, Z) PARTS_GENERIC_64_128(addsub, A)(A, B, S, Z) - -static FloatParts64 *parts64_mul(FloatParts64 *a, FloatParts64 *b, float_status *s); -static FloatParts128 *parts128_mul(FloatParts128 *a, FloatParts128 *b, float_status *s); - -#define parts_mul(A, B, S) PARTS_GENERIC_64_128(mul, A)(A, B, S) - -static FloatParts64 *parts64_muladd(FloatParts64 *a, FloatParts64 *b, FloatParts64 *c, int flags, float_status *s); -static FloatParts128 *parts128_muladd(FloatParts128 *a, FloatParts128 *b, FloatParts128 *c, int flags, float_status *s); - -#define parts_muladd(A, B, C, Z, S) PARTS_GENERIC_64_128(muladd, A)(A, B, C, Z, S) - -static FloatParts64 *parts64_div(FloatParts64 *a, FloatParts64 *b, float_status *s); -static FloatParts128 *parts128_div(FloatParts128 *a, FloatParts128 *b, float_status *s); - -#define parts_div(A, B, S) PARTS_GENERIC_64_128(div, A)(A, B, S) - -static FloatParts64 *parts64_modrem(FloatParts64 *a, FloatParts64 *b, uint64_t *mod_quot, float_status *s); -static FloatParts128 *parts128_modrem(FloatParts128 *a, FloatParts128 *b, uint64_t *mod_quot, float_status *s); - -#define parts_modrem(A, B, Q, S) PARTS_GENERIC_64_128(modrem, A)(A, B, Q, S) - -static void parts64_sqrt(FloatParts64 *a, float_status *s, const FloatFmt *f); -static void parts128_sqrt(FloatParts128 *a, float_status *s, const FloatFmt *f); - -#define parts_sqrt(A, S, F) PARTS_GENERIC_64_128(sqrt, A)(A, S, F) - -static bool parts64_round_to_int_normal(FloatParts64 *a, FloatRoundMode rm, int scale, int frac_size); -static bool parts128_round_to_int_normal(FloatParts128 *a, FloatRoundMode r, int scale, int frac_size); - -#define parts_round_to_int_normal(A, R, C, F) PARTS_GENERIC_64_128(round_to_int_normal, A)(A, R, C, F) - -static void parts64_round_to_int(FloatParts64 *a, FloatRoundMode rm, int scale, float_status *s, const FloatFmt *fmt); -static void parts128_round_to_int(FloatParts128 *a, FloatRoundMode r, int scale, float_status *s, const FloatFmt *fmt); - -#define parts_round_to_int(A, R, C, S, F) PARTS_GENERIC_64_128(round_to_int, A)(A, R, C, S, F) - -static int64_t parts64_float_to_sint(FloatParts64 *p, FloatRoundMode rmode, int scale, int64_t min, int64_t max, - float_status *s); -static int64_t parts128_float_to_sint(FloatParts128 *p, FloatRoundMode rmode, int scale, int64_t min, int64_t max, - float_status *s); - -#define parts_float_to_sint(P, R, Z, MN, MX, S) PARTS_GENERIC_64_128(float_to_sint, P)(P, R, Z, MN, MX, S) - -static uint64_t parts64_float_to_uint(FloatParts64 *p, FloatRoundMode rmode, int scale, uint64_t max, float_status *s); -static uint64_t parts128_float_to_uint(FloatParts128 *p, FloatRoundMode rmode, int scale, uint64_t max, - float_status *s); - -#define parts_float_to_uint(P, R, Z, M, S) PARTS_GENERIC_64_128(float_to_uint, P)(P, R, Z, M, S) - -static int64_t parts64_float_to_sint_modulo(FloatParts64 *p, FloatRoundMode rmode, int bitsm1, float_status *s); -static int64_t parts128_float_to_sint_modulo(FloatParts128 *p, FloatRoundMode rmode, int bitsm1, float_status *s); - -#define parts_float_to_sint_modulo(P, R, M, S) PARTS_GENERIC_64_128(float_to_sint_modulo, P)(P, R, M, S) - -static void parts64_sint_to_float(FloatParts64 *p, int64_t a, int scale, float_status *s); -static void parts128_sint_to_float(FloatParts128 *p, int64_t a, int scale, float_status *s); - -#define parts_float_to_sint(P, R, Z, MN, MX, S) PARTS_GENERIC_64_128(float_to_sint, P)(P, R, Z, MN, MX, S) - -#define parts_sint_to_float(P, I, Z, S) PARTS_GENERIC_64_128(sint_to_float, P)(P, I, Z, S) - -static void parts64_uint_to_float(FloatParts64 *p, uint64_t a, int scale, float_status *s); -static void parts128_uint_to_float(FloatParts128 *p, uint64_t a, int scale, float_status *s); - -#define parts_uint_to_float(P, I, Z, S) PARTS_GENERIC_64_128(uint_to_float, P)(P, I, Z, S) - -static FloatParts64 *parts64_minmax(FloatParts64 *a, FloatParts64 *b, float_status *s, int flags); -static FloatParts128 *parts128_minmax(FloatParts128 *a, FloatParts128 *b, float_status *s, int flags); - -#define parts_minmax(A, B, S, F) PARTS_GENERIC_64_128(minmax, A)(A, B, S, F) - -static FloatRelation parts64_compare(FloatParts64 *a, FloatParts64 *b, float_status *s, bool q); -static FloatRelation parts128_compare(FloatParts128 *a, FloatParts128 *b, float_status *s, bool q); - -#define parts_compare(A, B, S, Q) PARTS_GENERIC_64_128(compare, A)(A, B, S, Q) - -static void parts64_scalbn(FloatParts64 *a, int n, float_status *s); -static void parts128_scalbn(FloatParts128 *a, int n, float_status *s); - -#define parts_scalbn(A, N, S) PARTS_GENERIC_64_128(scalbn, A)(A, N, S) - -static void parts64_log2(FloatParts64 *a, float_status *s, const FloatFmt *f); -static void parts128_log2(FloatParts128 *a, float_status *s, const FloatFmt *f); - -#define parts_log2(A, S, F) PARTS_GENERIC_64_128(log2, A)(A, S, F) +static int32_t exp_scalbn(int32_t exp, int32_t scale) { + /* + * Catch chains of scaling which lose information. + * In particular, if the exponent has been saturated, + * do not allow it to become unsaturated. + */ + if (exp >= SCALBN_EXP_MAX) { + assert(scale >= 0); + } else if (exp <= SCALBN_EXP_MIN) { + assert(scale <= 0); + } + if (sadd32_overflow(exp, scale, &exp)) { + exp = scale < 0 ? SCALBN_EXP_MIN : SCALBN_EXP_MAX; + } else { + exp = MIN(MAX(exp, SCALBN_EXP_MIN), SCALBN_EXP_MAX); + } + return exp; +} /* * Helper functions for softfloat-parts.c.inc, per-size operations. */ -#define FRAC_GENERIC_64_128(NAME, P) _Generic((P), FloatParts64 *: frac64_##NAME, FloatParts128 *: frac128_##NAME) - -#define FRAC_GENERIC_64_128_256(NAME, P) \ - _Generic((P), FloatParts64 *: frac64_##NAME, FloatParts128 *: frac128_##NAME, FloatParts256 *: frac256_##NAME) - -static bool frac64_add(FloatParts64 *r, FloatParts64 *a, FloatParts64 *b) { +static bool frac64_add(FloatParts64 *r, const FloatParts64 *a, const FloatParts64 *b) { return uadd64_overflow(a->frac, b->frac, &r->frac); } -static bool frac128_add(FloatParts128 *r, FloatParts128 *a, FloatParts128 *b) { +static bool frac128_add(FloatParts128 *r, const FloatParts128 *a, const FloatParts128 *b) { bool c = 0; r->frac_lo = uadd64_carry(a->frac_lo, b->frac_lo, &c); r->frac_hi = uadd64_carry(a->frac_hi, b->frac_hi, &c); return c; } -static bool frac256_add(FloatParts256 *r, FloatParts256 *a, FloatParts256 *b) { +static bool frac256_add(FloatParts256 *r, const FloatParts256 *a, const FloatParts256 *b) { bool c = 0; r->frac_lo = uadd64_carry(a->frac_lo, b->frac_lo, &c); r->frac_lm = uadd64_carry(a->frac_lm, b->frac_lm, &c); @@ -799,19 +585,15 @@ static bool frac256_add(FloatParts256 *r, FloatParts256 *a, FloatParts256 *b) { return c; } -#define frac_add(R, A, B) FRAC_GENERIC_64_128_256(add, R)(R, A, B) - -static bool frac64_addi(FloatParts64 *r, FloatParts64 *a, uint64_t c) { +static bool frac64_addi(FloatParts64 *r, const FloatParts64 *a, uint64_t c) { return uadd64_overflow(a->frac, c, &r->frac); } -static bool frac128_addi(FloatParts128 *r, FloatParts128 *a, uint64_t c) { +static bool frac128_addi(FloatParts128 *r, const FloatParts128 *a, uint64_t c) { c = uadd64_overflow(a->frac_lo, c, &r->frac_lo); return uadd64_overflow(a->frac_hi, c, &r->frac_hi); } -#define frac_addi(R, A, C) FRAC_GENERIC_64_128(addi, R)(R, A, C) - static void frac64_allones(FloatParts64 *a) { a->frac = -1; } @@ -820,15 +602,13 @@ static void frac128_allones(FloatParts128 *a) { a->frac_hi = a->frac_lo = -1; } -#define frac_allones(A) FRAC_GENERIC_64_128(allones, A)(A) - -static FloatRelation frac64_cmp(FloatParts64 *a, FloatParts64 *b) { +static FloatRelation frac64_cmp(const FloatParts64 *a, const FloatParts64 *b) { return (a->frac == b->frac ? float_relation_equal : a->frac < b->frac ? float_relation_less : float_relation_greater); } -static FloatRelation frac128_cmp(FloatParts128 *a, FloatParts128 *b) { +static FloatRelation frac128_cmp(const FloatParts128 *a, const FloatParts128 *b) { uint64_t ta = a->frac_hi, tb = b->frac_hi; if (ta == tb) { ta = a->frac_lo, tb = b->frac_lo; @@ -839,8 +619,6 @@ static FloatRelation frac128_cmp(FloatParts128 *a, FloatParts128 *b) { return ta < tb ? float_relation_less : float_relation_greater; } -#define frac_cmp(A, B) FRAC_GENERIC_64_128(cmp, A)(A, B) - static void frac64_clear(FloatParts64 *a) { a->frac = 0; } @@ -849,9 +627,7 @@ static void frac128_clear(FloatParts128 *a) { a->frac_hi = a->frac_lo = 0; } -#define frac_clear(A) FRAC_GENERIC_64_128(clear, A)(A) - -static bool frac64_div(FloatParts64 *a, FloatParts64 *b) { +static bool frac64_div(FloatParts64 *a, const FloatParts64 *b) { uint64_t n1, n0, r, q; bool ret; @@ -882,7 +658,7 @@ static bool frac64_div(FloatParts64 *a, FloatParts64 *b) { return ret; } -static bool frac128_div(FloatParts128 *a, FloatParts128 *b) { +static bool frac128_div(FloatParts128 *a, const FloatParts128 *b) { uint64_t q0, q1, a0, a1, b0, b1; uint64_t r0, r1, r2, r3, t0, t1, t2, t3; bool ret = false; @@ -928,28 +704,22 @@ static bool frac128_div(FloatParts128 *a, FloatParts128 *b) { return ret; } -#define frac_div(A, B) FRAC_GENERIC_64_128(div, A)(A, B) - -static bool frac64_eqz(FloatParts64 *a) { +static bool frac64_eqz(const FloatParts64 *a) { return a->frac == 0; } -static bool frac128_eqz(FloatParts128 *a) { +static bool frac128_eqz(const FloatParts128 *a) { return (a->frac_hi | a->frac_lo) == 0; } -#define frac_eqz(A) FRAC_GENERIC_64_128(eqz, A)(A) - -static void frac64_mulw(FloatParts128 *r, FloatParts64 *a, FloatParts64 *b) { +static void frac64_mulw(FloatParts128 *r, const FloatParts64 *a, const FloatParts64 *b) { mulu64(&r->frac_lo, &r->frac_hi, a->frac, b->frac); } -static void frac128_mulw(FloatParts256 *r, FloatParts128 *a, FloatParts128 *b) { +static void frac128_mulw(FloatParts256 *r, const FloatParts128 *a, const FloatParts128 *b) { mul128To256(a->frac_hi, a->frac_lo, b->frac_hi, b->frac_lo, &r->frac_hi, &r->frac_hm, &r->frac_lm, &r->frac_lo); } -#define frac_mulw(R, A, B) FRAC_GENERIC_64_128(mulw, A)(R, A, B) - static void frac64_neg(FloatParts64 *a) { a->frac = -a->frac; } @@ -968,8 +738,6 @@ static void frac256_neg(FloatParts256 *a) { a->frac_hi = usub64_borrow(0, a->frac_hi, &c); } -#define frac_neg(A) FRAC_GENERIC_64_128_256(neg, A)(A) - static int frac64_normalize(FloatParts64 *a) { if (a->frac) { int shift = clz64(a->frac); @@ -1040,9 +808,7 @@ static int frac256_normalize(FloatParts256 *a) { return ret; } -#define frac_normalize(A) FRAC_GENERIC_64_128_256(normalize, A)(A) - -static void frac64_modrem(FloatParts64 *a, FloatParts64 *b, uint64_t *mod_quot) { +static void frac64_modrem(FloatParts64 *a, const FloatParts64 *b, uint64_t *mod_quot) { uint64_t a0, a1, b0, t0, t1, q, quot; int exp_diff = a->exp - b->exp; int shift; @@ -1123,7 +889,7 @@ static void frac64_modrem(FloatParts64 *a, FloatParts64 *b, uint64_t *mod_quot) a->frac = a0 | (a1 != 0); } -static void frac128_modrem(FloatParts128 *a, FloatParts128 *b, uint64_t *mod_quot) { +static void frac128_modrem(FloatParts128 *a, const FloatParts128 *b, uint64_t *mod_quot) { uint64_t a0, a1, a2, b0, b1, t0, t1, t2, q, quot; int exp_diff = a->exp - b->exp; int shift; @@ -1215,8 +981,6 @@ static void frac128_modrem(FloatParts128 *a, FloatParts128 *b, uint64_t *mod_quo a->frac_lo = a1 | (a2 != 0); } -#define frac_modrem(A, B, Q) FRAC_GENERIC_64_128(modrem, A)(A, B, Q) - static void frac64_shl(FloatParts64 *a, int c) { a->frac <<= c; } @@ -1238,8 +1002,6 @@ static void frac128_shl(FloatParts128 *a, int c) { a->frac_lo = a1; } -#define frac_shl(A, C) FRAC_GENERIC_64_128(shl, A)(A, C) - static void frac64_shr(FloatParts64 *a, int c) { a->frac >>= c; } @@ -1261,8 +1023,6 @@ static void frac128_shr(FloatParts128 *a, int c) { a->frac_lo = a1; } -#define frac_shr(A, C) FRAC_GENERIC_64_128(shr, A)(A, C) - static void frac64_shrjam(FloatParts64 *a, int c) { uint64_t a0 = a->frac; @@ -1348,20 +1108,18 @@ static void frac256_shrjam(FloatParts256 *a, int c) { a->frac_hi = a0; } -#define frac_shrjam(A, C) FRAC_GENERIC_64_128_256(shrjam, A)(A, C) - -static bool frac64_sub(FloatParts64 *r, FloatParts64 *a, FloatParts64 *b) { +static bool frac64_sub(FloatParts64 *r, const FloatParts64 *a, const FloatParts64 *b) { return usub64_overflow(a->frac, b->frac, &r->frac); } -static bool frac128_sub(FloatParts128 *r, FloatParts128 *a, FloatParts128 *b) { +static bool frac128_sub(FloatParts128 *r, const FloatParts128 *a, const FloatParts128 *b) { bool c = 0; r->frac_lo = usub64_borrow(a->frac_lo, b->frac_lo, &c); r->frac_hi = usub64_borrow(a->frac_hi, b->frac_hi, &c); return c; } -static bool frac256_sub(FloatParts256 *r, FloatParts256 *a, FloatParts256 *b) { +static bool frac256_sub(FloatParts256 *r, const FloatParts256 *a, const FloatParts256 *b) { bool c = 0; r->frac_lo = usub64_borrow(a->frac_lo, b->frac_lo, &c); r->frac_lm = usub64_borrow(a->frac_lm, b->frac_lm, &c); @@ -1370,33 +1128,27 @@ static bool frac256_sub(FloatParts256 *r, FloatParts256 *a, FloatParts256 *b) { return c; } -#define frac_sub(R, A, B) FRAC_GENERIC_64_128_256(sub, R)(R, A, B) - -static void frac64_truncjam(FloatParts64 *r, FloatParts128 *a) { +static void frac64_truncjam(FloatParts64 *r, const FloatParts128 *a) { r->frac = a->frac_hi | (a->frac_lo != 0); } -static void frac128_truncjam(FloatParts128 *r, FloatParts256 *a) { +static void frac128_truncjam(FloatParts128 *r, const FloatParts256 *a) { r->frac_hi = a->frac_hi; r->frac_lo = a->frac_hm | ((a->frac_lm | a->frac_lo) != 0); } -#define frac_truncjam(R, A) FRAC_GENERIC_64_128(truncjam, R)(R, A) - -static void frac64_widen(FloatParts128 *r, FloatParts64 *a) { +static void frac64_widen(FloatParts128 *r, const FloatParts64 *a) { r->frac_hi = a->frac; r->frac_lo = 0; } -static void frac128_widen(FloatParts256 *r, FloatParts128 *a) { +static void frac128_widen(FloatParts256 *r, const FloatParts128 *a) { r->frac_hi = a->frac_hi; r->frac_hm = a->frac_lo; r->frac_lm = 0; r->frac_lo = 0; } -#define frac_widen(A, B) FRAC_GENERIC_64_128(widen, B)(A, B) - /* * Reciprocal sqrt table. 1 bit of exponent, 6-bits of mantessa. * From https://git.musl-libc.org/cgit/musl/tree/src/math/sqrt_data.c @@ -1415,18 +1167,18 @@ static const uint16_t rsqrt_tab[128] = { 0xbcef, 0xbc23, 0xbb59, 0xba91, 0xb9cc, 0xb90a, 0xb84a, 0xb78c, 0xb6d0, 0xb617, 0xb560, }; +#define fracN(NAME) glue(glue(glue(frac, N), _), NAME) +#define fracW(NAME) glue(glue(glue(frac, W), _), NAME) #define partsN(NAME) glue(glue(glue(parts, N), _), NAME) +#define partsW(NAME) glue(glue(glue(parts, W), _), NAME) #define FloatPartsN glue(FloatParts, N) #define FloatPartsW glue(FloatParts, W) -#define N 64 -#define W 128 +#define N 256 #include "softfloat-parts-addsub.c.inc" -#include "softfloat-parts.c.inc" #undef N -#undef W #define N 128 #define W 256 @@ -1435,13 +1187,18 @@ static const uint16_t rsqrt_tab[128] = { #undef N #undef W -#define N 256 +#define N 64 +#define W 128 #include "softfloat-parts-addsub.c.inc" +#include "softfloat-parts.c.inc" #undef N #undef W +#undef fracN +#undef fracW #undef partsN +#undef partsW #undef FloatPartsN #undef FloatPartsW @@ -1449,80 +1206,127 @@ static const uint16_t rsqrt_tab[128] = { * Pack/unpack routines with a specific FloatFmt. */ -static void float16a_unpack_canonical(FloatParts64 *p, float16 f, float_status *s, const FloatFmt *params) { - float16_unpack_raw(p, f); - parts_canonicalize(p, s, params); +FloatParts64 float4_e2m1_unpack_canonical(float4_e2m1 f, float_status *s) { + FloatParts64 p = unpack_raw64(&float4_e2m1_params, f); + parts64_canonicalize(&p, s, &float4_e2m1_params); + return p; +} + +FloatParts64 float8_e4m3_unpack_canonical(float8_e4m3 f, float_status *s) { + FloatParts64 p = unpack_raw64(&float8_e4m3_params, f); + parts64_canonicalize(&p, s, &float8_e4m3_params); + return p; } -static void float16_unpack_canonical(FloatParts64 *p, float16 f, float_status *s) { - float16a_unpack_canonical(p, f, s, &float16_params); +FloatParts64 float8_e5m2_unpack_canonical(float8_e5m2 f, float_status *s) { + FloatParts64 p = unpack_raw64(&float8_e5m2_params, f); + parts64_canonicalize(&p, s, &float8_e5m2_params); + return p; } -static void bfloat16_unpack_canonical(FloatParts64 *p, bfloat16 f, float_status *s) { - bfloat16_unpack_raw(p, f); - parts_canonicalize(p, s, &bfloat16_params); +static FloatParts64 float16a_unpack_canonical(float16 f, float_status *s, const FloatFmt *params) { + FloatParts64 p = unpack_raw64(&float16_params, f); + parts64_canonicalize(&p, s, params); + return p; +} + +FloatParts64 float16_unpack_canonical(float16 f, float_status *s) { + return float16a_unpack_canonical(f, s, &float16_params); +} + +FloatParts64 bfloat16_unpack_canonical(bfloat16 f, float_status *s) { + FloatParts64 p = unpack_raw64(&bfloat16_params, f); + parts64_canonicalize(&p, s, &bfloat16_params); + return p; +} + +float8_e4m3 float8_e4m3_round_pack_canonical(FloatParts64 *p, float_status *s, bool saturate) { + parts64_uncanon(p, s, &float8_e4m3_params, saturate); + return pack_raw64(p, &float8_e4m3_params); +} + +float8_e5m2 float8_e5m2_round_pack_canonical(FloatParts64 *p, float_status *s, bool saturate) { + parts64_uncanon(p, s, &float8_e5m2_params, saturate); + return pack_raw64(p, &float8_e5m2_params); } static float16 float16a_round_pack_canonical(FloatParts64 *p, float_status *s, const FloatFmt *params) { - parts_uncanon(p, s, params); - return float16_pack_raw(p); + parts64_uncanon(p, s, params, false); + return pack_raw64(p, &float16_params); } -static float16 float16_round_pack_canonical(FloatParts64 *p, float_status *s) { +float16 float16_round_pack_canonical(FloatParts64 *p, float_status *s) { return float16a_round_pack_canonical(p, s, &float16_params); } -static bfloat16 bfloat16_round_pack_canonical(FloatParts64 *p, float_status *s) { - parts_uncanon(p, s, &bfloat16_params); - return bfloat16_pack_raw(p); +bfloat16 bfloat16_round_pack_canonical(FloatParts64 *p, float_status *s) { + parts64_uncanon(p, s, &bfloat16_params, false); + return pack_raw64(p, &bfloat16_params); } -static void float32_unpack_canonical(FloatParts64 *p, float32 f, float_status *s) { - float32_unpack_raw(p, f); - parts_canonicalize(p, s, &float32_params); +FloatParts64 float32_unpack_canonical(float32 f, float_status *s) { + FloatParts64 p = unpack_raw64(&float32_params, f); + parts64_canonicalize(&p, s, &float32_params); + return p; } -static float32 float32_round_pack_canonical(FloatParts64 *p, float_status *s) { - parts_uncanon(p, s, &float32_params); - return float32_pack_raw(p); +float32 float32_round_pack_canonical(FloatParts64 *p, float_status *s) { + parts64_uncanon(p, s, &float32_params, false); + return pack_raw64(p, &float32_params); } -static void float64_unpack_canonical(FloatParts64 *p, float64 f, float_status *s) { - float64_unpack_raw(p, f); - parts_canonicalize(p, s, &float64_params); +FloatParts64 float64_unpack_canonical(float64 f, float_status *s) { + FloatParts64 p = unpack_raw64(&float64_params, f); + parts64_canonicalize(&p, s, &float64_params); + return p; } -static float64 float64_round_pack_canonical(FloatParts64 *p, float_status *s) { - parts_uncanon(p, s, &float64_params); - return float64_pack_raw(p); +float64 float64_round_pack_canonical(FloatParts64 *p, float_status *s) { + parts64_uncanon(p, s, &float64_params, false); + return pack_raw64(p, &float64_params); } -static float64 float64r32_round_pack_canonical(FloatParts64 *p, float_status *s) { - parts_uncanon(p, s, &float32_params); +/* + * Round to Fmt while remaining canonicalized. + */ +FloatParts64 parts64_round_to_fmt(const FloatParts64 *p, float_status *s, const FloatFmt *fmt) { + FloatParts64 r = *p; + parts64_uncanon(&r, s, fmt, false); /* - * In parts_uncanon, we placed the fraction for float32 at the lsb. + * We normally expect uncanon to be followed by pack_raw, + * so we don't actually crop the bits. Do so now. + */ + r.frac &= MAKE_64BIT_MASK(0, fmt->frac_size); + parts64_canonicalize(&r, s, fmt); + return r; +} + +static float64 float64r32_pack_raw(FloatParts64 *p) { + /* + * In parts64_uncanon, we placed the fraction for float32 at the lsb. * We need to adjust the fraction higher so that the least N bits are * zero, and the fraction is adjacent to the float64 implicit bit. */ switch (p->cls) { case float_class_normal: + case float_class_denormal: if (unlikely(p->exp == 0)) { /* * The result is denormal for float32, but can be represented * in normalized form for float64. Adjust, per canonicalize. */ - int shift = frac_normalize(p); - p->exp = (float32_params.frac_shift - float32_params.exp_bias - shift + 1 + float64_params.exp_bias); - frac_shr(p, float64_params.frac_shift); + int shift = frac64_normalize(p); + frac64_shr(p, float64_params.frac_shift); + p->exp = float32_params.frac_shift - shift + 1; } else { - frac_shl(p, float32_params.frac_shift - float64_params.frac_shift); - p->exp += float64_params.exp_bias - float32_params.exp_bias; + frac64_shl(p, float32_params.frac_shift - float64_params.frac_shift); } + p->exp += float64_params.exp_bias - float32_params.exp_bias; break; case float_class_snan: case float_class_qnan: - frac_shl(p, float32_params.frac_shift - float64_params.frac_shift); + frac64_shl(p, float32_params.frac_shift - float64_params.frac_shift); p->exp = float64_params.exp_max; break; case float_class_inf: @@ -1534,23 +1338,29 @@ static float64 float64r32_round_pack_canonical(FloatParts64 *p, float_status *s) g_assert_not_reached(); } - return float64_pack_raw(p); + return pack_raw64(p, &float64_params); +} + +static float64 float64r32_round_pack_canonical(FloatParts64 *p, float_status *s) { + parts64_uncanon(p, s, &float32_params, false); + return float64r32_pack_raw(p); } -static void float128_unpack_canonical(FloatParts128 *p, float128 f, float_status *s) { - float128_unpack_raw(p, f); - parts_canonicalize(p, s, &float128_params); +FloatParts128 float128_unpack_canonical(float128 f, float_status *s) { + FloatParts128 p = float128_unpack_raw(f); + parts128_canonicalize(&p, s, &float128_params); + return p; } -static float128 float128_round_pack_canonical(FloatParts128 *p, float_status *s) { - parts_uncanon(p, s, &float128_params); +float128 float128_round_pack_canonical(FloatParts128 *p, float_status *s) { + parts128_uncanon(p, s, &float128_params, false); return float128_pack_raw(p); } /* Returns false if the encoding is invalid. */ -static bool floatx80_unpack_canonical(FloatParts128 *p, floatx80 f, float_status *s) { +bool floatx80_unpack_canonical(FloatParts128 *p, floatx80 f, float_status *s) { /* Ensure rounding precision is set before beginning. */ - switch (s->floatx80_rounding_precision) { + switch (get_floatx80_rounding_precision(s)) { case floatx80_precision_x: case floatx80_precision_d: case floatx80_precision_s: @@ -1559,15 +1369,18 @@ static bool floatx80_unpack_canonical(FloatParts128 *p, floatx80 f, float_status g_assert_not_reached(); } - if (unlikely(floatx80_invalid_encoding(f))) { + if (unlikely(floatx80_invalid_encoding(f, s))) { float_raise(float_flag_invalid, s); return false; } - floatx80_unpack_raw(p, f); + *p = (FloatParts128) {.cls = float_class_unclassified, + .sign = extract32(f.high, 15, 1), + .exp = extract32(f.high, 0, 15), + .frac_hi = f.low}; if (likely(p->exp != floatx80_params[floatx80_precision_x].exp_max)) { - parts_canonicalize(p, s, &floatx80_params[floatx80_precision_x]); + parts128_canonicalize(p, s, &floatx80_params[floatx80_precision_x]); } else { /* The explicit integer bit is ignored, after invalid checks. */ p->frac_hi &= MAKE_64BIT_MASK(0, 63); @@ -1578,15 +1391,16 @@ static bool floatx80_unpack_canonical(FloatParts128 *p, floatx80 f, float_status return true; } -static floatx80 floatx80_round_pack_canonical(FloatParts128 *p, float_status *s) { - const FloatFmt *fmt = &floatx80_params[s->floatx80_rounding_precision]; +floatx80 floatx80_round_pack_canonical(FloatParts128 *p, float_status *s) { + const FloatFmt *fmt = &floatx80_params[get_floatx80_rounding_precision(s)]; uint64_t frac; int exp; switch (p->cls) { case float_class_normal: - if (s->floatx80_rounding_precision == floatx80_precision_x) { - parts_uncanon_normal(p, s, fmt); + case float_class_denormal: + if (get_floatx80_rounding_precision(s) == floatx80_precision_x) { + parts128_uncanon_normal(p, s, fmt, false); frac = p->frac_hi; exp = p->exp; } else { @@ -1594,8 +1408,8 @@ static floatx80 floatx80_round_pack_canonical(FloatParts128 *p, float_status *s) p64.sign = p->sign; p64.exp = p->exp; - frac_truncjam(&p64, p); - parts_uncanon_normal(&p64, s, fmt); + frac64_truncjam(&p64, p); + parts64_uncanon_normal(&p64, s, fmt, false); frac = p64.frac; exp = p64.exp; } @@ -1606,7 +1420,7 @@ static floatx80 floatx80_round_pack_canonical(FloatParts128 *p, float_status *s) case float_class_inf: /* x86 and m68k differ in the setting of the integer bit. */ - frac = floatx80_infinity_low; + frac = get_floatx80_behaviour(s) & floatx80_default_inf_int_bit_is_zero ? 0 : (1ULL << 63); exp = fmt->exp_max; break; @@ -1634,13 +1448,11 @@ static floatx80 floatx80_round_pack_canonical(FloatParts128 *p, float_status *s) */ static float16 QEMU_FLATTEN float16_addsub(float16 a, float16 b, float_status *status, bool subtract) { - FloatParts64 pa, pb, *pr; + FloatParts64 pa = float16_unpack_canonical(a, status); + FloatParts64 pb = float16_unpack_canonical(b, status); + FloatParts64 pr = parts64_addsub(&pa, &pb, status, subtract); - float16_unpack_canonical(&pa, a, status); - float16_unpack_canonical(&pb, b, status); - pr = parts_addsub(&pa, &pb, status, subtract); - - return float16_round_pack_canonical(pr, status); + return float16_round_pack_canonical(&pr, status); } float16 float16_add(float16 a, float16 b, float_status *status) { @@ -1652,13 +1464,11 @@ float16 float16_sub(float16 a, float16 b, float_status *status) { } static float32 QEMU_SOFTFLOAT_ATTR soft_f32_addsub(float32 a, float32 b, float_status *status, bool subtract) { - FloatParts64 pa, pb, *pr; - - float32_unpack_canonical(&pa, a, status); - float32_unpack_canonical(&pb, b, status); - pr = parts_addsub(&pa, &pb, status, subtract); + FloatParts64 pa = float32_unpack_canonical(a, status); + FloatParts64 pb = float32_unpack_canonical(b, status); + FloatParts64 pr = parts64_addsub(&pa, &pb, status, subtract); - return float32_round_pack_canonical(pr, status); + return float32_round_pack_canonical(&pr, status); } static float32 soft_f32_add(float32 a, float32 b, float_status *status) { @@ -1670,13 +1480,11 @@ static float32 soft_f32_sub(float32 a, float32 b, float_status *status) { } static float64 QEMU_SOFTFLOAT_ATTR soft_f64_addsub(float64 a, float64 b, float_status *status, bool subtract) { - FloatParts64 pa, pb, *pr; + FloatParts64 pa = float64_unpack_canonical(a, status); + FloatParts64 pb = float64_unpack_canonical(b, status); + FloatParts64 pr = parts64_addsub(&pa, &pb, status, subtract); - float64_unpack_canonical(&pa, a, status); - float64_unpack_canonical(&pb, b, status); - pr = parts_addsub(&pa, &pb, status, subtract); - - return float64_round_pack_canonical(pr, status); + return float64_round_pack_canonical(&pr, status); } static float64 soft_f64_add(float64 a, float64 b, float_status *status) { @@ -1743,13 +1551,11 @@ float64 QEMU_FLATTEN float64_sub(float64 a, float64 b, float_status *s) { } static float64 float64r32_addsub(float64 a, float64 b, float_status *status, bool subtract) { - FloatParts64 pa, pb, *pr; + FloatParts64 pa = float64_unpack_canonical(a, status); + FloatParts64 pb = float64_unpack_canonical(b, status); + FloatParts64 pr = parts64_addsub(&pa, &pb, status, subtract); - float64_unpack_canonical(&pa, a, status); - float64_unpack_canonical(&pb, b, status); - pr = parts_addsub(&pa, &pb, status, subtract); - - return float64r32_round_pack_canonical(pr, status); + return float64r32_round_pack_canonical(&pr, status); } float64 float64r32_add(float64 a, float64 b, float_status *status) { @@ -1761,13 +1567,11 @@ float64 float64r32_sub(float64 a, float64 b, float_status *status) { } static bfloat16 QEMU_FLATTEN bfloat16_addsub(bfloat16 a, bfloat16 b, float_status *status, bool subtract) { - FloatParts64 pa, pb, *pr; - - bfloat16_unpack_canonical(&pa, a, status); - bfloat16_unpack_canonical(&pb, b, status); - pr = parts_addsub(&pa, &pb, status, subtract); + FloatParts64 pa = bfloat16_unpack_canonical(a, status); + FloatParts64 pb = bfloat16_unpack_canonical(b, status); + FloatParts64 pr = parts64_addsub(&pa, &pb, status, subtract); - return bfloat16_round_pack_canonical(pr, status); + return bfloat16_round_pack_canonical(&pr, status); } bfloat16 bfloat16_add(bfloat16 a, bfloat16 b, float_status *status) { @@ -1779,13 +1583,11 @@ bfloat16 bfloat16_sub(bfloat16 a, bfloat16 b, float_status *status) { } static float128 QEMU_FLATTEN float128_addsub(float128 a, float128 b, float_status *status, bool subtract) { - FloatParts128 pa, pb, *pr; + FloatParts128 pa = float128_unpack_canonical(a, status); + FloatParts128 pb = float128_unpack_canonical(b, status); + FloatParts128 pr = parts128_addsub(&pa, &pb, status, subtract); - float128_unpack_canonical(&pa, a, status); - float128_unpack_canonical(&pb, b, status); - pr = parts_addsub(&pa, &pb, status, subtract); - - return float128_round_pack_canonical(pr, status); + return float128_round_pack_canonical(&pr, status); } float128 float128_add(float128 a, float128 b, float_status *status) { @@ -1797,14 +1599,14 @@ float128 float128_sub(float128 a, float128 b, float_status *status) { } static floatx80 QEMU_FLATTEN floatx80_addsub(floatx80 a, floatx80 b, float_status *status, bool subtract) { - FloatParts128 pa, pb, *pr; + FloatParts128 pa, pb; if (!floatx80_unpack_canonical(&pa, a, status) || !floatx80_unpack_canonical(&pb, b, status)) { return floatx80_default_nan(status); } - pr = parts_addsub(&pa, &pb, status, subtract); - return floatx80_round_pack_canonical(pr, status); + pa = parts128_addsub(&pa, &pb, status, subtract); + return floatx80_round_pack_canonical(&pa, status); } floatx80 floatx80_add(floatx80 a, floatx80 b, float_status *status) { @@ -1820,33 +1622,27 @@ floatx80 floatx80_sub(floatx80 a, floatx80 b, float_status *status) { */ float16 QEMU_FLATTEN float16_mul(float16 a, float16 b, float_status *status) { - FloatParts64 pa, pb, *pr; - - float16_unpack_canonical(&pa, a, status); - float16_unpack_canonical(&pb, b, status); - pr = parts_mul(&pa, &pb, status); + FloatParts64 pa = float16_unpack_canonical(a, status); + FloatParts64 pb = float16_unpack_canonical(b, status); + FloatParts64 pr = parts64_mul(&pa, &pb, status); - return float16_round_pack_canonical(pr, status); + return float16_round_pack_canonical(&pr, status); } static float32 QEMU_SOFTFLOAT_ATTR soft_f32_mul(float32 a, float32 b, float_status *status) { - FloatParts64 pa, pb, *pr; + FloatParts64 pa = float32_unpack_canonical(a, status); + FloatParts64 pb = float32_unpack_canonical(b, status); + FloatParts64 pr = parts64_mul(&pa, &pb, status); - float32_unpack_canonical(&pa, a, status); - float32_unpack_canonical(&pb, b, status); - pr = parts_mul(&pa, &pb, status); - - return float32_round_pack_canonical(pr, status); + return float32_round_pack_canonical(&pr, status); } static float64 QEMU_SOFTFLOAT_ATTR soft_f64_mul(float64 a, float64 b, float_status *status) { - FloatParts64 pa, pb, *pr; - - float64_unpack_canonical(&pa, a, status); - float64_unpack_canonical(&pb, b, status); - pr = parts_mul(&pa, &pb, status); + FloatParts64 pa = float64_unpack_canonical(a, status); + FloatParts64 pb = float64_unpack_canonical(b, status); + FloatParts64 pr = parts64_mul(&pa, &pb, status); - return float64_round_pack_canonical(pr, status); + return float64_round_pack_canonical(&pr, status); } static float hard_f32_mul(float a, float b) { @@ -1866,81 +1662,102 @@ float64 QEMU_FLATTEN float64_mul(float64 a, float64 b, float_status *s) { } float64 float64r32_mul(float64 a, float64 b, float_status *status) { - FloatParts64 pa, pb, *pr; - - float64_unpack_canonical(&pa, a, status); - float64_unpack_canonical(&pb, b, status); - pr = parts_mul(&pa, &pb, status); + FloatParts64 pa = float64_unpack_canonical(a, status); + FloatParts64 pb = float64_unpack_canonical(b, status); + FloatParts64 pr = parts64_mul(&pa, &pb, status); - return float64r32_round_pack_canonical(pr, status); + return float64r32_round_pack_canonical(&pr, status); } bfloat16 QEMU_FLATTEN bfloat16_mul(bfloat16 a, bfloat16 b, float_status *status) { - FloatParts64 pa, pb, *pr; + FloatParts64 pa = bfloat16_unpack_canonical(a, status); + FloatParts64 pb = bfloat16_unpack_canonical(b, status); + FloatParts64 pr = parts64_mul(&pa, &pb, status); - bfloat16_unpack_canonical(&pa, a, status); - bfloat16_unpack_canonical(&pb, b, status); - pr = parts_mul(&pa, &pb, status); - - return bfloat16_round_pack_canonical(pr, status); + return bfloat16_round_pack_canonical(&pr, status); } float128 QEMU_FLATTEN float128_mul(float128 a, float128 b, float_status *status) { - FloatParts128 pa, pb, *pr; - - float128_unpack_canonical(&pa, a, status); - float128_unpack_canonical(&pb, b, status); - pr = parts_mul(&pa, &pb, status); + FloatParts128 pa = float128_unpack_canonical(a, status); + FloatParts128 pb = float128_unpack_canonical(b, status); + FloatParts128 pr = parts128_mul(&pa, &pb, status); - return float128_round_pack_canonical(pr, status); + return float128_round_pack_canonical(&pr, status); } floatx80 QEMU_FLATTEN floatx80_mul(floatx80 a, floatx80 b, float_status *status) { - FloatParts128 pa, pb, *pr; + FloatParts128 pa, pb; if (!floatx80_unpack_canonical(&pa, a, status) || !floatx80_unpack_canonical(&pb, b, status)) { return floatx80_default_nan(status); } - pr = parts_mul(&pa, &pb, status); - return floatx80_round_pack_canonical(pr, status); + pa = parts128_mul(&pa, &pb, status); + return floatx80_round_pack_canonical(&pa, status); } /* * Fused multiply-add */ -float16 QEMU_FLATTEN float16_muladd(float16 a, float16 b, float16 c, int flags, float_status *status) { - FloatParts64 pa, pb, pc, *pr; - - float16_unpack_canonical(&pa, a, status); - float16_unpack_canonical(&pb, b, status); - float16_unpack_canonical(&pc, c, status); - pr = parts_muladd(&pa, &pb, &pc, flags, status); +float16 float16_muladd_scalbn(float16 a, float16 b, float16 c, int scale, int flags, float_status *status) { + FloatParts64 pa = float16_unpack_canonical(a, status); + FloatParts64 pb = float16_unpack_canonical(b, status); + FloatParts64 pc = float16_unpack_canonical(c, status); + FloatParts64 pr = parts64_muladd(&pa, &pb, &pc, flags, status); - return float16_round_pack_canonical(pr, status); + /* Before rounding, scale. */ + if (scale) { + pr = parts64_scalbn(&pr, scale, status); + } + parts64_uncanon(&pr, status, &float16_params, false); + /* After rounding, apply negate result, especially for -0.0. */ + if ((flags & float_muladd_negate_result) && !is_nan(pr.cls)) { + pr.sign ^= 1; + } + return pack_raw64(&pr, &float16_params); } -static float32 QEMU_SOFTFLOAT_ATTR soft_f32_muladd(float32 a, float32 b, float32 c, int flags, float_status *status) { - FloatParts64 pa, pb, pc, *pr; +float16 float16_muladd(float16 a, float16 b, float16 c, int flags, float_status *status) { + return float16_muladd_scalbn(a, b, c, 0, flags, status); +} - float32_unpack_canonical(&pa, a, status); - float32_unpack_canonical(&pb, b, status); - float32_unpack_canonical(&pc, c, status); - pr = parts_muladd(&pa, &pb, &pc, flags, status); +float32 QEMU_SOFTFLOAT_ATTR float32_muladd_scalbn(float32 a, float32 b, float32 c, int scale, int flags, + float_status *status) { + FloatParts64 pa = float32_unpack_canonical(a, status); + FloatParts64 pb = float32_unpack_canonical(b, status); + FloatParts64 pc = float32_unpack_canonical(c, status); + FloatParts64 pr = parts64_muladd(&pa, &pb, &pc, flags, status); - return float32_round_pack_canonical(pr, status); + /* Before rounding, scale. */ + if (scale) { + pr = parts64_scalbn(&pr, scale, status); + } + parts64_uncanon(&pr, status, &float32_params, false); + /* After rounding, apply negate result, especially for -0.0. */ + if ((flags & float_muladd_negate_result) && !is_nan(pr.cls)) { + pr.sign ^= 1; + } + return pack_raw64(&pr, &float32_params); } -static float64 QEMU_SOFTFLOAT_ATTR soft_f64_muladd(float64 a, float64 b, float64 c, int flags, float_status *status) { - FloatParts64 pa, pb, pc, *pr; +float64 QEMU_SOFTFLOAT_ATTR float64_muladd_scalbn(float64 a, float64 b, float64 c, int scale, int flags, + float_status *status) { + FloatParts64 pa = float64_unpack_canonical(a, status); + FloatParts64 pb = float64_unpack_canonical(b, status); + FloatParts64 pc = float64_unpack_canonical(c, status); + FloatParts64 pr = parts64_muladd(&pa, &pb, &pc, flags, status); - float64_unpack_canonical(&pa, a, status); - float64_unpack_canonical(&pb, b, status); - float64_unpack_canonical(&pc, c, status); - pr = parts_muladd(&pa, &pb, &pc, flags, status); - - return float64_round_pack_canonical(pr, status); + /* Before rounding, scale. */ + if (scale) { + pr = parts64_scalbn(&pr, scale, status); + } + parts64_uncanon(&pr, status, &float64_params, false); + /* After rounding, apply negate result, especially for -0.0. */ + if ((flags & float_muladd_negate_result) && !is_nan(pr.cls)) { + pr.sign ^= 1; + } + return pack_raw64(&pr, &float64_params); } static bool force_soft_fma; @@ -1955,7 +1772,7 @@ float32 QEMU_FLATTEN float32_muladd(float32 xa, float32 xb, float32 xc, int flag if (unlikely(!can_use_fpu(s))) { goto soft; } - if (unlikely(flags & float_muladd_halve_result)) { + if (unlikely(flags & float_muladd_suppress_add_product_zero)) { goto soft; } @@ -2011,7 +1828,7 @@ float32 QEMU_FLATTEN float32_muladd(float32 xa, float32 xb, float32 xc, int flag return ur.s; soft: - return soft_f32_muladd(ua.s, ub.s, uc.s, flags, s); + return float32_muladd_scalbn(ua.s, ub.s, uc.s, 0, flags, s); } float64 QEMU_FLATTEN float64_muladd(float64 xa, float64 xb, float64 xc, int flags, float_status *s) { @@ -2024,9 +1841,6 @@ float64 QEMU_FLATTEN float64_muladd(float64 xa, float64 xb, float64 xc, int flag if (unlikely(!can_use_fpu(s))) { goto soft; } - if (unlikely(flags & float_muladd_halve_result)) { - goto soft; - } float64_input_flush3(&ua.s, &ub.s, &uc.s, s); if (unlikely(!f64_is_zon3(ua, ub, uc))) { @@ -2080,40 +1894,49 @@ float64 QEMU_FLATTEN float64_muladd(float64 xa, float64 xb, float64 xc, int flag return ur.s; soft: - return soft_f64_muladd(ua.s, ub.s, uc.s, flags, s); + return float64_muladd_scalbn(ua.s, ub.s, uc.s, 0, flags, s); } float64 float64r32_muladd(float64 a, float64 b, float64 c, int flags, float_status *status) { - FloatParts64 pa, pb, pc, *pr; - - float64_unpack_canonical(&pa, a, status); - float64_unpack_canonical(&pb, b, status); - float64_unpack_canonical(&pc, c, status); - pr = parts_muladd(&pa, &pb, &pc, flags, status); + FloatParts64 pa = float64_unpack_canonical(a, status); + FloatParts64 pb = float64_unpack_canonical(b, status); + FloatParts64 pc = float64_unpack_canonical(c, status); + FloatParts64 pr = parts64_muladd(&pa, &pb, &pc, flags, status); - return float64r32_round_pack_canonical(pr, status); + /* Round before applying negate result. */ + parts64_uncanon(&pr, status, &float32_params, false); + if ((flags & float_muladd_negate_result) && !is_nan(pr.cls)) { + pr.sign ^= 1; + } + return float64r32_pack_raw(&pr); } -bfloat16 QEMU_FLATTEN bfloat16_muladd(bfloat16 a, bfloat16 b, bfloat16 c, int flags, float_status *status) { - FloatParts64 pa, pb, pc, *pr; +bfloat16 bfloat16_muladd(bfloat16 a, bfloat16 b, bfloat16 c, int flags, float_status *status) { + FloatParts64 pa = bfloat16_unpack_canonical(a, status); + FloatParts64 pb = bfloat16_unpack_canonical(b, status); + FloatParts64 pc = bfloat16_unpack_canonical(c, status); + FloatParts64 pr = parts64_muladd(&pa, &pb, &pc, flags, status); - bfloat16_unpack_canonical(&pa, a, status); - bfloat16_unpack_canonical(&pb, b, status); - bfloat16_unpack_canonical(&pc, c, status); - pr = parts_muladd(&pa, &pb, &pc, flags, status); - - return bfloat16_round_pack_canonical(pr, status); + /* Round before applying negate result. */ + parts64_uncanon(&pr, status, &bfloat16_params, false); + if ((flags & float_muladd_negate_result) && !is_nan(pr.cls)) { + pr.sign ^= 1; + } + return pack_raw64(&pr, &bfloat16_params); } -float128 QEMU_FLATTEN float128_muladd(float128 a, float128 b, float128 c, int flags, float_status *status) { - FloatParts128 pa, pb, pc, *pr; +float128 float128_muladd(float128 a, float128 b, float128 c, int flags, float_status *status) { + FloatParts128 pa = float128_unpack_canonical(a, status); + FloatParts128 pb = float128_unpack_canonical(b, status); + FloatParts128 pc = float128_unpack_canonical(c, status); + FloatParts128 pr = parts128_muladd(&pa, &pb, &pc, flags, status); - float128_unpack_canonical(&pa, a, status); - float128_unpack_canonical(&pb, b, status); - float128_unpack_canonical(&pc, c, status); - pr = parts_muladd(&pa, &pb, &pc, flags, status); - - return float128_round_pack_canonical(pr, status); + /* Round before applying negate result. */ + parts128_uncanon(&pr, status, &float128_params, false); + if ((flags & float_muladd_negate_result) && !is_nan(pr.cls)) { + pr.sign ^= 1; + } + return float128_pack_raw(&pr); } /* @@ -2121,33 +1944,27 @@ float128 QEMU_FLATTEN float128_muladd(float128 a, float128 b, float128 c, int fl */ float16 float16_div(float16 a, float16 b, float_status *status) { - FloatParts64 pa, pb, *pr; + FloatParts64 pa = float16_unpack_canonical(a, status); + FloatParts64 pb = float16_unpack_canonical(b, status); + FloatParts64 pr = parts64_div(&pa, &pb, status); - float16_unpack_canonical(&pa, a, status); - float16_unpack_canonical(&pb, b, status); - pr = parts_div(&pa, &pb, status); - - return float16_round_pack_canonical(pr, status); + return float16_round_pack_canonical(&pr, status); } static float32 QEMU_SOFTFLOAT_ATTR soft_f32_div(float32 a, float32 b, float_status *status) { - FloatParts64 pa, pb, *pr; - - float32_unpack_canonical(&pa, a, status); - float32_unpack_canonical(&pb, b, status); - pr = parts_div(&pa, &pb, status); + FloatParts64 pa = float32_unpack_canonical(a, status); + FloatParts64 pb = float32_unpack_canonical(b, status); + FloatParts64 pr = parts64_div(&pa, &pb, status); - return float32_round_pack_canonical(pr, status); + return float32_round_pack_canonical(&pr, status); } static float64 QEMU_SOFTFLOAT_ATTR soft_f64_div(float64 a, float64 b, float_status *status) { - FloatParts64 pa, pb, *pr; - - float64_unpack_canonical(&pa, a, status); - float64_unpack_canonical(&pb, b, status); - pr = parts_div(&pa, &pb, status); + FloatParts64 pa = float64_unpack_canonical(a, status); + FloatParts64 pb = float64_unpack_canonical(b, status); + FloatParts64 pr = parts64_div(&pa, &pb, status); - return float64_round_pack_canonical(pr, status); + return float64_round_pack_canonical(&pr, status); } static float hard_f32_div(float a, float b) { @@ -2195,44 +2012,38 @@ float64 QEMU_FLATTEN float64_div(float64 a, float64 b, float_status *s) { } float64 float64r32_div(float64 a, float64 b, float_status *status) { - FloatParts64 pa, pb, *pr; - - float64_unpack_canonical(&pa, a, status); - float64_unpack_canonical(&pb, b, status); - pr = parts_div(&pa, &pb, status); + FloatParts64 pa = float64_unpack_canonical(a, status); + FloatParts64 pb = float64_unpack_canonical(b, status); + FloatParts64 pr = parts64_div(&pa, &pb, status); - return float64r32_round_pack_canonical(pr, status); + return float64r32_round_pack_canonical(&pr, status); } bfloat16 QEMU_FLATTEN bfloat16_div(bfloat16 a, bfloat16 b, float_status *status) { - FloatParts64 pa, pb, *pr; + FloatParts64 pa = bfloat16_unpack_canonical(a, status); + FloatParts64 pb = bfloat16_unpack_canonical(b, status); + FloatParts64 pr = parts64_div(&pa, &pb, status); - bfloat16_unpack_canonical(&pa, a, status); - bfloat16_unpack_canonical(&pb, b, status); - pr = parts_div(&pa, &pb, status); - - return bfloat16_round_pack_canonical(pr, status); + return bfloat16_round_pack_canonical(&pr, status); } float128 QEMU_FLATTEN float128_div(float128 a, float128 b, float_status *status) { - FloatParts128 pa, pb, *pr; - - float128_unpack_canonical(&pa, a, status); - float128_unpack_canonical(&pb, b, status); - pr = parts_div(&pa, &pb, status); + FloatParts128 pa = float128_unpack_canonical(a, status); + FloatParts128 pb = float128_unpack_canonical(b, status); + FloatParts128 pr = parts128_div(&pa, &pb, status); - return float128_round_pack_canonical(pr, status); + return float128_round_pack_canonical(&pr, status); } floatx80 floatx80_div(floatx80 a, floatx80 b, float_status *status) { - FloatParts128 pa, pb, *pr; + FloatParts128 pa, pb; if (!floatx80_unpack_canonical(&pa, a, status) || !floatx80_unpack_canonical(&pb, b, status)) { return floatx80_default_nan(status); } - pr = parts_div(&pa, &pb, status); - return floatx80_round_pack_canonical(pr, status); + pa = parts128_div(&pa, &pb, status); + return floatx80_round_pack_canonical(&pa, status); } /* @@ -2240,31 +2051,25 @@ floatx80 floatx80_div(floatx80 a, floatx80 b, float_status *status) { */ float32 float32_rem(float32 a, float32 b, float_status *status) { - FloatParts64 pa, pb, *pr; - - float32_unpack_canonical(&pa, a, status); - float32_unpack_canonical(&pb, b, status); - pr = parts_modrem(&pa, &pb, NULL, status); + FloatParts64 pa = float32_unpack_canonical(a, status); + FloatParts64 pb = float32_unpack_canonical(b, status); + FloatParts64 *pr = parts64_modrem(&pa, &pb, NULL, status); return float32_round_pack_canonical(pr, status); } float64 float64_rem(float64 a, float64 b, float_status *status) { - FloatParts64 pa, pb, *pr; - - float64_unpack_canonical(&pa, a, status); - float64_unpack_canonical(&pb, b, status); - pr = parts_modrem(&pa, &pb, NULL, status); + FloatParts64 pa = float64_unpack_canonical(a, status); + FloatParts64 pb = float64_unpack_canonical(b, status); + FloatParts64 *pr = parts64_modrem(&pa, &pb, NULL, status); return float64_round_pack_canonical(pr, status); } float128 float128_rem(float128 a, float128 b, float_status *status) { - FloatParts128 pa, pb, *pr; - - float128_unpack_canonical(&pa, a, status); - float128_unpack_canonical(&pb, b, status); - pr = parts_modrem(&pa, &pb, NULL, status); + FloatParts128 pa = float128_unpack_canonical(a, status); + FloatParts128 pb = float128_unpack_canonical(b, status); + FloatParts128 *pr = parts128_modrem(&pa, &pb, NULL, status); return float128_round_pack_canonical(pr, status); } @@ -2285,7 +2090,7 @@ floatx80 floatx80_modrem(floatx80 a, floatx80 b, bool mod, uint64_t *quotient, f if (!floatx80_unpack_canonical(&pa, a, status) || !floatx80_unpack_canonical(&pb, b, status)) { return floatx80_default_nan(status); } - pr = parts_modrem(&pa, &pb, mod ? quotient : NULL, status); + pr = parts128_modrem(&pa, &pb, mod ? quotient : NULL, status); return floatx80_round_pack_canonical(pr, status); } @@ -2336,6 +2141,9 @@ static void parts_float_to_ahp(FloatParts64 *a, float_status *s) { a->frac = MAKE_64BIT_MASK(float16_params_ahp.frac_shift, float16_params_ahp.frac_size + 1); break; + case float_class_denormal: + float_raise(float_flag_input_denormal_used, s); + break; case float_class_normal: case float_class_zero: break; @@ -2345,70 +2153,153 @@ static void parts_float_to_ahp(FloatParts64 *a, float_status *s) { } } +static void parts_float_to_e5m2(FloatParts64 *a, float_status *s, bool saturate) { + switch (a->cls) { + case float_class_snan: + case float_class_qnan: + *a = parts64_return_nan(a, s); + break; + + case float_class_inf: + /* Per OCP, conversion in SATURATE mode bounds Inf to MAX. */ + if (saturate) { + a->cls = float_class_normal; + a->exp = float8_e5m2_params.exp_max - 1; + a->frac = MAKE_64BIT_MASK(float8_e5m2_params.frac_shift, float8_e5m2_params.frac_size + 1); + } + break; + + case float_class_denormal: + float_raise(float_flag_input_denormal_used, s); + break; + case float_class_normal: + case float_class_zero: + break; + default: + g_assert_not_reached(); + } +} + static void parts64_float_to_float(FloatParts64 *a, float_status *s) { if (is_nan(a->cls)) { - parts_return_nan(a, s); + *a = parts64_return_nan(a, s); + } + if (a->cls == float_class_denormal) { + float_raise(float_flag_input_denormal_used, s); } } static void parts128_float_to_float(FloatParts128 *a, float_status *s) { if (is_nan(a->cls)) { - parts_return_nan(a, s); + *a = parts128_return_nan(a, s); + } + if (a->cls == float_class_denormal) { + float_raise(float_flag_input_denormal_used, s); } } -#define parts_float_to_float(P, S) PARTS_GENERIC_64_128(float_to_float, P)(P, S) - -static void parts_float_to_float_narrow(FloatParts64 *a, FloatParts128 *b, float_status *s) { - a->cls = b->cls; - a->sign = b->sign; - a->exp = b->exp; +static FloatParts64 parts128_to_parts64(FloatParts128 *b, float_status *s) { + FloatParts64 r = { + .cls = b->cls, + .sign = b->sign, + .exp = b->exp, + }; - if (a->cls == float_class_normal) { - frac_truncjam(a, b); - } else if (is_nan(a->cls)) { - /* Discard the low bits of the NaN. */ - a->frac = b->frac_hi; - parts_return_nan(a, s); + switch (r.cls) { + case float_class_denormal: + float_raise(float_flag_input_denormal_used, s); + /* fall through */ + case float_class_normal: + frac64_truncjam(&r, b); + break; + case float_class_snan: + case float_class_qnan: + /* Discard the low bits of the NaN. */ + r.frac = b->frac_hi; + r = parts64_return_nan(&r, s); + break; + default: + break; } + return r; } -static void parts_float_to_float_widen(FloatParts128 *a, FloatParts64 *b, float_status *s) { - a->cls = b->cls; - a->sign = b->sign; - a->exp = b->exp; - frac_widen(a, b); +static FloatParts128 parts64_to_parts128(FloatParts64 *b, float_status *s) { + FloatParts128 r = { + .cls = b->cls, + .sign = b->sign, + .exp = b->exp, + .frac_hi = b->frac, + }; - if (is_nan(a->cls)) { - parts_return_nan(a, s); + switch (r.cls) { + case float_class_qnan: + case float_class_snan: + r = parts128_return_nan(&r, s); + break; + case float_class_denormal: + float_raise(float_flag_input_denormal_used, s); + break; + default: + break; } + return r; +} + +float8_e4m3 float4_e2m1_to_float8_e4m3(float4_e2m1 a, float_status *s) { + FloatParts64 p = float4_e2m1_unpack_canonical(a, s); + parts64_float_to_float(&p, s); + return float8_e4m3_round_pack_canonical(&p, s, false); +} + +bfloat16 float8_e4m3_to_bfloat16(float8_e4m3 a, float_status *s) { + FloatParts64 p = float8_e4m3_unpack_canonical(a, s); + parts64_float_to_float(&p, s); + return bfloat16_round_pack_canonical(&p, s); +} + +bfloat16 float8_e5m2_to_bfloat16(float8_e5m2 a, float_status *s) { + FloatParts64 p = float8_e5m2_unpack_canonical(a, s); + parts64_float_to_float(&p, s); + return bfloat16_round_pack_canonical(&p, s); } float32 float16_to_float32(float16 a, bool ieee, float_status *s) { const FloatFmt *fmt16 = ieee ? &float16_params : &float16_params_ahp; - FloatParts64 p; + FloatParts64 p = float16a_unpack_canonical(a, s, fmt16); - float16a_unpack_canonical(&p, a, s, fmt16); - parts_float_to_float(&p, s); + parts64_float_to_float(&p, s); return float32_round_pack_canonical(&p, s); } float64 float16_to_float64(float16 a, bool ieee, float_status *s) { const FloatFmt *fmt16 = ieee ? &float16_params : &float16_params_ahp; - FloatParts64 p; + FloatParts64 p = float16a_unpack_canonical(a, s, fmt16); - float16a_unpack_canonical(&p, a, s, fmt16); - parts_float_to_float(&p, s); + parts64_float_to_float(&p, s); return float64_round_pack_canonical(&p, s); } +float8_e4m3 float32_to_float8_e4m3(float32 a, bool saturate, float_status *s) { + FloatParts64 p = float32_unpack_canonical(a, s); + + parts64_float_to_float(&p, s); + return float8_e4m3_round_pack_canonical(&p, s, saturate); +} + +float8_e5m2 float32_to_float8_e5m2(float32 a, bool saturate, float_status *s) { + FloatParts64 p = float32_unpack_canonical(a, s); + + parts_float_to_e5m2(&p, s, saturate); + return float8_e5m2_round_pack_canonical(&p, s, saturate); +} + float16 float32_to_float16(float32 a, bool ieee, float_status *s) { - FloatParts64 p; + FloatParts64 p = float32_unpack_canonical(a, s); const FloatFmt *fmt; - float32_unpack_canonical(&p, a, s); if (ieee) { - parts_float_to_float(&p, s); + parts64_float_to_float(&p, s); fmt = &float16_params; } else { parts_float_to_ahp(&p, s); @@ -2418,10 +2309,9 @@ float16 float32_to_float16(float32 a, bool ieee, float_status *s) { } static float64 QEMU_SOFTFLOAT_ATTR soft_float32_to_float64(float32 a, float_status *s) { - FloatParts64 p; + FloatParts64 p = float32_unpack_canonical(a, s); - float32_unpack_canonical(&p, a, s); - parts_float_to_float(&p, s); + parts64_float_to_float(&p, s); return float64_round_pack_canonical(&p, s); } @@ -2441,12 +2331,11 @@ float64 float32_to_float64(float32 a, float_status *s) { } float16 float64_to_float16(float64 a, bool ieee, float_status *s) { - FloatParts64 p; + FloatParts64 p = float64_unpack_canonical(a, s); const FloatFmt *fmt; - float64_unpack_canonical(&p, a, s); if (ieee) { - parts_float_to_float(&p, s); + parts64_float_to_float(&p, s); fmt = &float16_params; } else { parts_float_to_ahp(&p, s); @@ -2455,79 +2344,80 @@ float16 float64_to_float16(float64 a, bool ieee, float_status *s) { return float16a_round_pack_canonical(&p, s, fmt); } -float32 float64_to_float32(float64 a, float_status *s) { - FloatParts64 p; +float32 float64_to_float32(float64 a, float_status *s) { + FloatParts64 p = float64_unpack_canonical(a, s); + + parts64_float_to_float(&p, s); + return float32_round_pack_canonical(&p, s); +} + +float8_e4m3 bfloat16_to_float8_e4m3(bfloat16 a, bool saturate, float_status *s) { + FloatParts64 p = bfloat16_unpack_canonical(a, s); - float64_unpack_canonical(&p, a, s); - parts_float_to_float(&p, s); - return float32_round_pack_canonical(&p, s); + parts64_float_to_float(&p, s); + return float8_e4m3_round_pack_canonical(&p, s, saturate); +} + +float8_e5m2 bfloat16_to_float8_e5m2(bfloat16 a, bool saturate, float_status *s) { + FloatParts64 p = bfloat16_unpack_canonical(a, s); + + parts_float_to_e5m2(&p, s, saturate); + return float8_e5m2_round_pack_canonical(&p, s, saturate); } float32 bfloat16_to_float32(bfloat16 a, float_status *s) { - FloatParts64 p; + FloatParts64 p = bfloat16_unpack_canonical(a, s); - bfloat16_unpack_canonical(&p, a, s); - parts_float_to_float(&p, s); + parts64_float_to_float(&p, s); return float32_round_pack_canonical(&p, s); } float64 bfloat16_to_float64(bfloat16 a, float_status *s) { - FloatParts64 p; + FloatParts64 p = bfloat16_unpack_canonical(a, s); - bfloat16_unpack_canonical(&p, a, s); - parts_float_to_float(&p, s); + parts64_float_to_float(&p, s); return float64_round_pack_canonical(&p, s); } bfloat16 float32_to_bfloat16(float32 a, float_status *s) { - FloatParts64 p; + FloatParts64 p = float32_unpack_canonical(a, s); - float32_unpack_canonical(&p, a, s); - parts_float_to_float(&p, s); + parts64_float_to_float(&p, s); return bfloat16_round_pack_canonical(&p, s); } bfloat16 float64_to_bfloat16(float64 a, float_status *s) { - FloatParts64 p; + FloatParts64 p = float64_unpack_canonical(a, s); - float64_unpack_canonical(&p, a, s); - parts_float_to_float(&p, s); + parts64_float_to_float(&p, s); return bfloat16_round_pack_canonical(&p, s); } float32 float128_to_float32(float128 a, float_status *s) { - FloatParts64 p64; - FloatParts128 p128; + FloatParts128 p128 = float128_unpack_canonical(a, s); + FloatParts64 p64 = parts128_to_parts64(&p128, s); - float128_unpack_canonical(&p128, a, s); - parts_float_to_float_narrow(&p64, &p128, s); return float32_round_pack_canonical(&p64, s); } float64 float128_to_float64(float128 a, float_status *s) { - FloatParts64 p64; - FloatParts128 p128; + FloatParts128 p128 = float128_unpack_canonical(a, s); + FloatParts64 p64 = parts128_to_parts64(&p128, s); - float128_unpack_canonical(&p128, a, s); - parts_float_to_float_narrow(&p64, &p128, s); return float64_round_pack_canonical(&p64, s); } float128 float32_to_float128(float32 a, float_status *s) { - FloatParts64 p64; - FloatParts128 p128; + FloatParts64 p64 = float32_unpack_canonical(a, s); + FloatParts128 p128 = parts64_to_parts128(&p64, s); - float32_unpack_canonical(&p64, a, s); - parts_float_to_float_widen(&p128, &p64, s); return float128_round_pack_canonical(&p128, s); } float128 float64_to_float128(float64 a, float_status *s) { - FloatParts64 p64; - FloatParts128 p128; + FloatParts64 p64 = float64_unpack_canonical(a, s); + FloatParts128 p128 = parts64_to_parts128(&p64, s); - float64_unpack_canonical(&p64, a, s); - parts_float_to_float_widen(&p128, &p64, s); return float128_round_pack_canonical(&p128, s); } @@ -2536,9 +2426,9 @@ float32 floatx80_to_float32(floatx80 a, float_status *s) { FloatParts128 p128; if (floatx80_unpack_canonical(&p128, a, s)) { - parts_float_to_float_narrow(&p64, &p128, s); + p64 = parts128_to_parts64(&p128, s); } else { - parts_default_nan(&p64, s); + p64 = parts64_default_nan(s); } return float32_round_pack_canonical(&p64, s); } @@ -2548,9 +2438,9 @@ float64 floatx80_to_float64(floatx80 a, float_status *s) { FloatParts128 p128; if (floatx80_unpack_canonical(&p128, a, s)) { - parts_float_to_float_narrow(&p64, &p128, s); + p64 = parts128_to_parts64(&p128, s); } else { - parts_default_nan(&p64, s); + p64 = parts64_default_nan(s); } return float64_round_pack_canonical(&p64, s); } @@ -2559,36 +2449,31 @@ float128 floatx80_to_float128(floatx80 a, float_status *s) { FloatParts128 p; if (floatx80_unpack_canonical(&p, a, s)) { - parts_float_to_float(&p, s); + parts128_float_to_float(&p, s); } else { - parts_default_nan(&p, s); + p = parts128_default_nan(s); } return float128_round_pack_canonical(&p, s); } floatx80 float32_to_floatx80(float32 a, float_status *s) { - FloatParts64 p64; - FloatParts128 p128; + FloatParts64 p64 = float32_unpack_canonical(a, s); + FloatParts128 p128 = parts64_to_parts128(&p64, s); - float32_unpack_canonical(&p64, a, s); - parts_float_to_float_widen(&p128, &p64, s); return floatx80_round_pack_canonical(&p128, s); } floatx80 float64_to_floatx80(float64 a, float_status *s) { - FloatParts64 p64; - FloatParts128 p128; + FloatParts64 p64 = float64_unpack_canonical(a, s); + FloatParts128 p128 = parts64_to_parts128(&p64, s); - float64_unpack_canonical(&p64, a, s); - parts_float_to_float_widen(&p128, &p64, s); return floatx80_round_pack_canonical(&p128, s); } floatx80 float128_to_floatx80(float128 a, float_status *s) { - FloatParts128 p; + FloatParts128 p = float128_unpack_canonical(a, s); - float128_unpack_canonical(&p, a, s); - parts_float_to_float(&p, s); + parts128_float_to_float(&p, s); return floatx80_round_pack_canonical(&p, s); } @@ -2597,42 +2482,37 @@ floatx80 float128_to_floatx80(float128 a, float_status *s) { */ float16 float16_round_to_int(float16 a, float_status *s) { - FloatParts64 p; + FloatParts64 p = float16_unpack_canonical(a, s); - float16_unpack_canonical(&p, a, s); - parts_round_to_int(&p, s->float_rounding_mode, 0, s, &float16_params); + p = parts64_round_to_int(&p, get_float_rounding_mode(s), 0, s, &float16_params); return float16_round_pack_canonical(&p, s); } float32 float32_round_to_int(float32 a, float_status *s) { - FloatParts64 p; + FloatParts64 p = float32_unpack_canonical(a, s); - float32_unpack_canonical(&p, a, s); - parts_round_to_int(&p, s->float_rounding_mode, 0, s, &float32_params); + p = parts64_round_to_int(&p, get_float_rounding_mode(s), 0, s, &float32_params); return float32_round_pack_canonical(&p, s); } float64 float64_round_to_int(float64 a, float_status *s) { - FloatParts64 p; + FloatParts64 p = float64_unpack_canonical(a, s); - float64_unpack_canonical(&p, a, s); - parts_round_to_int(&p, s->float_rounding_mode, 0, s, &float64_params); + p = parts64_round_to_int(&p, get_float_rounding_mode(s), 0, s, &float64_params); return float64_round_pack_canonical(&p, s); } bfloat16 bfloat16_round_to_int(bfloat16 a, float_status *s) { - FloatParts64 p; + FloatParts64 p = bfloat16_unpack_canonical(a, s); - bfloat16_unpack_canonical(&p, a, s); - parts_round_to_int(&p, s->float_rounding_mode, 0, s, &bfloat16_params); + p = parts64_round_to_int(&p, get_float_rounding_mode(s), 0, s, &bfloat16_params); return bfloat16_round_pack_canonical(&p, s); } float128 float128_round_to_int(float128 a, float_status *s) { - FloatParts128 p; + FloatParts128 p = float128_unpack_canonical(a, s); - float128_unpack_canonical(&p, a, s); - parts_round_to_int(&p, s->float_rounding_mode, 0, s, &float128_params); + p = parts128_round_to_int(&p, get_float_rounding_mode(s), 0, s, &float128_params); return float128_round_pack_canonical(&p, s); } @@ -2643,8 +2523,8 @@ floatx80 floatx80_round_to_int(floatx80 a, float_status *status) { return floatx80_default_nan(status); } - parts_round_to_int(&p, status->float_rounding_mode, 0, status, - &floatx80_params[status->floatx80_rounding_precision]); + p = parts128_round_to_int(&p, get_float_rounding_mode(status), 0, status, + &floatx80_params[get_floatx80_rounding_precision(status)]); return floatx80_round_pack_canonical(&p, status); } @@ -2653,116 +2533,89 @@ floatx80 floatx80_round_to_int(floatx80 a, float_status *status) { */ int8_t float16_to_int8_scalbn(float16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float16_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT8_MIN, INT8_MAX, s); + FloatParts64 p = float16_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT8_MIN, INT8_MAX, s); } int16_t float16_to_int16_scalbn(float16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float16_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT16_MIN, INT16_MAX, s); + FloatParts64 p = float16_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT16_MIN, INT16_MAX, s); } int32_t float16_to_int32_scalbn(float16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float16_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); + FloatParts64 p = float16_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); } int64_t float16_to_int64_scalbn(float16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float16_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); + FloatParts64 p = float16_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); } int16_t float32_to_int16_scalbn(float32 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float32_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT16_MIN, INT16_MAX, s); + FloatParts64 p = float32_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT16_MIN, INT16_MAX, s); } int32_t float32_to_int32_scalbn(float32 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float32_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); + FloatParts64 p = float32_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); } int64_t float32_to_int64_scalbn(float32 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float32_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); + FloatParts64 p = float32_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); } int16_t float64_to_int16_scalbn(float64 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float64_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT16_MIN, INT16_MAX, s); + FloatParts64 p = float64_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT16_MIN, INT16_MAX, s); } int32_t float64_to_int32_scalbn(float64 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float64_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); + FloatParts64 p = float64_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); } int64_t float64_to_int64_scalbn(float64 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; + FloatParts64 p = float64_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); +} - float64_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); +int8_t bfloat16_to_int8_scalbn(bfloat16 a, FloatRoundMode rmode, int scale, float_status *s) { + FloatParts64 p = bfloat16_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT8_MIN, INT8_MAX, s); } int16_t bfloat16_to_int16_scalbn(bfloat16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - bfloat16_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT16_MIN, INT16_MAX, s); + FloatParts64 p = bfloat16_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT16_MIN, INT16_MAX, s); } int32_t bfloat16_to_int32_scalbn(bfloat16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - bfloat16_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); + FloatParts64 p = bfloat16_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); } int64_t bfloat16_to_int64_scalbn(bfloat16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - bfloat16_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); + FloatParts64 p = bfloat16_unpack_canonical(a, s); + return parts64_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); } static int32_t float128_to_int32_scalbn(float128 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts128 p; - - float128_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); + FloatParts128 p = float128_unpack_canonical(a, s); + return parts128_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); } static int64_t float128_to_int64_scalbn(float128 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts128 p; - - float128_unpack_canonical(&p, a, s); - return parts_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); + FloatParts128 p = float128_unpack_canonical(a, s); + return parts128_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); } static Int128 float128_to_int128_scalbn(float128 a, FloatRoundMode rmode, int scale, float_status *s) { - int flags = 0; + FloatExceptionFlags flags = 0; Int128 r; - FloatParts128 p; - - float128_unpack_canonical(&p, a, s); + FloatParts128 p = float128_unpack_canonical(a, s); switch (p.cls) { case float_class_snan: @@ -2782,7 +2635,8 @@ static Int128 float128_to_int128_scalbn(float128 a, FloatRoundMode rmode, int sc return int128_zero(); case float_class_normal: - if (parts_round_to_int_normal(&p, rmode, scale, 128 - 2)) { + case float_class_denormal: + if (parts128_round_to_int_normal(&p, rmode, scale, 128 - 2)) { flags = float_flag_inexact; } @@ -2812,78 +2666,78 @@ static int32_t floatx80_to_int32_scalbn(floatx80 a, FloatRoundMode rmode, int sc FloatParts128 p; if (!floatx80_unpack_canonical(&p, a, s)) { - parts_default_nan(&p, s); + p = parts128_default_nan(s); } - return parts_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); + return parts128_float_to_sint(&p, rmode, scale, INT32_MIN, INT32_MAX, s); } static int64_t floatx80_to_int64_scalbn(floatx80 a, FloatRoundMode rmode, int scale, float_status *s) { FloatParts128 p; if (!floatx80_unpack_canonical(&p, a, s)) { - parts_default_nan(&p, s); + p = parts128_default_nan(s); } - return parts_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); + return parts128_float_to_sint(&p, rmode, scale, INT64_MIN, INT64_MAX, s); } int8_t float16_to_int8(float16 a, float_status *s) { - return float16_to_int8_scalbn(a, s->float_rounding_mode, 0, s); + return float16_to_int8_scalbn(a, get_float_rounding_mode(s), 0, s); } int16_t float16_to_int16(float16 a, float_status *s) { - return float16_to_int16_scalbn(a, s->float_rounding_mode, 0, s); + return float16_to_int16_scalbn(a, get_float_rounding_mode(s), 0, s); } int32_t float16_to_int32(float16 a, float_status *s) { - return float16_to_int32_scalbn(a, s->float_rounding_mode, 0, s); + return float16_to_int32_scalbn(a, get_float_rounding_mode(s), 0, s); } int64_t float16_to_int64(float16 a, float_status *s) { - return float16_to_int64_scalbn(a, s->float_rounding_mode, 0, s); + return float16_to_int64_scalbn(a, get_float_rounding_mode(s), 0, s); } int16_t float32_to_int16(float32 a, float_status *s) { - return float32_to_int16_scalbn(a, s->float_rounding_mode, 0, s); + return float32_to_int16_scalbn(a, get_float_rounding_mode(s), 0, s); } int32_t float32_to_int32(float32 a, float_status *s) { - return float32_to_int32_scalbn(a, s->float_rounding_mode, 0, s); + return float32_to_int32_scalbn(a, get_float_rounding_mode(s), 0, s); } int64_t float32_to_int64(float32 a, float_status *s) { - return float32_to_int64_scalbn(a, s->float_rounding_mode, 0, s); + return float32_to_int64_scalbn(a, get_float_rounding_mode(s), 0, s); } int16_t float64_to_int16(float64 a, float_status *s) { - return float64_to_int16_scalbn(a, s->float_rounding_mode, 0, s); + return float64_to_int16_scalbn(a, get_float_rounding_mode(s), 0, s); } int32_t float64_to_int32(float64 a, float_status *s) { - return float64_to_int32_scalbn(a, s->float_rounding_mode, 0, s); + return float64_to_int32_scalbn(a, get_float_rounding_mode(s), 0, s); } int64_t float64_to_int64(float64 a, float_status *s) { - return float64_to_int64_scalbn(a, s->float_rounding_mode, 0, s); + return float64_to_int64_scalbn(a, get_float_rounding_mode(s), 0, s); } int32_t float128_to_int32(float128 a, float_status *s) { - return float128_to_int32_scalbn(a, s->float_rounding_mode, 0, s); + return float128_to_int32_scalbn(a, get_float_rounding_mode(s), 0, s); } int64_t float128_to_int64(float128 a, float_status *s) { - return float128_to_int64_scalbn(a, s->float_rounding_mode, 0, s); + return float128_to_int64_scalbn(a, get_float_rounding_mode(s), 0, s); } Int128 float128_to_int128(float128 a, float_status *s) { - return float128_to_int128_scalbn(a, s->float_rounding_mode, 0, s); + return float128_to_int128_scalbn(a, get_float_rounding_mode(s), 0, s); } int32_t floatx80_to_int32(floatx80 a, float_status *s) { - return floatx80_to_int32_scalbn(a, s->float_rounding_mode, 0, s); + return floatx80_to_int32_scalbn(a, get_float_rounding_mode(s), 0, s); } int64_t floatx80_to_int64(floatx80 a, float_status *s) { - return floatx80_to_int64_scalbn(a, s->float_rounding_mode, 0, s); + return floatx80_to_int64_scalbn(a, get_float_rounding_mode(s), 0, s); } int16_t float16_to_int16_round_to_zero(float16 a, float_status *s) { @@ -2942,16 +2796,24 @@ int64_t floatx80_to_int64_round_to_zero(floatx80 a, float_status *s) { return floatx80_to_int64_scalbn(a, float_round_to_zero, 0, s); } +int8_t bfloat16_to_int8(bfloat16 a, float_status *s) { + return bfloat16_to_int8_scalbn(a, get_float_rounding_mode(s), 0, s); +} + int16_t bfloat16_to_int16(bfloat16 a, float_status *s) { - return bfloat16_to_int16_scalbn(a, s->float_rounding_mode, 0, s); + return bfloat16_to_int16_scalbn(a, get_float_rounding_mode(s), 0, s); } int32_t bfloat16_to_int32(bfloat16 a, float_status *s) { - return bfloat16_to_int32_scalbn(a, s->float_rounding_mode, 0, s); + return bfloat16_to_int32_scalbn(a, get_float_rounding_mode(s), 0, s); } int64_t bfloat16_to_int64(bfloat16 a, float_status *s) { - return bfloat16_to_int64_scalbn(a, s->float_rounding_mode, 0, s); + return bfloat16_to_int64_scalbn(a, get_float_rounding_mode(s), 0, s); +} + +int8_t bfloat16_to_int8_round_to_zero(bfloat16 a, float_status *s) { + return bfloat16_to_int8_scalbn(a, float_round_to_zero, 0, s); } int16_t bfloat16_to_int16_round_to_zero(bfloat16 a, float_status *s) { @@ -2966,18 +2828,81 @@ int64_t bfloat16_to_int64_round_to_zero(bfloat16 a, float_status *s) { return bfloat16_to_int64_scalbn(a, float_round_to_zero, 0, s); } -int32_t float64_to_int32_modulo(float64 a, FloatRoundMode rmode, float_status *s) { - FloatParts64 p; +/* + * Like partsN(float_to_sint), except do not saturate the result. + * Instead, return the rounded unbounded precision two's compliment result, + * modulo 2**(bitsm1 + 1). + */ +static int64_t parts64_float_to_sint_modulo(FloatParts64 *p, FloatRoundMode rmode, int bitsm1, float_status *s) { + int flags = 0; + uint64_t r; + bool overflow = false; + + switch (p->cls) { + case float_class_snan: + flags |= float_flag_invalid_snan; + /* fall through */ + case float_class_qnan: + flags |= float_flag_invalid; + r = 0; + break; + + case float_class_inf: + overflow = true; + r = 0; + break; + + case float_class_zero: + return 0; + + case float_class_normal: + case float_class_denormal: + /* TODO: 64 - 2 is frac_size for rounding; could use input fmt. */ + if (parts64_round_to_int_normal(p, rmode, 0, 64 - 2)) { + flags = float_flag_inexact; + } + + if (p->exp <= DECOMPOSED_BINARY_POINT) { + r = p->frac >> (DECOMPOSED_BINARY_POINT - p->exp); + if (p->exp < bitsm1) { + /* Result in range. */ + } else if (p->exp == bitsm1) { + /* The only in-range value is INT_MIN. */ + overflow = !p->sign || p->frac != DECOMPOSED_IMPLICIT_BIT; + } else { + overflow = true; + } + } else { + /* Overflow, but there might still be bits to return. */ + int shl = p->exp - DECOMPOSED_BINARY_POINT; + r = (shl < 64 ? p->frac << shl : 0); + overflow = true; + } + + if (p->sign) { + r = -r; + } + break; + + default: + g_assert_not_reached(); + } - float64_unpack_canonical(&p, a, s); - return parts_float_to_sint_modulo(&p, rmode, 31, s); + if (overflow) { + flags = float_flag_invalid | float_flag_invalid_cvti; + } + float_raise(flags, s); + return r; } -int64_t float64_to_int64_modulo(float64 a, FloatRoundMode rmode, float_status *s) { - FloatParts64 p; +int32_t float64_to_int32_modulo(float64 a, FloatRoundMode rmode, float_status *s) { + FloatParts64 p = float64_unpack_canonical(a, s); + return parts64_float_to_sint_modulo(&p, rmode, 31, s); +} - float64_unpack_canonical(&p, a, s); - return parts_float_to_sint_modulo(&p, rmode, 63, s); +int64_t float64_to_int64_modulo(float64 a, FloatRoundMode rmode, float_status *s) { + FloatParts64 p = float64_unpack_canonical(a, s); + return parts64_float_to_sint_modulo(&p, rmode, 63, s); } /* @@ -2985,116 +2910,89 @@ int64_t float64_to_int64_modulo(float64 a, FloatRoundMode rmode, float_status *s */ uint8_t float16_to_uint8_scalbn(float16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float16_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT8_MAX, s); + FloatParts64 p = float16_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT8_MAX, s); } uint16_t float16_to_uint16_scalbn(float16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float16_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT16_MAX, s); + FloatParts64 p = float16_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT16_MAX, s); } uint32_t float16_to_uint32_scalbn(float16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float16_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT32_MAX, s); + FloatParts64 p = float16_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT32_MAX, s); } uint64_t float16_to_uint64_scalbn(float16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float16_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT64_MAX, s); + FloatParts64 p = float16_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT64_MAX, s); } uint16_t float32_to_uint16_scalbn(float32 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float32_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT16_MAX, s); + FloatParts64 p = float32_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT16_MAX, s); } uint32_t float32_to_uint32_scalbn(float32 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float32_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT32_MAX, s); + FloatParts64 p = float32_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT32_MAX, s); } uint64_t float32_to_uint64_scalbn(float32 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float32_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT64_MAX, s); + FloatParts64 p = float32_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT64_MAX, s); } uint16_t float64_to_uint16_scalbn(float64 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float64_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT16_MAX, s); + FloatParts64 p = float64_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT16_MAX, s); } uint32_t float64_to_uint32_scalbn(float64 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - float64_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT32_MAX, s); + FloatParts64 p = float64_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT32_MAX, s); } uint64_t float64_to_uint64_scalbn(float64 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; + FloatParts64 p = float64_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT64_MAX, s); +} - float64_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT64_MAX, s); +uint8_t bfloat16_to_uint8_scalbn(bfloat16 a, FloatRoundMode rmode, int scale, float_status *s) { + FloatParts64 p = bfloat16_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT8_MAX, s); } uint16_t bfloat16_to_uint16_scalbn(bfloat16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - bfloat16_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT16_MAX, s); + FloatParts64 p = bfloat16_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT16_MAX, s); } uint32_t bfloat16_to_uint32_scalbn(bfloat16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - bfloat16_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT32_MAX, s); + FloatParts64 p = bfloat16_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT32_MAX, s); } uint64_t bfloat16_to_uint64_scalbn(bfloat16 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts64 p; - - bfloat16_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT64_MAX, s); + FloatParts64 p = bfloat16_unpack_canonical(a, s); + return parts64_float_to_uint(&p, rmode, scale, UINT64_MAX, s); } static uint32_t float128_to_uint32_scalbn(float128 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts128 p; - - float128_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT32_MAX, s); + FloatParts128 p = float128_unpack_canonical(a, s); + return parts128_float_to_uint(&p, rmode, scale, UINT32_MAX, s); } static uint64_t float128_to_uint64_scalbn(float128 a, FloatRoundMode rmode, int scale, float_status *s) { - FloatParts128 p; - - float128_unpack_canonical(&p, a, s); - return parts_float_to_uint(&p, rmode, scale, UINT64_MAX, s); + FloatParts128 p = float128_unpack_canonical(a, s); + return parts128_float_to_uint(&p, rmode, scale, UINT64_MAX, s); } static Int128 float128_to_uint128_scalbn(float128 a, FloatRoundMode rmode, int scale, float_status *s) { int flags = 0; Int128 r; - FloatParts128 p; - - float128_unpack_canonical(&p, a, s); + FloatParts128 p = float128_unpack_canonical(a, s); switch (p.cls) { case float_class_snan: @@ -3114,7 +3012,8 @@ static Int128 float128_to_uint128_scalbn(float128 a, FloatRoundMode rmode, int s return int128_zero(); case float_class_normal: - if (parts_round_to_int_normal(&p, rmode, scale, 128 - 2)) { + case float_class_denormal: + if (parts128_round_to_int_normal(&p, rmode, scale, 128 - 2)) { flags = float_flag_inexact; if (p.cls == float_class_zero) { r = int128_zero(); @@ -3143,55 +3042,55 @@ static Int128 float128_to_uint128_scalbn(float128 a, FloatRoundMode rmode, int s } uint8_t float16_to_uint8(float16 a, float_status *s) { - return float16_to_uint8_scalbn(a, s->float_rounding_mode, 0, s); + return float16_to_uint8_scalbn(a, get_float_rounding_mode(s), 0, s); } uint16_t float16_to_uint16(float16 a, float_status *s) { - return float16_to_uint16_scalbn(a, s->float_rounding_mode, 0, s); + return float16_to_uint16_scalbn(a, get_float_rounding_mode(s), 0, s); } uint32_t float16_to_uint32(float16 a, float_status *s) { - return float16_to_uint32_scalbn(a, s->float_rounding_mode, 0, s); + return float16_to_uint32_scalbn(a, get_float_rounding_mode(s), 0, s); } uint64_t float16_to_uint64(float16 a, float_status *s) { - return float16_to_uint64_scalbn(a, s->float_rounding_mode, 0, s); + return float16_to_uint64_scalbn(a, get_float_rounding_mode(s), 0, s); } uint16_t float32_to_uint16(float32 a, float_status *s) { - return float32_to_uint16_scalbn(a, s->float_rounding_mode, 0, s); + return float32_to_uint16_scalbn(a, get_float_rounding_mode(s), 0, s); } uint32_t float32_to_uint32(float32 a, float_status *s) { - return float32_to_uint32_scalbn(a, s->float_rounding_mode, 0, s); + return float32_to_uint32_scalbn(a, get_float_rounding_mode(s), 0, s); } uint64_t float32_to_uint64(float32 a, float_status *s) { - return float32_to_uint64_scalbn(a, s->float_rounding_mode, 0, s); + return float32_to_uint64_scalbn(a, get_float_rounding_mode(s), 0, s); } uint16_t float64_to_uint16(float64 a, float_status *s) { - return float64_to_uint16_scalbn(a, s->float_rounding_mode, 0, s); + return float64_to_uint16_scalbn(a, get_float_rounding_mode(s), 0, s); } uint32_t float64_to_uint32(float64 a, float_status *s) { - return float64_to_uint32_scalbn(a, s->float_rounding_mode, 0, s); + return float64_to_uint32_scalbn(a, get_float_rounding_mode(s), 0, s); } uint64_t float64_to_uint64(float64 a, float_status *s) { - return float64_to_uint64_scalbn(a, s->float_rounding_mode, 0, s); + return float64_to_uint64_scalbn(a, get_float_rounding_mode(s), 0, s); } uint32_t float128_to_uint32(float128 a, float_status *s) { - return float128_to_uint32_scalbn(a, s->float_rounding_mode, 0, s); + return float128_to_uint32_scalbn(a, get_float_rounding_mode(s), 0, s); } uint64_t float128_to_uint64(float128 a, float_status *s) { - return float128_to_uint64_scalbn(a, s->float_rounding_mode, 0, s); + return float128_to_uint64_scalbn(a, get_float_rounding_mode(s), 0, s); } Int128 float128_to_uint128(float128 a, float_status *s) { - return float128_to_uint128_scalbn(a, s->float_rounding_mode, 0, s); + return float128_to_uint128_scalbn(a, get_float_rounding_mode(s), 0, s); } uint16_t float16_to_uint16_round_to_zero(float16 a, float_status *s) { @@ -3242,16 +3141,24 @@ Int128 float128_to_uint128_round_to_zero(float128 a, float_status *s) { return float128_to_uint128_scalbn(a, float_round_to_zero, 0, s); } +uint8_t bfloat16_to_uint8(bfloat16 a, float_status *s) { + return bfloat16_to_uint8_scalbn(a, get_float_rounding_mode(s), 0, s); +} + uint16_t bfloat16_to_uint16(bfloat16 a, float_status *s) { - return bfloat16_to_uint16_scalbn(a, s->float_rounding_mode, 0, s); + return bfloat16_to_uint16_scalbn(a, get_float_rounding_mode(s), 0, s); } uint32_t bfloat16_to_uint32(bfloat16 a, float_status *s) { - return bfloat16_to_uint32_scalbn(a, s->float_rounding_mode, 0, s); + return bfloat16_to_uint32_scalbn(a, get_float_rounding_mode(s), 0, s); } uint64_t bfloat16_to_uint64(bfloat16 a, float_status *s) { - return bfloat16_to_uint64_scalbn(a, s->float_rounding_mode, 0, s); + return bfloat16_to_uint64_scalbn(a, get_float_rounding_mode(s), 0, s); +} + +uint8_t bfloat16_to_uint8_round_to_zero(bfloat16 a, float_status *s) { + return bfloat16_to_uint8_scalbn(a, float_round_to_zero, 0, s); } uint16_t bfloat16_to_uint16_round_to_zero(bfloat16 a, float_status *s) { @@ -3273,7 +3180,7 @@ uint64_t bfloat16_to_uint64_round_to_zero(bfloat16 a, float_status *s) { float16 int64_to_float16_scalbn(int64_t a, int scale, float_status *status) { FloatParts64 p; - parts_sint_to_float(&p, a, scale, status); + parts64_sint_to_float(&p, a, scale, status); return float16_round_pack_canonical(&p, status); } @@ -3345,7 +3252,7 @@ float64 int64_to_float64_scalbn(int64_t a, int scale, float_status *status) { return ur.s; } - parts_sint_to_float(&p, a, scale, status); + parts64_sint_to_float(&p, a, scale, status); return float64_round_pack_canonical(&p, status); } @@ -3372,7 +3279,7 @@ float64 int16_to_float64(int16_t a, float_status *status) { bfloat16 int64_to_bfloat16_scalbn(int64_t a, int scale, float_status *status) { FloatParts64 p; - parts_sint_to_float(&p, a, scale, status); + parts64_sint_to_float(&p, a, scale, status); return bfloat16_round_pack_canonical(&p, status); } @@ -3384,6 +3291,10 @@ bfloat16 int16_to_bfloat16_scalbn(int16_t a, int scale, float_status *status) { return int64_to_bfloat16_scalbn(a, scale, status); } +bfloat16 int8_to_bfloat16_scalbn(int8_t a, int scale, float_status *status) { + return int64_to_bfloat16_scalbn(a, scale, status); +} + bfloat16 int64_to_bfloat16(int64_t a, float_status *status) { return int64_to_bfloat16_scalbn(a, 0, status); } @@ -3396,6 +3307,10 @@ bfloat16 int16_to_bfloat16(int16_t a, float_status *status) { return int64_to_bfloat16_scalbn(a, 0, status); } +bfloat16 int8_to_bfloat16(int8_t a, float_status *status) { + return int64_to_bfloat16_scalbn(a, 0, status); +} + float128 int128_to_float128(Int128 a, float_status *status) { FloatParts128 p = {}; int shift; @@ -3427,7 +3342,7 @@ float128 int128_to_float128(Int128 a, float_status *status) { float128 int64_to_float128(int64_t a, float_status *status) { FloatParts128 p; - parts_sint_to_float(&p, a, 0, status); + parts128_sint_to_float(&p, a, 0, status); return float128_round_pack_canonical(&p, status); } @@ -3438,7 +3353,7 @@ float128 int32_to_float128(int32_t a, float_status *status) { floatx80 int64_to_floatx80(int64_t a, float_status *status) { FloatParts128 p; - parts_sint_to_float(&p, a, 0, status); + parts128_sint_to_float(&p, a, 0, status); return floatx80_round_pack_canonical(&p, status); } @@ -3453,7 +3368,7 @@ floatx80 int32_to_floatx80(int32_t a, float_status *status) { float16 uint64_to_float16_scalbn(uint64_t a, int scale, float_status *status) { FloatParts64 p; - parts_uint_to_float(&p, a, scale, status); + parts64_uint_to_float(&p, a, scale, status); return float16_round_pack_canonical(&p, status); } @@ -3491,7 +3406,7 @@ float32 uint64_to_float32_scalbn(uint64_t a, int scale, float_status *status) { return ur.s; } - parts_uint_to_float(&p, a, scale, status); + parts64_uint_to_float(&p, a, scale, status); return float32_round_pack_canonical(&p, status); } @@ -3525,7 +3440,7 @@ float64 uint64_to_float64_scalbn(uint64_t a, int scale, float_status *status) { return ur.s; } - parts_uint_to_float(&p, a, scale, status); + parts64_uint_to_float(&p, a, scale, status); return float64_round_pack_canonical(&p, status); } @@ -3552,7 +3467,7 @@ float64 uint16_to_float64(uint16_t a, float_status *status) { bfloat16 uint64_to_bfloat16_scalbn(uint64_t a, int scale, float_status *status) { FloatParts64 p; - parts_uint_to_float(&p, a, scale, status); + parts64_uint_to_float(&p, a, scale, status); return bfloat16_round_pack_canonical(&p, status); } @@ -3564,6 +3479,10 @@ bfloat16 uint16_to_bfloat16_scalbn(uint16_t a, int scale, float_status *status) return uint64_to_bfloat16_scalbn(a, scale, status); } +bfloat16 uint8_to_bfloat16_scalbn(uint8_t a, int scale, float_status *status) { + return uint64_to_bfloat16_scalbn(a, scale, status); +} + bfloat16 uint64_to_bfloat16(uint64_t a, float_status *status) { return uint64_to_bfloat16_scalbn(a, 0, status); } @@ -3576,10 +3495,14 @@ bfloat16 uint16_to_bfloat16(uint16_t a, float_status *status) { return uint64_to_bfloat16_scalbn(a, 0, status); } +bfloat16 uint8_to_bfloat16(uint8_t a, float_status *status) { + return uint64_to_bfloat16_scalbn(a, 0, status); +} + float128 uint64_to_float128(uint64_t a, float_status *status) { FloatParts128 p; - parts_uint_to_float(&p, a, 0, status); + parts128_uint_to_float(&p, a, 0, status); return float128_round_pack_canonical(&p, status); } @@ -3611,90 +3534,55 @@ float128 uint128_to_float128(Int128 a, float_status *status) { * Minimum and maximum */ -static float16 float16_minmax(float16 a, float16 b, float_status *s, int flags) { - FloatParts64 pa, pb, *pr; - - float16_unpack_canonical(&pa, a, s); - float16_unpack_canonical(&pb, b, s); - pr = parts_minmax(&pa, &pb, s, flags); +float16 float16_minmax(float16 a, float16 b, float_status *s, int flags) { + FloatParts64 pa = float16_unpack_canonical(a, s); + FloatParts64 pb = float16_unpack_canonical(b, s); + FloatParts64 *pr = parts64_minmax(&pa, &pb, s, flags); return float16_round_pack_canonical(pr, s); } -static bfloat16 bfloat16_minmax(bfloat16 a, bfloat16 b, float_status *s, int flags) { - FloatParts64 pa, pb, *pr; - - bfloat16_unpack_canonical(&pa, a, s); - bfloat16_unpack_canonical(&pb, b, s); - pr = parts_minmax(&pa, &pb, s, flags); +bfloat16 bfloat16_minmax(bfloat16 a, bfloat16 b, float_status *s, int flags) { + FloatParts64 pa = bfloat16_unpack_canonical(a, s); + FloatParts64 pb = bfloat16_unpack_canonical(b, s); + FloatParts64 *pr = parts64_minmax(&pa, &pb, s, flags); return bfloat16_round_pack_canonical(pr, s); } -static float32 float32_minmax(float32 a, float32 b, float_status *s, int flags) { - FloatParts64 pa, pb, *pr; - - float32_unpack_canonical(&pa, a, s); - float32_unpack_canonical(&pb, b, s); - pr = parts_minmax(&pa, &pb, s, flags); +float32 float32_minmax(float32 a, float32 b, float_status *s, int flags) { + FloatParts64 pa = float32_unpack_canonical(a, s); + FloatParts64 pb = float32_unpack_canonical(b, s); + FloatParts64 *pr = parts64_minmax(&pa, &pb, s, flags); return float32_round_pack_canonical(pr, s); } -static float64 float64_minmax(float64 a, float64 b, float_status *s, int flags) { - FloatParts64 pa, pb, *pr; - - float64_unpack_canonical(&pa, a, s); - float64_unpack_canonical(&pb, b, s); - pr = parts_minmax(&pa, &pb, s, flags); +float64 float64_minmax(float64 a, float64 b, float_status *s, int flags) { + FloatParts64 pa = float64_unpack_canonical(a, s); + FloatParts64 pb = float64_unpack_canonical(b, s); + FloatParts64 *pr = parts64_minmax(&pa, &pb, s, flags); return float64_round_pack_canonical(pr, s); } -static float128 float128_minmax(float128 a, float128 b, float_status *s, int flags) { - FloatParts128 pa, pb, *pr; - - float128_unpack_canonical(&pa, a, s); - float128_unpack_canonical(&pb, b, s); - pr = parts_minmax(&pa, &pb, s, flags); +float128 float128_minmax(float128 a, float128 b, float_status *s, int flags) { + FloatParts128 pa = float128_unpack_canonical(a, s); + FloatParts128 pb = float128_unpack_canonical(b, s); + FloatParts128 *pr = parts128_minmax(&pa, &pb, s, flags); return float128_round_pack_canonical(pr, s); } -#define MINMAX_1(type, name, flags) \ - type type##_##name(type a, type b, float_status *s) { \ - return type##_minmax(a, b, s, flags); \ - } - -#define MINMAX_2(type) \ - MINMAX_1(type, max, 0) \ - MINMAX_1(type, maxnum, minmax_isnum) \ - MINMAX_1(type, maxnummag, minmax_isnum | minmax_ismag) \ - MINMAX_1(type, maximum_number, minmax_isnumber) \ - MINMAX_1(type, min, minmax_ismin) \ - MINMAX_1(type, minnum, minmax_ismin | minmax_isnum) \ - MINMAX_1(type, minnummag, minmax_ismin | minmax_isnum | minmax_ismag) \ - MINMAX_1(type, minimum_number, minmax_ismin | minmax_isnumber) - -MINMAX_2(float16) -MINMAX_2(bfloat16) -MINMAX_2(float32) -MINMAX_2(float64) -MINMAX_2(float128) - -#undef MINMAX_1 -#undef MINMAX_2 - /* * Floating point compare */ static FloatRelation QEMU_FLATTEN float16_do_compare(float16 a, float16 b, float_status *s, bool is_quiet) { - FloatParts64 pa, pb; + FloatParts64 pa = float16_unpack_canonical(a, s); + FloatParts64 pb = float16_unpack_canonical(b, s); - float16_unpack_canonical(&pa, a, s); - float16_unpack_canonical(&pb, b, s); - return parts_compare(&pa, &pb, s, is_quiet); + return parts64_compare(&pa, &pb, s, is_quiet); } FloatRelation float16_compare(float16 a, float16 b, float_status *s) { @@ -3706,11 +3594,10 @@ FloatRelation float16_compare_quiet(float16 a, float16 b, float_status *s) { } static FloatRelation QEMU_SOFTFLOAT_ATTR float32_do_compare(float32 a, float32 b, float_status *s, bool is_quiet) { - FloatParts64 pa, pb; + FloatParts64 pa = float32_unpack_canonical(a, s); + FloatParts64 pb = float32_unpack_canonical(b, s); - float32_unpack_canonical(&pa, a, s); - float32_unpack_canonical(&pb, b, s); - return parts_compare(&pa, &pb, s, is_quiet); + return parts64_compare(&pa, &pb, s, is_quiet); } static FloatRelation QEMU_FLATTEN float32_hs_compare(float32 xa, float32 xb, float_status *s, bool is_quiet) { @@ -3723,7 +3610,11 @@ static FloatRelation QEMU_FLATTEN float32_hs_compare(float32 xa, float32 xb, flo goto soft; } - float32_input_flush2(&ua.s, &ub.s, s); + if (unlikely(float32_is_denormal(ua.s) || float32_is_denormal(ub.s))) { + /* We may need to set the input_denormal_used flag */ + goto soft; + } + if (isgreaterequal(ua.h, ub.h)) { if (isgreater(ua.h, ub.h)) { return float_relation_greater; @@ -3750,11 +3641,10 @@ FloatRelation float32_compare_quiet(float32 a, float32 b, float_status *s) { } static FloatRelation QEMU_SOFTFLOAT_ATTR float64_do_compare(float64 a, float64 b, float_status *s, bool is_quiet) { - FloatParts64 pa, pb; + FloatParts64 pa = float64_unpack_canonical(a, s); + FloatParts64 pb = float64_unpack_canonical(b, s); - float64_unpack_canonical(&pa, a, s); - float64_unpack_canonical(&pb, b, s); - return parts_compare(&pa, &pb, s, is_quiet); + return parts64_compare(&pa, &pb, s, is_quiet); } static FloatRelation QEMU_FLATTEN float64_hs_compare(float64 xa, float64 xb, float_status *s, bool is_quiet) { @@ -3767,7 +3657,11 @@ static FloatRelation QEMU_FLATTEN float64_hs_compare(float64 xa, float64 xb, flo goto soft; } - float64_input_flush2(&ua.s, &ub.s, s); + if (unlikely(float64_is_denormal(ua.s) || float64_is_denormal(ub.s))) { + /* We may need to set the input_denormal_used flag */ + goto soft; + } + if (isgreaterequal(ua.h, ub.h)) { if (isgreater(ua.h, ub.h)) { return float_relation_greater; @@ -3794,11 +3688,10 @@ FloatRelation float64_compare_quiet(float64 a, float64 b, float_status *s) { } static FloatRelation QEMU_FLATTEN bfloat16_do_compare(bfloat16 a, bfloat16 b, float_status *s, bool is_quiet) { - FloatParts64 pa, pb; + FloatParts64 pa = bfloat16_unpack_canonical(a, s); + FloatParts64 pb = bfloat16_unpack_canonical(b, s); - bfloat16_unpack_canonical(&pa, a, s); - bfloat16_unpack_canonical(&pb, b, s); - return parts_compare(&pa, &pb, s, is_quiet); + return parts64_compare(&pa, &pb, s, is_quiet); } FloatRelation bfloat16_compare(bfloat16 a, bfloat16 b, float_status *s) { @@ -3810,11 +3703,10 @@ FloatRelation bfloat16_compare_quiet(bfloat16 a, bfloat16 b, float_status *s) { } static FloatRelation QEMU_FLATTEN float128_do_compare(float128 a, float128 b, float_status *s, bool is_quiet) { - FloatParts128 pa, pb; + FloatParts128 pa = float128_unpack_canonical(a, s); + FloatParts128 pb = float128_unpack_canonical(b, s); - float128_unpack_canonical(&pa, a, s); - float128_unpack_canonical(&pb, b, s); - return parts_compare(&pa, &pb, s, is_quiet); + return parts128_compare(&pa, &pb, s, is_quiet); } FloatRelation float128_compare(float128 a, float128 b, float_status *s) { @@ -3831,7 +3723,7 @@ static FloatRelation QEMU_FLATTEN floatx80_do_compare(floatx80 a, floatx80 b, fl if (!floatx80_unpack_canonical(&pa, a, s) || !floatx80_unpack_canonical(&pb, b, s)) { return float_relation_unordered; } - return parts_compare(&pa, &pb, s, is_quiet); + return parts128_compare(&pa, &pb, s, is_quiet); } FloatRelation floatx80_compare(floatx80 a, floatx80 b, float_status *s) { @@ -3847,42 +3739,37 @@ FloatRelation floatx80_compare_quiet(floatx80 a, floatx80 b, float_status *s) { */ float16 float16_scalbn(float16 a, int n, float_status *status) { - FloatParts64 p; + FloatParts64 p = float16_unpack_canonical(a, status); - float16_unpack_canonical(&p, a, status); - parts_scalbn(&p, n, status); + p = parts64_scalbn(&p, n, status); return float16_round_pack_canonical(&p, status); } float32 float32_scalbn(float32 a, int n, float_status *status) { - FloatParts64 p; + FloatParts64 p = float32_unpack_canonical(a, status); - float32_unpack_canonical(&p, a, status); - parts_scalbn(&p, n, status); + p = parts64_scalbn(&p, n, status); return float32_round_pack_canonical(&p, status); } float64 float64_scalbn(float64 a, int n, float_status *status) { - FloatParts64 p; + FloatParts64 p = float64_unpack_canonical(a, status); - float64_unpack_canonical(&p, a, status); - parts_scalbn(&p, n, status); + p = parts64_scalbn(&p, n, status); return float64_round_pack_canonical(&p, status); } bfloat16 bfloat16_scalbn(bfloat16 a, int n, float_status *status) { - FloatParts64 p; + FloatParts64 p = bfloat16_unpack_canonical(a, status); - bfloat16_unpack_canonical(&p, a, status); - parts_scalbn(&p, n, status); + p = parts64_scalbn(&p, n, status); return bfloat16_round_pack_canonical(&p, status); } float128 float128_scalbn(float128 a, int n, float_status *status) { - FloatParts128 p; + FloatParts128 p = float128_unpack_canonical(a, status); - float128_unpack_canonical(&p, a, status); - parts_scalbn(&p, n, status); + p = parts128_scalbn(&p, n, status); return float128_round_pack_canonical(&p, status); } @@ -3892,7 +3779,7 @@ floatx80 floatx80_scalbn(floatx80 a, int n, float_status *status) { if (!floatx80_unpack_canonical(&p, a, status)) { return floatx80_default_nan(status); } - parts_scalbn(&p, n, status); + p = parts128_scalbn(&p, n, status); return floatx80_round_pack_canonical(&p, status); } @@ -3901,26 +3788,23 @@ floatx80 floatx80_scalbn(floatx80 a, int n, float_status *status) { */ float16 QEMU_FLATTEN float16_sqrt(float16 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = float16_unpack_canonical(a, status); - float16_unpack_canonical(&p, a, status); - parts_sqrt(&p, status, &float16_params); + parts64_sqrt(&p, status, &float16_params); return float16_round_pack_canonical(&p, status); } static float32 QEMU_SOFTFLOAT_ATTR soft_f32_sqrt(float32 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = float32_unpack_canonical(a, status); - float32_unpack_canonical(&p, a, status); - parts_sqrt(&p, status, &float32_params); + parts64_sqrt(&p, status, &float32_params); return float32_round_pack_canonical(&p, status); } static float64 QEMU_SOFTFLOAT_ATTR soft_f64_sqrt(float64 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = float64_unpack_canonical(a, status); - float64_unpack_canonical(&p, a, status); - parts_sqrt(&p, status, &float64_params); + parts64_sqrt(&p, status, &float64_params); return float64_round_pack_canonical(&p, status); } @@ -3971,26 +3855,23 @@ float64 QEMU_FLATTEN float64_sqrt(float64 xa, float_status *s) { } float64 float64r32_sqrt(float64 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = float64_unpack_canonical(a, status); - float64_unpack_canonical(&p, a, status); - parts_sqrt(&p, status, &float64_params); + parts64_sqrt(&p, status, &float64_params); return float64r32_round_pack_canonical(&p, status); } bfloat16 QEMU_FLATTEN bfloat16_sqrt(bfloat16 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = bfloat16_unpack_canonical(a, status); - bfloat16_unpack_canonical(&p, a, status); - parts_sqrt(&p, status, &bfloat16_params); + parts64_sqrt(&p, status, &bfloat16_params); return bfloat16_round_pack_canonical(&p, status); } float128 QEMU_FLATTEN float128_sqrt(float128 a, float_status *status) { - FloatParts128 p; + FloatParts128 p = float128_unpack_canonical(a, status); - float128_unpack_canonical(&p, a, status); - parts_sqrt(&p, status, &float128_params); + parts128_sqrt(&p, status, &float128_params); return float128_round_pack_canonical(&p, status); } @@ -4000,26 +3881,144 @@ floatx80 floatx80_sqrt(floatx80 a, float_status *s) { if (!floatx80_unpack_canonical(&p, a, s)) { return floatx80_default_nan(s); } - parts_sqrt(&p, s, &floatx80_params[s->floatx80_rounding_precision]); + parts128_sqrt(&p, s, &floatx80_params[get_floatx80_rounding_precision(s)]); return floatx80_round_pack_canonical(&p, s); } /* * log2 */ + +static void parts64_log2(FloatParts64 *a, float_status *s, const FloatFmt *fmt) { + uint64_t a0, a1, r, t, ign; + int i, n, a_exp, f_exp; + + if (unlikely(a->cls != float_class_normal)) { + switch (a->cls) { + case float_class_denormal: + if (!a->sign) { + /* -ve denormal will be InvalidOperation */ + float_raise(float_flag_input_denormal_used, s); + } + break; + case float_class_snan: + case float_class_qnan: + *a = parts64_return_nan(a, s); + return; + case float_class_zero: + float_raise(float_flag_divbyzero, s); + /* log2(0) = -inf */ + a->cls = float_class_inf; + a->sign = 1; + return; + case float_class_inf: + if (unlikely(a->sign)) { + goto d_nan; + } + return; + default: + g_assert_not_reached(); + } + } + if (unlikely(a->sign)) { + goto d_nan; + } + + a_exp = a->exp; + f_exp = -1; + + r = 0; + t = DECOMPOSED_IMPLICIT_BIT; + a0 = a->frac_hi; + a1 = 0; + + n = fmt->frac_size + 2; + if (unlikely(a_exp == -1)) { + /* + * When a_exp == -1, we're computing the log2 of a value [0.5,1.0). + * When the value is very close to 1.0, there are lots of 1's in + * the msb parts of the fraction. At the end, when we subtract + * this value from -1.0, we can see a catastrophic loss of precision, + * as 0x800..000 - 0x7ff..ffx becomes 0x000..00y, leaving only the + * bits of y in the final result. To minimize this, compute as many + * digits as we can. + * ??? This case needs another algorithm to avoid this. + */ + n = fmt->frac_size * 2 + 2; + /* Don't compute a value overlapping the sticky bit */ + n = MIN(n, 62); + } + + for (i = 0; i < n; i++) { + if (a1) { + mul128To256(a0, a1, a0, a1, &a0, &a1, &ign, &ign); + } else if (a0 & 0xffffffffull) { + mul64To128(a0, a0, &a0, &a1); + } else if (a0 & ~DECOMPOSED_IMPLICIT_BIT) { + a0 >>= 32; + a0 *= a0; + } else { + goto exact; + } + + if (a0 & DECOMPOSED_IMPLICIT_BIT) { + if (unlikely(a_exp == 0 && r == 0)) { + /* + * When a_exp == 0, we're computing the log2 of a value + * [1.0,2.0). When the value is very close to 1.0, there + * are lots of 0's in the msb parts of the fraction. + * We need to compute more digits to produce a correct + * result -- restart at the top of the fraction. + * ??? This is likely to lose precision quickly, as for + * float128; we may need another method. + */ + f_exp -= i; + t = r = DECOMPOSED_IMPLICIT_BIT; + i = 0; + } else { + r |= t; + } + } else { + add128(a0, a1, a0, a1, &a0, &a1); + } + t >>= 1; + } + + /* Set sticky for inexact. */ + r |= (a1 || a0 & ~DECOMPOSED_IMPLICIT_BIT); + +exact: + parts64_sint_to_float(a, a_exp, 0, s); + if (r != 0) { + FloatParts64 f = {.cls = float_class_normal, .frac = r}; + f.exp = f_exp - frac64_normalize(&f); + + if (a_exp < 0) { + parts64_sub_normal(a, &f); + } else if (a_exp > 0) { + parts64_add_normal(a, &f); + } else { + *a = f; + } + } + return; + +d_nan: + float_raise(float_flag_invalid, s); + *a = parts64_default_nan(s); +} + float32 float32_log2(float32 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = float32_unpack_canonical(a, status); - float32_unpack_canonical(&p, a, status); - parts_log2(&p, status, &float32_params); + parts64_log2(&p, status, &float32_params); return float32_round_pack_canonical(&p, status); } float64 float64_log2(float64 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = float64_unpack_canonical(a, status); - float64_unpack_canonical(&p, a, status); - parts_log2(&p, status, &float64_params); + parts64_log2(&p, status, &float64_params); return float64_round_pack_canonical(&p, status); } @@ -4028,43 +4027,38 @@ float64 float64_log2(float64 a, float_status *status) { *----------------------------------------------------------------------------*/ float16 float16_default_nan(float_status *status) { - FloatParts64 p; + FloatParts64 p = parts64_default_nan(status); - parts_default_nan(&p, status); p.frac >>= float16_params.frac_shift; - return float16_pack_raw(&p); + return pack_raw64(&p, &float16_params); } float32 float32_default_nan(float_status *status) { - FloatParts64 p; + FloatParts64 p = parts64_default_nan(status); - parts_default_nan(&p, status); p.frac >>= float32_params.frac_shift; - return float32_pack_raw(&p); + return pack_raw64(&p, &float32_params); } float64 float64_default_nan(float_status *status) { - FloatParts64 p; + FloatParts64 p = parts64_default_nan(status); - parts_default_nan(&p, status); p.frac >>= float64_params.frac_shift; - return float64_pack_raw(&p); + return pack_raw64(&p, &float64_params); } float128 float128_default_nan(float_status *status) { - FloatParts128 p; + FloatParts128 p = parts128_default_nan(status); - parts_default_nan(&p, status); - frac_shr(&p, float128_params.frac_shift); + frac128_shr(&p, float128_params.frac_shift); return float128_pack_raw(&p); } bfloat16 bfloat16_default_nan(float_status *status) { - FloatParts64 p; + FloatParts64 p = parts64_default_nan(status); - parts_default_nan(&p, status); p.frac >>= bfloat16_params.frac_shift; - return bfloat16_pack_raw(&p); + return pack_raw64(&p, &bfloat16_params); } /*---------------------------------------------------------------------------- @@ -4072,52 +4066,47 @@ bfloat16 bfloat16_default_nan(float_status *status) { *----------------------------------------------------------------------------*/ float16 float16_silence_nan(float16 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = unpack_raw64(&float16_params, a); - float16_unpack_raw(&p, a); p.frac <<= float16_params.frac_shift; - parts_silence_nan(&p, status); + p = parts64_silence_nan(&p, status); p.frac >>= float16_params.frac_shift; - return float16_pack_raw(&p); + return pack_raw64(&p, &float16_params); } float32 float32_silence_nan(float32 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = unpack_raw64(&float32_params, a); - float32_unpack_raw(&p, a); p.frac <<= float32_params.frac_shift; - parts_silence_nan(&p, status); + p = parts64_silence_nan(&p, status); p.frac >>= float32_params.frac_shift; - return float32_pack_raw(&p); + return pack_raw64(&p, &float32_params); } float64 float64_silence_nan(float64 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = unpack_raw64(&float64_params, a); - float64_unpack_raw(&p, a); p.frac <<= float64_params.frac_shift; - parts_silence_nan(&p, status); + p = parts64_silence_nan(&p, status); p.frac >>= float64_params.frac_shift; - return float64_pack_raw(&p); + return pack_raw64(&p, &float64_params); } bfloat16 bfloat16_silence_nan(bfloat16 a, float_status *status) { - FloatParts64 p; + FloatParts64 p = unpack_raw64(&bfloat16_params, a); - bfloat16_unpack_raw(&p, a); p.frac <<= bfloat16_params.frac_shift; - parts_silence_nan(&p, status); + p = parts64_silence_nan(&p, status); p.frac >>= bfloat16_params.frac_shift; - return bfloat16_pack_raw(&p); + return pack_raw64(&p, &bfloat16_params); } float128 float128_silence_nan(float128 a, float_status *status) { - FloatParts128 p; + FloatParts128 p = float128_unpack_raw(a); - float128_unpack_raw(&p, a); - frac_shl(&p, float128_params.frac_shift); - parts_silence_nan(&p, status); - frac_shr(&p, float128_params.frac_shift); + frac128_shl(&p, float128_params.frac_shift); + p = parts128_silence_nan(&p, status); + frac128_shr(&p, float128_params.frac_shift); return float128_pack_raw(&p); } @@ -4128,7 +4117,7 @@ float128 float128_silence_nan(float128 a, float_status *status) { static bool parts_squash_denormal(FloatParts64 p, float_status *status) { if (p.exp == 0 && p.frac != 0) { - float_raise(float_flag_input_denormal, status); + float_raise(float_flag_input_denormal_flushed, status); return true; } @@ -4136,10 +4125,9 @@ static bool parts_squash_denormal(FloatParts64 p, float_status *status) { } float16 float16_squash_input_denormal(float16 a, float_status *status) { - if (status->flush_inputs_to_zero) { - FloatParts64 p; + if (get_flush_inputs_to_zero(status)) { + FloatParts64 p = unpack_raw64(&float16_params, a); - float16_unpack_raw(&p, a); if (parts_squash_denormal(p, status)) { return float16_set_sign(float16_zero, p.sign); } @@ -4148,10 +4136,9 @@ float16 float16_squash_input_denormal(float16 a, float_status *status) { } float32 float32_squash_input_denormal(float32 a, float_status *status) { - if (status->flush_inputs_to_zero) { - FloatParts64 p; + if (get_flush_inputs_to_zero(status)) { + FloatParts64 p = unpack_raw64(&float32_params, a); - float32_unpack_raw(&p, a); if (parts_squash_denormal(p, status)) { return float32_set_sign(float32_zero, p.sign); } @@ -4160,10 +4147,9 @@ float32 float32_squash_input_denormal(float32 a, float_status *status) { } float64 float64_squash_input_denormal(float64 a, float_status *status) { - if (status->flush_inputs_to_zero) { - FloatParts64 p; + if (get_flush_inputs_to_zero(status)) { + FloatParts64 p = unpack_raw64(&float64_params, a); - float64_unpack_raw(&p, a); if (parts_squash_denormal(p, status)) { return float64_set_sign(float64_zero, p.sign); } @@ -4172,10 +4158,9 @@ float64 float64_squash_input_denormal(float64 a, float_status *status) { } bfloat16 bfloat16_squash_input_denormal(bfloat16 a, float_status *status) { - if (status->flush_inputs_to_zero) { - FloatParts64 p; + if (get_flush_inputs_to_zero(status)) { + FloatParts64 p = unpack_raw64(&bfloat16_params, a); - bfloat16_unpack_raw(&p, a); if (parts_squash_denormal(p, status)) { return bfloat16_set_sign(bfloat16_zero, p.sign); } @@ -4198,6 +4183,23 @@ void normalizeFloatx80Subnormal(uint64_t aSig, int32_t *zExpPtr, uint64_t *zSigP *zExpPtr = 1 - shiftCount; } +/*---------------------------------------------------------------------------- +| Takes two extended double-precision floating-point values `a' and `b', one +| of which is a NaN, and returns the appropriate NaN result. If either `a' or +| `b' is a signaling NaN, the invalid exception is raised. +*----------------------------------------------------------------------------*/ + +floatx80 propagateFloatx80NaN(floatx80 a, floatx80 b, float_status *status) { + FloatParts128 pa, pb; + + if (!floatx80_unpack_canonical(&pa, a, status) || !floatx80_unpack_canonical(&pb, b, status)) { + return floatx80_default_nan(status); + } + + pa = parts128_pick_nan(&pa, &pb, status); + return floatx80_round_pack_canonical(&pa, status); +} + /*---------------------------------------------------------------------------- | Takes an abstract floating-point value having sign `zSign', exponent `zExp', | and extended significand formed by the concatenation of `zSig0' and `zSig1', @@ -4228,7 +4230,7 @@ floatx80 roundAndPackFloatx80(FloatX80RoundPrec roundingPrecision, bool zSign, i bool roundNearestEven, increment, isTiny; int64_t roundIncrement, roundMask, roundBits; - roundingMode = status->float_rounding_mode; + roundingMode = get_float_rounding_mode(status); roundNearestEven = (roundingMode == float_round_nearest_even); switch (roundingPrecision) { case floatx80_precision_x: @@ -4267,11 +4269,11 @@ floatx80 roundAndPackFloatx80(FloatX80RoundPrec roundingPrecision, bool zSign, i goto overflow; } if (zExp <= 0) { - if (status->flush_to_zero) { - float_raise(float_flag_output_denormal, status); + if (get_flush_to_zero(status)) { + float_raise(float_flag_output_denormal_flushed, status); return packFloatx80(zSign, 0, 0); } - isTiny = status->tininess_before_rounding || (zExp < 0) || (zSig0 <= zSig0 + roundIncrement); + isTiny = get_tininess_before_rounding(status) || (zExp < 0) || (zSig0 <= zSig0 + roundIncrement); shift64RightJamming(zSig0, 1 - zExp, &zSig0); zExp = 0; roundBits = zSig0 & roundMask; @@ -4335,11 +4337,11 @@ floatx80 roundAndPackFloatx80(FloatX80RoundPrec roundingPrecision, bool zSign, i (!zSign && (roundingMode == float_round_down))) { return packFloatx80(zSign, 0x7FFE, ~roundMask); } - return packFloatx80(zSign, floatx80_infinity_high, floatx80_infinity_low); + return floatx80_default_inf(zSign, status); } if (zExp <= 0) { - isTiny = - status->tininess_before_rounding || (zExp < 0) || !increment || (zSig0 < UINT64_C(0xFFFFFFFFFFFFFFFF)); + isTiny = get_tininess_before_rounding(status) || (zExp < 0) || !increment || + (zSig0 < UINT64_C(0xFFFFFFFFFFFFFFFF)); shift64ExtraRightJamming(zSig0, zSig1, 1 - zExp, &zSig0, &zSig1); zExp = 0; if (isTiny && zSig1) { @@ -4457,37 +4459,37 @@ static const float64 float32_exp2_coefficients[15] = { }; float32 float32_exp2(float32 a, float_status *status) { - FloatParts64 xp, xnp, tp, rp; - int i; + FloatParts64 xnp, tp, rp; + FloatParts64 xp = float32_unpack_canonical(a, status); - float32_unpack_canonical(&xp, a, status); if (unlikely(xp.cls != float_class_normal)) { switch (xp.cls) { + case float_class_denormal: + break; case float_class_snan: case float_class_qnan: - parts_return_nan(&xp, status); + xp = parts64_return_nan(&xp, status); return float32_round_pack_canonical(&xp, status); case float_class_inf: return xp.sign ? float32_zero : a; case float_class_zero: return float32_one; default: - break; + g_assert_not_reached(); } - g_assert_not_reached(); } float_raise(float_flag_inexact, status); - float64_unpack_canonical(&tp, float64_ln2, status); - xp = *parts_mul(&xp, &tp, status); + tp = float64_unpack_canonical(float64_ln2, status); + xp = parts64_mul(&xp, &tp, status); xnp = xp; - float64_unpack_canonical(&rp, float64_one, status); - for (i = 0; i < 15; i++) { - float64_unpack_canonical(&tp, float32_exp2_coefficients[i], status); - rp = *parts_muladd(&tp, &xnp, &rp, 0, status); - xnp = *parts_mul(&xnp, &xp, status); + rp = float64_unpack_canonical(float64_one, status); + for (int i = 0; i < 15; i++) { + tp = float64_unpack_canonical(float32_exp2_coefficients[i], status); + rp = parts64_muladd(&tp, &xnp, &rp, 0, status); + xnp = parts64_mul(&xnp, &xp, status); } return float32_round_pack_canonical(&rp, status); From bae2b050b2a1873a802bd4a255d528ea9e364f6d Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Tue, 18 Aug 2026 15:43:15 +0000 Subject: [PATCH 06/52] libcpu: initialized the x86 float_status behaviour rules Since qemu 11.1 softfloat asserts when it has to choose between two or three input NaNs and no propagation rule was selected, and when it has to produce a default NaN and no bit pattern was set. cpu_state_reset() memsets the CPU state, which leaves every rule at zero, so these have to be reapplied on every reset. Without this the build is clean but the first operation on two NaNs aborts. Mirrors cpu_init_fp_statuses() in qemu's target/i386/tcg/fpu_helper.c. Also include the new tcg/utils/cpu-float.h, which now holds the float and integer reinterpretation unions that used to live in bswap.h. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- libcpu/src/cpu-all.h | 1 + libcpu/src/target-i386/helper.c | 49 +++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/libcpu/src/cpu-all.h b/libcpu/src/cpu-all.h index 180ff63ae..bcc249b08 100644 --- a/libcpu/src/cpu-all.h +++ b/libcpu/src/cpu-all.h @@ -24,6 +24,7 @@ #include #include #include +#include #include "qemu-common.h" #ifdef CONFIG_SYMBEX diff --git a/libcpu/src/target-i386/helper.c b/libcpu/src/target-i386/helper.c index 540156d08..7758984e8 100644 --- a/libcpu/src/target-i386/helper.c +++ b/libcpu/src/target-i386/helper.c @@ -107,6 +107,53 @@ target_ulong cpu_get_eflags(CPUX86State *env) { // #define DEBUG_MMU /* NOTE: must be called outside the CPU execute loop */ +/* + * Set up the float_status fields that describe baked-in hardware behaviour + * rather than guest-visible control register state. Since QEMU 11.1 softfloat + * asserts when it has to pick between NaNs and no rule was selected, so these + * must be reapplied every time cpu_state_reset() zeroes the CPU state. + * + * This mirrors cpu_init_fp_statuses() in QEMU's target/i386/tcg/fpu_helper.c. + */ +static void cpu_init_fp_statuses(CPUX86State *env) { + /* + * Use x87 NaN propagation rules: + * SNaN + QNaN => return the QNaN + * two SNaNs => return the one with the larger significand, silenced + * two QNaNs => return the one with the larger significand + * SNaN and a non-NaN => return the SNaN, silenced + * QNaN and a non-NaN => return the QNaN + * + * If we get down to comparing significands and they are the same, + * return the NaN with the positive sign bit (if any). + */ + set_float_2nan_prop_rule(float_2nan_prop_x87, &env->fp_status); + set_float_2nan_prop_rule(float_2nan_prop_x87, &env->mmx_status); + set_float_2nan_prop_rule(float_2nan_prop_x87, &env->sse_status); + + /* + * Only SSE has multiply-add instructions. For 0 * inf + NaN the input NaN + * is selected, and multiple input NaNs are selected in the order a, b, c. + * Invalid is not raised for the 0 * inf + (Q)NaN case. + */ + set_float_infzeronan_rule(float_infzeronan_dnan_never | float_infzeronan_suppress_invalid, &env->sse_status); + set_float_3nan_prop_rule(float_3nan_prop_abc, &env->sse_status); + + /* Default NaN: sign bit set, most significant frac bit set */ + set_float_default_nan_pattern(0b11000000, &env->fp_status); + set_float_default_nan_pattern(0b11000000, &env->mmx_status); + set_float_default_nan_pattern(0b11000000, &env->sse_status); + + /* + * x86 does flush-to-zero detection after rounding: the SDM section 10.2.3.3 + * on the FTZ bit of MXCSR says that we flush when we detect underflow, + * which x86 does after rounding. + */ + set_float_ftz_detection(float_ftz_after_rounding, &env->fp_status); + set_float_ftz_detection(float_ftz_after_rounding, &env->mmx_status); + set_float_ftz_detection(float_ftz_after_rounding, &env->sse_status); +} + void cpu_state_reset(CPUX86State *env) { int i; @@ -117,6 +164,8 @@ void cpu_state_reset(CPUX86State *env) { memset(env, 0, offsetof(CPUX86State, breakpoints)); + cpu_init_fp_statuses(env); + tlb_flush(env, 1); env->old_exception = -1; From 94058db0e9b163a64fce6afa4d0b595378d9251b Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Tue, 18 Aug 2026 15:49:01 +0000 Subject: [PATCH 07/52] skills: added a skill to upgrade libtcg Captures the workflow used for the qemu 10.2 to 11.1 upgrade: normalize the upstream formatting before comparing, then three-way merge. Records the S2E deviations that have to survive future merges, the libcpu fallout that libtcg's own build does not catch, and the changes that are guest visible rather than merely mechanical. The most important part is the warning not to replace RR_cpu()/WR_cpu() with direct struct access when upstream makes a field unaddressable: that silences the compiler but silently reads the native CPU state instead of KLEE's on symbolic paths. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- .claude/skills/upgrade-libtcg/SKILL.md | 169 +++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 .claude/skills/upgrade-libtcg/SKILL.md diff --git a/.claude/skills/upgrade-libtcg/SKILL.md b/.claude/skills/upgrade-libtcg/SKILL.md new file mode 100644 index 000000000..1934b585e --- /dev/null +++ b/.claude/skills/upgrade-libtcg/SKILL.md @@ -0,0 +1,169 @@ +--- +name: upgrade-libtcg +description: Upgrade libtcg (and its softfloat/utils subsets) to a newer QEMU release. Use when asked to move libtcg to a new QEMU version, pull in upstream TCG changes, rebase the TCG fork, or when a QEMU tag is named alongside libtcg/tcg/softfloat. Covers the normalize-then-merge workflow, the S2E deviations that must survive, and the libcpu fallout. +--- + +# Upgrading libtcg to a new QEMU release + +libtcg is a de-QEMU-ified fork of QEMU's TCG: headers are moved out of `qemu/`, +`exec/` and `accel/tcg/` into `tcg/utils/`, `tcg/exec/` and `tcg/accel/`, and the +whole tree is reformatted with the S2E `.clang-format`. **`git cherry-pick` and +`patch` never apply** — every line differs because of reformatting alone. + +The tooling lives in `libtcg/scripts/upgrade/`. Read its `README.md` first. + +## The core idea + +Run the upstream file through clang-format with the S2E style *before* +comparing. That collapses the diff to the genuine S2E delta — `src/tcg.c` goes +from ~6800 differing lines to ~79 — which makes the upgrade an ordinary +three-way merge: + + base = clang-formatted upstream at the OLD tag + theirs = clang-formatted upstream at the NEW tag + ours = the current libtcg file + +Expect most files to merge clean, including the big ones (`tcg.c`, `tcg-op.c`, +`optimize.c`, `tcg-target.c.inc`). Conflicts are almost always one hunk in an +include block or where S2E's `extern "C"` guard meets appended upstream code. + +## Steps + +### 1. Scope it + + cat libtcg/scripts/upgrade/BASELINE # the tag libtcg currently tracks + git -C ~/qemu log --oneline .. -- tcg/ include/tcg/ + +**libtcg is not uniformly at one version.** Only the TCG core tracks `BASELINE`; +much of `utils/` still sits at v8.1.0. Before assuming a file's baseline, check +it: format the file at several candidate tags and pick the smallest diff. A file +that is stale relative to its neighbours is a bug waiting to happen — the 11.1 +upgrade found `tcg-gvec-desc.h` stranded at an old descriptor encoding while +`simd_desc()` already wrote the new one. + +Note deleted, added and renamed files in the upstream range; `merge.sh` reports +them but cannot decide what to do about them. + +### 2. Merge + + cd libtcg/scripts/upgrade + QEMU_SRC=~/qemu ./merge.sh # dry run, reports conflicts + QEMU_SRC=~/qemu ./merge.sh --apply # write back + +Prefer applying a chosen subset by hand over `--apply` when the upgrade is +scoped to part of the tree (e.g. TCG core but not `fpu/`). Merged output sits in +`scripts/upgrade/out/merged/`. + +Resolve conflicts by keeping the libtcg side of include blocks (the `` +paths and `// clang-format off` markers), and keeping the upstream side of +everything else, with the `extern "C"` guard moved to wrap the new code. + +### 3. Import new files by hand + +Files upstream added have no libtcg name to merge into. Normalize, then rewrite +the includes to libtcg paths and add `extern "C"` guards: + + QEMU_SRC=~/qemu ./normalize.sh include/tcg/foo.h > ../../include/tcg/foo.h + +**Make imported headers self-contained.** Upstream relies on `qemu/osdep.h` +being included first everywhere; libtcg has no such prelude, and the S2E +clang-format sets `SortIncludes: true`, so it will reorder an include block and +break any header that depends on its position. + +### 4. Build + + cd ~/s2e/build/libs2e-release && make -j16 + cd ~/s2e/build/libs2e-debug && make -j16 + +Both trees, six configurations each: `{i386,x86_64}-{,s2e-,s2e_sp-}softmmu`. +Iterate on `libs2e-release/x86_64-s2e-softmmu/libtcg` alone for a fast loop, but +finish on the full build — the i386 (`TARGET_LONG_BITS=32`) configurations +exercise different paths. + +### 5. Verify the S2E patches survived + +A clean merge is not a correct merge. Diff each changed file against normalized +upstream at the new tag and confirm the residual is *only* the expected S2E +delta: + + diff scripts/upgrade/out/new/src/x86_64/tcg-target.c.inc src/x86_64/tcg-target.c.inc + +Patches that must still be there, and that upstream refactors can silently +relocate: + +- `s->qemu_ld_helpers` / `s->qemu_st_helpers` (per-context, not the static table) +- the `CONFIG_SYMBEX && CONFIG_SYMBEX_MP` `se_addend` load on the TLB hit path — + check it is anchored to the right `tcg_out_ld`, not merely present +- `tcg_target_force_tb_exit` +- `tcg_prologue_init(TCGContext *s)` taking the context explicitly +- `mutex_t` / `spin_*` / `g_*cache_linesize` in `region.c` + +### 6. Re-normalize and record + + ./run-clang-format.sh # from the S2E source root + make -j16 # formatting can reorder includes; rebuild + +Then update `BASELINE` and any renamed paths in `mapping.tsv`, add newly tracked +files, and confirm the tree is normalized by merging the new tag onto itself: + + QEMU_SRC=~/qemu ./merge.sh # must be 0 conflicts + +### 7. Commit + +Per `CLAUDE.md`: `component: short description`, lowercase. Split by phase — +tooling, rename, the merge itself, then each consumer. Explain *why* in the +body, especially for anything that deviates from upstream. + +## Deviations that must survive every merge + +- **`float_status.float_rounding_mode` is a plain field, not a bitfield.** S2E + addresses the CPU state by `(offset, size)`; `RR_cpu`/`WR_cpu` need + `offsetof`/`sizeof`, which no bitfield supports. +- **`tcg/utils/cpu-float.h`** holds the float/integer reinterpretation unions + that upstream keeps in `include/qemu/cpu-float.h`. Leaving them in `bswap.h` + creates a cycle: `softfloat-types.h` → `registerfields.h` → `bitops.h` → + `host-utils.h` → `bswap.h`. +- **`accel/getpc.h`** drops upstream's `#ifndef CONFIG_TCG #error` guard. +- **`exec/helper-head.h.inc`** keeps its `#ifdef TARGET_LONG_BITS` guard instead + of including `exec/target_long.h`. + +## The libcpu fallout + +libcpu consumes libtcg and breaks in ways libtcg's own build will not catch. + +**Never replace `RR_cpu`/`WR_cpu` with direct struct access to silence a +compiler error.** Under `CONFIG_SYMBEX` these route through +`g_sqi.regs.read_concrete()` when `fast_concrete_invocation` is false — that is, +when the helper runs as bitcode inside KLEE. Direct access reads the native copy +of the CPU state instead of KLEE's, silently, on exactly the symbolic paths that +matter. If upstream makes a field unaddressable, change the field in libtcg. + +**Check for newly required initialization.** Softfloat asserts at runtime when a +NaN propagation rule or default NaN pattern was never set. `cpu_state_reset()` +memsets the CPU state, so anything of that kind must be reapplied there — see +`cpu_init_fp_statuses()` in `libcpu/src/target-i386/helper.c`, mirroring QEMU's +`target/i386/tcg/fpu_helper.c`. This class of bug builds clean and aborts later, +so grep upstream's target code for setters the fork does not call. + +**Watch for removed macros and renamed flags**, e.g. the removal of +`TARGET_INSN_START_EXTRA_WORDS` (which made `tcg_gen_insn_start` take a fixed +`INSN_START_WORDS` arguments, callers padding with zeroes), and +`float_flag_input_denormal` → `float_flag_input_denormal_flushed`. + +## Things that change behaviour, not just code + +Say so explicitly when reporting the upgrade: + +- Softfloat changes are guest-visible, and `softfloat.c` is compiled to + `softfloat.bc` and interpreted by KLEE, so symbolic paths see them too. +- `float_status` layout changes do not break compatibility with existing S2E snapshots. Snapshots are handled by vanilla QEMU. +- `tcg-llvm.cpp` switches over TCG opcodes; if the upstream range removes or + renames any, the LLVM translator needs updating. Check the opcode list diff: + `diff <(git show :include/tcg/tcg-opc.h | grep -oE '^DEF\([a-z0-9_]+') ...` + +## Testing + +`testsuite/` drives real guest images through `~/s2e/projects/testsuite/*`. The +launch scripts use `BUILD=debug`, so build `libs2e-debug` before running. +`basic4-xmm` is the one most likely to notice softfloat changes. Ask before +running the suite — it is slow, and the user often has it covered. From 274db633a3a073e8eabaaec552f8cfa5d4e6623a Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Tue, 18 Aug 2026 16:35:13 +0000 Subject: [PATCH 08/52] libtcg: upgraded utils to qemu 11.1 The utility subset had been left behind by the earlier upgrades. Checking each file's baseline individually rather than assuming one showed a spread: most of utils/ was at v8.1.0, elf.h at v8.0.0, and the host support headers somewhere between v9.1.0 and v11.0.0. Merged each group from its own baseline. atomic128-cas.h was the interesting one: it had been stranded before v10.2.0 and so was missing atomic16_xchg entirely. That is a host support file which should have moved with the TCG core, and it was missed. elf.h is now byte for byte upstream. The rest differ only by include rewiring, the C++ linkage guards, and three deviations now recorded in scripts/upgrade/README.md and the skill: the new -> _new parameter rename in atomic128-cas.h (new is a C++ keyword and these headers are included from C++), the #ifndef BIT guard in bitops.h (libcpu/include/cpu/kvm.h also defines BIT), and osdep.h carrying what upstream keeps in include/qemu/compiler.h, which now needs typeof_strip_qual for the 11.1 qatomic macros. Dropping bswap.h from int128.h, which 11.1 no longer needs, exposed two files that had been relying on it transitively: int128.h itself for inttypes.h, and optimize.c for bswap16/32/64. Both now include what they use. The files not mentioned here were simply never touched upstream since their baseline, so they are current by definition. The hand written subsets (osdep.h, cutils.*, log.*, bitmap.h, bswap.h) stay at v8.1.0 era deliberately: they are reduced S2E-specific rewrites rather than vendored copies, and a mechanical merge would be wrong. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- libtcg/include/tcg/utils/atomic.h | 105 ++-------- libtcg/include/tcg/utils/atomic128.h | 4 +- libtcg/include/tcg/utils/bitops.h | 182 +++++++++++++++++- libtcg/include/tcg/utils/cpuid.h | 6 + .../tcg/utils/host/generic/atomic128-cas.h | 89 ++++++++- libtcg/include/tcg/utils/int128.h | 9 +- libtcg/include/tcg/utils/osdep.h | 43 +++++ libtcg/scripts/upgrade/README.md | 16 +- libtcg/scripts/upgrade/mapping.tsv | 9 +- libtcg/src/elf.h | 79 +++++--- libtcg/src/optimize.c | 1 + libtcg/src/utils/cpuinfo-i386.c | 9 +- 12 files changed, 412 insertions(+), 140 deletions(-) diff --git a/libtcg/include/tcg/utils/atomic.h b/libtcg/include/tcg/utils/atomic.h index ec7927992..539068f1e 100644 --- a/libtcg/include/tcg/utils/atomic.h +++ b/libtcg/include/tcg/utils/atomic.h @@ -28,45 +28,6 @@ extern "C" { (void) 0; \ }) -/* The variable that receives the old value of an atomically-accessed - * variable must be non-qualified, because atomic builtins return values - * through a pointer-type argument as in __atomic_load(&var, &old, MODEL). - * - * This macro has to handle types smaller than int manually, because of - * implicit promotion. int and larger types, as well as pointers, can be - * converted to a non-qualified type just by applying a binary operator. - */ -#define typeof_strip_qual(expr) \ - typeof(__builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), bool) || __builtin_types_compatible_p(typeof(expr), const bool) || \ - __builtin_types_compatible_p(typeof(expr), volatile bool) || \ - __builtin_types_compatible_p(typeof(expr), const volatile bool), \ - (bool) 1, \ - __builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), signed char) || \ - __builtin_types_compatible_p(typeof(expr), const signed char) || \ - __builtin_types_compatible_p(typeof(expr), volatile signed char) || \ - __builtin_types_compatible_p(typeof(expr), const volatile signed char), \ - (signed char) 1, \ - __builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), unsigned char) || \ - __builtin_types_compatible_p(typeof(expr), const unsigned char) || \ - __builtin_types_compatible_p(typeof(expr), volatile unsigned char) || \ - __builtin_types_compatible_p(typeof(expr), const volatile unsigned char), \ - (unsigned char) 1, \ - __builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), signed short) || \ - __builtin_types_compatible_p(typeof(expr), const signed short) || \ - __builtin_types_compatible_p(typeof(expr), volatile signed short) || \ - __builtin_types_compatible_p(typeof(expr), const volatile signed short), \ - (signed short) 1, \ - __builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), unsigned short) || \ - __builtin_types_compatible_p(typeof(expr), const unsigned short) || \ - __builtin_types_compatible_p(typeof(expr), volatile unsigned short) || \ - __builtin_types_compatible_p(typeof(expr), const volatile unsigned short), \ - (unsigned short) 1, (expr) + 0)))))) - #ifndef __ATOMIC_RELAXED #error "Expecting C11 atomic ops" #endif @@ -119,25 +80,13 @@ extern "C" { */ #define signal_barrier() __atomic_signal_fence(__ATOMIC_SEQ_CST) -/* Sanity check that the size of an atomic operation isn't "overly large". - * Despite the fact that e.g. i686 has 64-bit atomic operations, we do not +/* + * Sanity check that the size of an atomic operation isn't "overly large". + * Despite the fact that e.g. x86-64 has 128-bit atomic operations, we do not * want to use them because we ought not need them, and this lets us do a - * bit of sanity checking that other 32-bit hosts might build. - * - * That said, we have a problem on 64-bit ILP32 hosts in that in order to - * sync with TCG_OVERSIZED_GUEST, this must match TCG_TARGET_REG_BITS. - * We'd prefer not want to pull in everything else TCG related, so handle - * those few cases by hand. - * - * Note that x32 is fully detected with __x86_64__ + _ILP32, and that for - * Sparc we always force the use of sparcv9 in configure. MIPS n32 (ILP32) & - * n64 (LP64) ABIs are both detected using __mips64. + * bit of sanity checking that other 32- and 64-bit hosts might build. */ -#if defined(__x86_64__) || defined(__sparc__) || defined(__mips64) -#define ATOMIC_REG_SIZE 8 -#else -#define ATOMIC_REG_SIZE sizeof(void *) -#endif +#define ATOMIC_REG_SIZE sizeof(uint64_t) /* Weak atomic operations prevent the compiler moving other * loads/stores past the atomic operation load/store. However there is @@ -176,13 +125,19 @@ extern "C" { smp_read_barrier_depends(); #endif -#define qatomic_rcu_read(ptr) \ +/* + * Preprocessor sorcery ahead: use a different identifier for the + * local variable in each expansion, so we can nest macro calls + * without shadowing variables. + */ +#define qatomic_rcu_read_internal(ptr, _val) \ ({ \ qemu_build_assert(sizeof(*ptr) <= ATOMIC_REG_SIZE); \ typeof_strip_qual(*ptr) _val; \ qatomic_rcu_read__nocheck(ptr, &_val); \ _val; \ }) +#define qatomic_rcu_read(ptr) qatomic_rcu_read_internal((ptr), MAKE_IDENTIFIER(_val)) #define qatomic_rcu_set(ptr, i) \ do { \ @@ -214,7 +169,7 @@ extern "C" { qatomic_xchg__nocheck(ptr, i); \ }) -/* Returns the eventual value, failed or not */ +/* Returns the old value of '*ptr' (whether the cmpxchg failed or not) */ #define qatomic_cmpxchg__nocheck(ptr, old, new) \ ({ \ typeof_strip_qual(*ptr) _old = (old); \ @@ -263,7 +218,7 @@ extern "C" { * kernel read-modify-write atomics. Provide a macro to obtain * the same semantics. */ -#if !defined(QEMU_SANITIZE_THREAD) && (defined(__i386__) || defined(__x86_64__) || defined(__s390x__)) +#if !defined(QEMU_SANITIZE_THREAD) && (defined(__x86_64__) || defined(__s390x__)) #define smp_mb__before_rmw() signal_barrier() #define smp_mb__after_rmw() signal_barrier() #else @@ -276,7 +231,7 @@ extern "C" { * plus a fence. */ -#if !defined(QEMU_SANITIZE_THREAD) && (defined(__i386__) || defined(__x86_64__) || defined(__s390x__)) +#if !defined(QEMU_SANITIZE_THREAD) && (defined(__x86_64__) || defined(__s390x__)) #define qatomic_set_mb(ptr, i) \ ({ \ (void) qatomic_xchg(ptr, i); \ @@ -299,36 +254,6 @@ extern "C" { _oldn; \ }) -/* - * Abstractions to access atomically (i.e. "once") i64/u64 variables. - * - * The i386 abi is odd in that by default members are only aligned to - * 4 bytes, which means that 8-byte types can wind up mis-aligned. - * Clang will then warn about this, and emit a call into libatomic. - * - * Use of these types in structures when they will be used with atomic - * operations can avoid this. - */ -typedef int64_t aligned_int64_t __attribute__((aligned(8))); -typedef uint64_t aligned_uint64_t __attribute__((aligned(8))); - -#ifdef CONFIG_ATOMIC64 -/* Use __nocheck because sizeof(void *) might be < sizeof(u64) */ -#define qatomic_read_i64(P) _Generic(*(P), int64_t: qatomic_read__nocheck(P)) -#define qatomic_read_u64(P) _Generic(*(P), uint64_t: qatomic_read__nocheck(P)) -#define qatomic_set_i64(P, V) _Generic(*(P), int64_t: qatomic_set__nocheck(P, V)) -#define qatomic_set_u64(P, V) _Generic(*(P), uint64_t: qatomic_set__nocheck(P, V)) - -static inline void qatomic64_init(void) { -} -#else /* !CONFIG_ATOMIC64 */ -int64_t qatomic_read_i64(const int64_t *ptr); -uint64_t qatomic_read_u64(const uint64_t *ptr); -void qatomic_set_i64(int64_t *ptr, int64_t val); -void qatomic_set_u64(uint64_t *ptr, uint64_t val); -void qatomic64_init(void); -#endif /* !CONFIG_ATOMIC64 */ - #ifdef __cplusplus } #endif diff --git a/libtcg/include/tcg/utils/atomic128.h b/libtcg/include/tcg/utils/atomic128.h index a2e419374..8053d05e7 100644 --- a/libtcg/include/tcg/utils/atomic128.h +++ b/libtcg/include/tcg/utils/atomic128.h @@ -47,8 +47,8 @@ extern "C" { * See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80878 * * This interpretation is not especially helpful for QEMU. - * For softmmu, all RAM is always read/write from the hypervisor. - * For user-only, if the guest doesn't implement such an __atomic_read + * For system-mode, all RAM is always read/write from the hypervisor. + * For user-mode, if the guest doesn't implement such an __atomic_read * then the host need not worry about it either. * * Moreover, using libatomic is not an option, because its interface is diff --git a/libtcg/include/tcg/utils/bitops.h b/libtcg/include/tcg/utils/bitops.h index 33be69150..decb18d5e 100644 --- a/libtcg/include/tcg/utils/bitops.h +++ b/libtcg/include/tcg/utils/bitops.h @@ -23,20 +23,50 @@ extern "C" { #endif -#define BITS_PER_BYTE CHAR_BIT -#define BITS_PER_LONG (sizeof(unsigned long) * BITS_PER_BYTE) +#define BITS_PER_BYTE CHAR_BIT +#define BITS_PER_LONG (sizeof(unsigned long) * BITS_PER_BYTE) +#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long)) +#define BITS_TO_U32S(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(uint32_t)) #ifndef BIT #define BIT(nr) (1UL << (nr)) #endif - -#define BIT_ULL(nr) (1ULL << (nr)) -#define BIT_MASK(nr) (1UL << ((nr) % BITS_PER_LONG)) -#define BIT_WORD(nr) ((nr) / BITS_PER_LONG) -#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long)) +#define BIT_ULL(nr) (1ULL << (nr)) #define MAKE_64BIT_MASK(shift, length) (((~0ULL) >> (64 - (length))) << (shift)) +/** + * DOC: Functions operating on arrays of bits + * + * We provide a set of functions which work on arbitrary-length arrays of + * bits. These come in several flavours which vary in what the type of the + * underlying storage for the bits is: + * + * - Bits stored in an array of 'unsigned long': set_bit(), clear_bit(), etc + * - Bits stored in an array of 'uint32_t': set_bit32(), clear_bit32(), etc + * + * Because the 'unsigned long' type has a size which varies between + * host systems, the versions using 'uint32_t' are often preferable. + * This is particularly the case in a device model where there may + * be some guest-visible register view of the bit array. + * + * We do not currently implement uint32_t versions of find_last_bit(), + * find_next_bit(), find_next_zero_bit(), find_first_bit() or + * find_first_zero_bit(), because we haven't yet needed them. If you + * need them you should implement them similarly to the 'unsigned long' + * versions. + * + * You can declare a bitmap to be used with these functions via the + * DECLARE_BITMAP and DECLARE_BITMAP32 macros in bitmap.h. + */ + +/** + * DOC: 'unsigned long' bit array APIs + */ + +#define BIT_MASK(nr) (1UL << ((nr) % BITS_PER_LONG)) +#define BIT_WORD(nr) ((nr) / BITS_PER_LONG) + /** * set_bit - Set a bit in memory * @nr: the bit to set @@ -73,6 +103,18 @@ static inline void clear_bit(long nr, unsigned long *addr) { *p &= ~mask; } +/** + * clear_bit_atomic - Clears a bit in memory atomically + * @nr: Bit to clear + * @addr: Address to start counting from + */ +static inline void clear_bit_atomic(long nr, unsigned long *addr) { + unsigned long mask = BIT_MASK(nr); + unsigned long *p = addr + BIT_WORD(nr); + + return qatomic_and(p, ~mask); +} + /** * change_bit - Toggle a bit in memory * @nr: Bit to change @@ -203,6 +245,132 @@ static inline unsigned long find_first_zero_bit(const unsigned long *addr, unsig return find_next_zero_bit(addr, size, 0); } +/** + * DOC: 'uint32_t' bit array APIs + */ + +#define BIT32_MASK(nr) (1UL << ((nr) % 32)) +#define BIT32_WORD(nr) ((nr) / 32) + +/** + * set_bit32 - Set a bit in memory + * @nr: the bit to set + * @addr: the address to start counting from + */ +static inline void set_bit32(long nr, uint32_t *addr) { + uint32_t mask = BIT32_MASK(nr); + uint32_t *p = addr + BIT32_WORD(nr); + + *p |= mask; +} + +/** + * set_bit32_atomic - Set a bit in memory atomically + * @nr: the bit to set + * @addr: the address to start counting from + */ +static inline void set_bit32_atomic(long nr, uint32_t *addr) { + uint32_t mask = BIT32_MASK(nr); + uint32_t *p = addr + BIT32_WORD(nr); + + qatomic_or(p, mask); +} + +/** + * clear_bit32 - Clears a bit in memory + * @nr: Bit to clear + * @addr: Address to start counting from + */ +static inline void clear_bit32(long nr, uint32_t *addr) { + uint32_t mask = BIT32_MASK(nr); + uint32_t *p = addr + BIT32_WORD(nr); + + *p &= ~mask; +} + +/** + * clear_bit32_atomic - Clears a bit in memory atomically + * @nr: Bit to clear + * @addr: Address to start counting from + */ +static inline void clear_bit32_atomic(long nr, uint32_t *addr) { + uint32_t mask = BIT32_MASK(nr); + uint32_t *p = addr + BIT32_WORD(nr); + + return qatomic_and(p, ~mask); +} + +/** + * change_bit32 - Toggle a bit in memory + * @nr: Bit to change + * @addr: Address to start counting from + */ +static inline void change_bit32(long nr, uint32_t *addr) { + uint32_t mask = BIT32_MASK(nr); + uint32_t *p = addr + BIT32_WORD(nr); + + *p ^= mask; +} + +/** + * test_and_set_bit32 - Set a bit and return its old value + * @nr: Bit to set + * @addr: Address to count from + */ +static inline int test_and_set_bit32(long nr, uint32_t *addr) { + uint32_t mask = BIT32_MASK(nr); + uint32_t *p = addr + BIT32_WORD(nr); + uint32_t old = *p; + + *p = old | mask; + return (old & mask) != 0; +} + +/** + * test_and_clear_bit32 - Clear a bit and return its old value + * @nr: Bit to clear + * @addr: Address to count from + */ +static inline int test_and_clear_bit32(long nr, uint32_t *addr) { + uint32_t mask = BIT32_MASK(nr); + uint32_t *p = addr + BIT32_WORD(nr); + uint32_t old = *p; + + *p = old & ~mask; + return (old & mask) != 0; +} + +/** + * test_and_change_bit32 - Change a bit and return its old value + * @nr: Bit to change + * @addr: Address to count from + */ +static inline int test_and_change_bit32(long nr, uint32_t *addr) { + uint32_t mask = BIT32_MASK(nr); + uint32_t *p = addr + BIT32_WORD(nr); + uint32_t old = *p; + + *p = old ^ mask; + return (old & mask) != 0; +} + +/** + * test_bit32 - Determine whether a bit is set + * @nr: bit number to test + * @addr: Address to start counting from + */ +static inline int test_bit32(long nr, const uint32_t *addr) { + return 1U & (addr[BIT32_WORD(nr)] >> (nr & 31)); +} + +/** + * DOC: Miscellaneous bit operations on single values + * + * These functions are a collection of useful operations + * (rotations, bit extract, bit deposit, etc) on single + * integer values. + */ + /** * rol8 - rotate an 8-bit value left * @word: value to rotate diff --git a/libtcg/include/tcg/utils/cpuid.h b/libtcg/include/tcg/utils/cpuid.h index 11cd4c482..47d398c6e 100644 --- a/libtcg/include/tcg/utils/cpuid.h +++ b/libtcg/include/tcg/utils/cpuid.h @@ -29,6 +29,9 @@ extern "C" { #endif /* Leaf 1, %ecx */ +#ifndef bit_PCLMUL +#define bit_PCLMUL (1 << 1) +#endif #ifndef bit_SSE4_1 #define bit_SSE4_1 (1 << 19) #endif @@ -69,6 +72,9 @@ extern "C" { #ifndef bit_AVX512VBMI2 #define bit_AVX512VBMI2 (1 << 6) #endif +#ifndef bit_GFNI +#define bit_GFNI (1 << 8) +#endif /* Leaf 0x80000001, %ecx */ #ifndef bit_LZCNT diff --git a/libtcg/include/tcg/utils/host/generic/atomic128-cas.h b/libtcg/include/tcg/utils/host/generic/atomic128-cas.h index 3f2b463ce..fae69044c 100644 --- a/libtcg/include/tcg/utils/host/generic/atomic128-cas.h +++ b/libtcg/include/tcg/utils/host/generic/atomic128-cas.h @@ -21,10 +21,52 @@ static inline Int128 ATTRIBUTE_ATOMIC128_OPT atomic16_cmpxchg(Int128 *ptr, Int12 r.i = qatomic_cmpxchg__nocheck(ptr_align, c.i, n.i); return r.s; } + +/* + * Since we're looping anyway, use weak compare and swap. + * If the host supports weak, this will eliminate a second loop hidden + * within the atomic operation itself; otherwise the weak parameter is + * ignored. + */ +static inline Int128 ATTRIBUTE_ATOMIC128_OPT atomic16_xchg(Int128 *ptr, Int128 _new) { + __int128_t *ptr_align = __builtin_assume_aligned(ptr, 16); + Int128Alias o, n; + + n.s = _new; + o.i = *ptr_align; + while (!__atomic_compare_exchange_n(ptr_align, &o.i, n.i, true, __ATOMIC_SEQ_CST, 0)) { + continue; + } + return o.s; +} + +static inline Int128 ATTRIBUTE_ATOMIC128_OPT atomic16_fetch_and(Int128 *ptr, Int128 val) { + __int128_t *ptr_align = __builtin_assume_aligned(ptr, 16); + Int128Alias o, v; + + v.s = val; + o.i = *ptr_align; + while (!__atomic_compare_exchange_n(ptr_align, &o.i, o.i & v.i, true, __ATOMIC_SEQ_CST, 0)) { + continue; + } + return o.s; +} + +static inline Int128 ATTRIBUTE_ATOMIC128_OPT atomic16_fetch_or(Int128 *ptr, Int128 val) { + __int128_t *ptr_align = __builtin_assume_aligned(ptr, 16); + Int128Alias o, v; + + v.s = val; + o.i = *ptr_align; + while (!__atomic_compare_exchange_n(ptr_align, &o.i, o.i | v.i, true, __ATOMIC_SEQ_CST, 0)) { + continue; + } + return o.s; +} #define HAVE_CMPXCHG128 1 #elif defined(CONFIG_CMPXCHG128) static inline Int128 ATTRIBUTE_ATOMIC128_OPT atomic16_cmpxchg(Int128 *ptr, Int128 cmp, Int128 _new) { - __int128_t *ptr_align = __builtin_assume_aligned(ptr, 16); + Int128Aligned *ptr_align = __builtin_assume_aligned(ptr, 16); Int128Alias r, c, n; c.s = cmp; @@ -32,6 +74,51 @@ static inline Int128 ATTRIBUTE_ATOMIC128_OPT atomic16_cmpxchg(Int128 *ptr, Int12 r.i = __sync_val_compare_and_swap_16(ptr_align, c.i, n.i); return r.s; } + +static inline Int128 ATTRIBUTE_ATOMIC128_OPT atomic16_xchg(Int128 *ptr, Int128 _new) { + Int128Aligned *ptr_align = __builtin_assume_aligned(ptr, 16); + Int128Alias o, n; + + n.s = _new; + o.s = *ptr_align; + while (1) { + __int128 c = __sync_val_compare_and_swap_16(ptr_align, o.i, n.i); + if (c == o.i) { + return o.s; + } + o.i = c; + } +} + +static inline Int128 ATTRIBUTE_ATOMIC128_OPT atomic16_fetch_and(Int128 *ptr, Int128 val) { + Int128Aligned *ptr_align = __builtin_assume_aligned(ptr, 16); + Int128Alias o, v; + + v.s = val; + o.s = *ptr_align; + while (1) { + __int128 c = __sync_val_compare_and_swap_16(ptr_align, o.i, o.i & v.i); + if (c == o.i) { + return o.s; + } + o.i = c; + } +} + +static inline Int128 ATTRIBUTE_ATOMIC128_OPT atomic16_fetch_or(Int128 *ptr, Int128 val) { + Int128Aligned *ptr_align = __builtin_assume_aligned(ptr, 16); + Int128Alias o, v; + + v.s = val; + o.s = *ptr_align; + while (1) { + __int128 c = __sync_val_compare_and_swap_16(ptr_align, o.i, o.i | v.i); + if (c == o.i) { + return o.s; + } + o.i = c; + } +} #define HAVE_CMPXCHG128 1 #else /* Fallback definition that must be optimized away, or error. */ diff --git a/libtcg/include/tcg/utils/int128.h b/libtcg/include/tcg/utils/int128.h index 2e93a6b43..fb21ffbb9 100644 --- a/libtcg/include/tcg/utils/int128.h +++ b/libtcg/include/tcg/utils/int128.h @@ -2,10 +2,9 @@ #define INT128_H #include +#include #include -#include "bswap.h" - #ifdef __cplusplus extern "C" { #endif @@ -17,6 +16,7 @@ extern "C" { */ #if defined(CONFIG_INT128) && !defined(CONFIG_TCG_INTERPRETER) typedef __int128_t Int128; +typedef __int128_t __attribute__((aligned(16))) Int128Aligned; static inline Int128 int128_make64(uint64_t a) { return a; @@ -160,7 +160,7 @@ static inline Int128 bswap128(Int128 a) { #if __has_builtin(__builtin_bswap128) return __builtin_bswap128(a); #else - return int128_make128(bswap64(int128_gethi(a)), bswap64(int128_getlo(a))); + return int128_make128(__builtin_bswap64(int128_gethi(a)), __builtin_bswap64(int128_getlo(a))); #endif } @@ -191,6 +191,7 @@ static inline Int128 int128_rems(Int128 a, Int128 b) { #else /* !CONFIG_INT128 */ typedef struct Int128 Int128; +typedef struct Int128 __attribute__((aligned(16))) Int128Aligned; /* * We guarantee that the in-memory byte representation of an @@ -381,7 +382,7 @@ static inline void int128_subfrom(Int128 *a, Int128 b) { } static inline Int128 bswap128(Int128 a) { - return int128_make128(bswap64(a.hi), bswap64(a.lo)); + return int128_make128(__builtin_bswap64(a.hi), __builtin_bswap64(a.lo)); } static inline int clz128(Int128 a) { diff --git a/libtcg/include/tcg/utils/osdep.h b/libtcg/include/tcg/utils/osdep.h index fcff9c033..d2225b747 100644 --- a/libtcg/include/tcg/utils/osdep.h +++ b/libtcg/include/tcg/utils/osdep.h @@ -104,6 +104,49 @@ extern "C" { #define QEMU_ALWAYS_INLINE #endif +#ifndef __cplusplus +/* + * Take the type of an expression, stripped of any const/volatile qualifiers. + * The atomic builtins return values through a pointer-type argument, as in + * __atomic_load(&var, &old, MODEL), so the destination must be non-qualified. + * + * Types smaller than int are handled explicitly because of implicit promotion; + * int and larger types, and pointers, are stripped by applying a binary + * operator. Upstream keeps this in include/qemu/compiler.h, whose contents + * libtcg folds into osdep.h. + */ +#define typeof_strip_qual(expr) \ + typeof(__builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), bool) || __builtin_types_compatible_p(typeof(expr), const bool) || \ + __builtin_types_compatible_p(typeof(expr), volatile bool) || \ + __builtin_types_compatible_p(typeof(expr), const volatile bool), \ + (bool) 1, \ + __builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), signed char) || \ + __builtin_types_compatible_p(typeof(expr), const signed char) || \ + __builtin_types_compatible_p(typeof(expr), volatile signed char) || \ + __builtin_types_compatible_p(typeof(expr), const volatile signed char), \ + (signed char) 1, \ + __builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), unsigned char) || \ + __builtin_types_compatible_p(typeof(expr), const unsigned char) || \ + __builtin_types_compatible_p(typeof(expr), volatile unsigned char) || \ + __builtin_types_compatible_p(typeof(expr), const volatile unsigned char), \ + (unsigned char) 1, \ + __builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), signed short) || \ + __builtin_types_compatible_p(typeof(expr), const signed short) || \ + __builtin_types_compatible_p(typeof(expr), volatile signed short) || \ + __builtin_types_compatible_p(typeof(expr), const volatile signed short), \ + (signed short) 1, \ + __builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), unsigned short) || \ + __builtin_types_compatible_p(typeof(expr), const unsigned short) || \ + __builtin_types_compatible_p(typeof(expr), volatile unsigned short) || \ + __builtin_types_compatible_p(typeof(expr), const volatile unsigned short), \ + (unsigned short) 1, (expr) + 0)))))) +#endif /* !__cplusplus */ + /* * If __attribute__((error)) is present, use it to produce an error at * compile time. Otherwise, one must wait for the linker to diagnose diff --git a/libtcg/scripts/upgrade/README.md b/libtcg/scripts/upgrade/README.md index 64a9404b6..ba28a2f43 100644 --- a/libtcg/scripts/upgrade/README.md +++ b/libtcg/scripts/upgrade/README.md @@ -39,19 +39,23 @@ The upgrade is then an ordinary three-way merge: reports files that were deleted upstream or added since the old tag, both of which need a human decision. -Not every libtcg file tracks upstream closely. Several utility files -(`utils/osdep.h`, `utils/cutils.c`, `utils/log.c`, `utils/bitmap.h`) are heavily -reduced S2E-specific subsets, and most of `utils/` still sits at QEMU v8.1.0. -These are listed in `mapping.tsv` for reference but normally want a manual look -rather than a mechanical merge. +Not every libtcg file tracks upstream closely. The utility files below the +"hand written" marker in `mapping.tsv` (`utils/osdep.h`, `utils/cutils.*`, +`utils/log.*`, `utils/bitmap.h`, `utils/bswap.h`) are heavily reduced +S2E-specific subsets rather than vendored copies, and are still v8.1.0-era. +They are listed for reference but want a manual look rather than a mechanical +merge. -Two S2E deviations in the merged code are deliberate and must survive future +Several S2E deviations in the merged code are deliberate and must survive future merges: - `float_status.float_rounding_mode` is a plain field rather than a bitfield. S2E addresses the CPU state by (offset, size) so helpers running as bitcode inside KLEE can read it back, which `offsetof`/`sizeof` on a bitfield cannot express. +- `host/generic/atomic128-cas.h` renames the `new` parameter to `_new`, since + these headers are included from C++. +- `utils/osdep.h` carries what upstream keeps in `include/qemu/compiler.h`. - `utils/cpu-float.h` holds the float/integer reinterpretation unions that upstream keeps in `include/qemu/cpu-float.h`. Leaving them in `bswap.h`, as older libtcg did, creates an include cycle through `softfloat-types.h` -> diff --git a/libtcg/scripts/upgrade/mapping.tsv b/libtcg/scripts/upgrade/mapping.tsv index 5f8388006..c895b7bd5 100644 --- a/libtcg/scripts/upgrade/mapping.tsv +++ b/libtcg/scripts/upgrade/mapping.tsv @@ -68,12 +68,11 @@ include/tcg/utils/host/generic/load-extract-al16-al8.h host/include/generic/host include/tcg/utils/host/generic/store-insert-al16.h host/include/generic/host/store-insert-al16.h.inc src/utils/cpuinfo-i386.c util/cpuinfo-i386.c # --- utilities ---------------------------------------------------------- -# Mostly still at QEMU v8.1.0; the upgrade deliberately lags the TCG core, -# and only what newer TCG or softfloat actually needs has been pulled in. +# These track BASELINE. Files not listed as changing upstream since v8.1.0 +# were simply never touched there, so they are current by definition. include/tcg/utils/atomic.h include/qemu/atomic.h include/tcg/utils/atomic128.h include/qemu/atomic128.h include/tcg/utils/bitops.h include/qemu/bitops.h -include/tcg/utils/bswap.h include/qemu/bswap.h include/tcg/utils/cpuid.h include/qemu/cpuid.h include/tcg/utils/debug-assert.h include/tcg/debug-assert.h include/tcg/utils/host-utils.h include/qemu/host-utils.h @@ -89,7 +88,9 @@ src/utils/interval-tree.c util/interval-tree.c src/utils/memalign.c util/memalign.c src/utils/qtree.c util/qtree.c src/elf.h include/elf.h -# Heavily reduced S2E-specific subsets: merge by hand, not mechanically. +# Heavily reduced S2E-specific subsets, still v8.1.0-era: these are hand +# written rather than vendored, so merge by hand, not mechanically. +include/tcg/utils/bswap.h include/qemu/bswap.h include/tcg/utils/bitmap.h include/qemu/bitmap.h include/tcg/utils/cutils.h include/qemu/cutils.h include/tcg/utils/log.h include/qemu/log.h diff --git a/libtcg/src/elf.h b/libtcg/src/elf.h index a63787c60..d1e3fce6d 100644 --- a/libtcg/src/elf.h +++ b/libtcg/src/elf.h @@ -56,6 +56,13 @@ typedef int64_t Elf64_Sxword; #define EF_MIPS_ARCH_32R6 0x90000000 /* MIPS32r6 code. */ #define EF_MIPS_ARCH_64R6 0xa0000000 /* MIPS64r6 code. */ +/* MIPS Architectural Extensions. */ +#define EF_MIPS_ARCH_ASE 0x0f000000 + +#define EF_MIPS_ARCH_ASE_MICROMIPS 0x02000000 +#define EF_MIPS_ARCH_ASE_M16 0x04000000 +#define EF_MIPS_ARCH_ASE_MDMX 0x08000000 + /* The ABI of a file. */ #define EF_MIPS_ABI_O32 0x00001000 /* O32 ABI. */ #define EF_MIPS_ABI_O64 0x00002000 /* O32 extended for 64 bit. */ @@ -594,25 +601,53 @@ typedef struct { /* Bits present in AT_HWCAP for s390. */ -#define HWCAP_S390_ESAN3 1 -#define HWCAP_S390_ZARCH 2 -#define HWCAP_S390_STFLE 4 -#define HWCAP_S390_MSA 8 -#define HWCAP_S390_LDISP 16 -#define HWCAP_S390_EIMM 32 -#define HWCAP_S390_DFP 64 -#define HWCAP_S390_HPAGE 128 -#define HWCAP_S390_ETF3EH 256 -#define HWCAP_S390_HIGH_GPRS 512 -#define HWCAP_S390_TE 1024 -#define HWCAP_S390_VXRS 2048 -#define HWCAP_S390_VXRS_BCD 4096 -#define HWCAP_S390_VXRS_EXT 8192 -#define HWCAP_S390_GS 16384 -#define HWCAP_S390_VXRS_EXT2 32768 -#define HWCAP_S390_VXRS_PDE 65536 -#define HWCAP_S390_SORT 131072 -#define HWCAP_S390_DFLT 262144 +#define HWCAP_S390_NR_ESAN3 0 +#define HWCAP_S390_NR_ZARCH 1 +#define HWCAP_S390_NR_STFLE 2 +#define HWCAP_S390_NR_MSA 3 +#define HWCAP_S390_NR_LDISP 4 +#define HWCAP_S390_NR_EIMM 5 +#define HWCAP_S390_NR_DFP 6 +#define HWCAP_S390_NR_HPAGE 7 +#define HWCAP_S390_NR_ETF3EH 8 +#define HWCAP_S390_NR_HIGH_GPRS 9 +#define HWCAP_S390_NR_TE 10 +#define HWCAP_S390_NR_VXRS 11 +#define HWCAP_S390_NR_VXRS_BCD 12 +#define HWCAP_S390_NR_VXRS_EXT 13 +#define HWCAP_S390_NR_GS 14 +#define HWCAP_S390_NR_VXRS_EXT2 15 +#define HWCAP_S390_NR_VXRS_PDE 16 +#define HWCAP_S390_NR_SORT 17 +#define HWCAP_S390_NR_DFLT 18 +#define HWCAP_S390_NR_VXRS_PDE2 19 +#define HWCAP_S390_NR_NNPA 20 +#define HWCAP_S390_NR_PCI_MIO 21 +#define HWCAP_S390_NR_SIE 22 + +#define HWCAP_S390_ESAN3 (1 << HWCAP_S390_NR_ESAN3) +#define HWCAP_S390_ZARCH (1 << HWCAP_S390_NR_ZARCH) +#define HWCAP_S390_STFLE (1 << HWCAP_S390_NR_STFLE) +#define HWCAP_S390_MSA (1 << HWCAP_S390_NR_MSA) +#define HWCAP_S390_LDISP (1 << HWCAP_S390_NR_LDISP) +#define HWCAP_S390_EIMM (1 << HWCAP_S390_NR_EIMM) +#define HWCAP_S390_DFP (1 << HWCAP_S390_NR_DFP) +#define HWCAP_S390_HPAGE (1 << HWCAP_S390_NR_HPAGE) +#define HWCAP_S390_ETF3EH (1 << HWCAP_S390_NR_ETF3EH) +#define HWCAP_S390_HIGH_GPRS (1 << HWCAP_S390_NR_HIGH_GPRS) +#define HWCAP_S390_TE (1 << HWCAP_S390_NR_TE) +#define HWCAP_S390_VXRS (1 << HWCAP_S390_NR_VXRS) +#define HWCAP_S390_VXRS_BCD (1 << HWCAP_S390_NR_VXRS_BCD) +#define HWCAP_S390_VXRS_EXT (1 << HWCAP_S390_NR_VXRS_EXT) +#define HWCAP_S390_GS (1 << HWCAP_S390_NR_GS) +#define HWCAP_S390_VXRS_EXT2 (1 << HWCAP_S390_NR_VXRS_EXT2) +#define HWCAP_S390_VXRS_PDE (1 << HWCAP_S390_NR_VXRS_PDE) +#define HWCAP_S390_SORT (1 << HWCAP_S390_NR_SORT) +#define HWCAP_S390_DFLT (1 << HWCAP_S390_NR_DFLT) +#define HWCAP_S390_VXRS_PDE2 (1 << HWCAP_S390_NR_VXRS_PDE2) +#define HWCAP_S390_NNPA (1 << HWCAP_S390_NR_NNPA) +#define HWCAP_S390_PCI_MIO (1 << HWCAP_S390_NR_PCI_MIO) +#define HWCAP_S390_SIE (1 << HWCAP_S390_NR_SIE) /* M68K specific definitions. */ /* We use the top 24 bits to encode information about the @@ -1114,10 +1149,10 @@ typedef struct { #define EFA_PARISC_1_1 0x0210 /* PA-RISC 1.1 big-endian. */ #define EFA_PARISC_2_0 0x0214 /* PA-RISC 2.0 big-endian. */ -/* Additional section indeces. */ +/* Additional section indices. */ -#define SHN_PARISC_ANSI_COMMON \ - 0xff00 /* Section for tenatively declared \ +#define SHN_PARISC_ANSI_COMMON \ + 0xff00 /* Section for tentatively declared \ symbols in ANSI C. */ #define SHN_PARISC_HUGE_COMMON 0xff01 /* Common blocks in huge model. */ diff --git a/libtcg/src/optimize.c b/libtcg/src/optimize.c index 820d44136..8e2c3c2e4 100644 --- a/libtcg/src/optimize.c +++ b/libtcg/src/optimize.c @@ -25,6 +25,7 @@ #include +#include "tcg/utils/bswap.h" #include "tcg/utils/int128.h" #include "tcg/utils/interval-tree.h" #include "tcg/utils/osdep.h" diff --git a/libtcg/src/utils/cpuinfo-i386.c b/libtcg/src/utils/cpuinfo-i386.c index 515f820d5..d0658346e 100644 --- a/libtcg/src/utils/cpuinfo-i386.c +++ b/libtcg/src/utils/cpuinfo-i386.c @@ -1,6 +1,6 @@ /* * SPDX-License-Identifier: GPL-2.0-or-later - * Host specific cpu indentification for x86. + * Host specific cpu identification for x86. */ #include @@ -34,11 +34,11 @@ unsigned __attribute__((constructor)) cpuinfo_init(void) { if (max >= 1) { __cpuid(1, a, b, c, d); - info |= (d & bit_CMOV ? CPUINFO_CMOV : 0); info |= (d & bit_SSE2 ? CPUINFO_SSE2 : 0); - info |= (c & bit_SSE4_1 ? CPUINFO_SSE4 : 0); + info |= (c & bit_OSXSAVE ? CPUINFO_OSXSAVE : 0); info |= (c & bit_MOVBE ? CPUINFO_MOVBE : 0); info |= (c & bit_POPCNT ? CPUINFO_POPCNT : 0); + info |= (c & bit_PCLMUL ? CPUINFO_PCLMUL : 0); /* Our AES support requires PSHUFB as well. */ info |= ((c & bit_AES) && (c & bit_SSSE3) ? CPUINFO_AES : 0); @@ -50,6 +50,7 @@ unsigned __attribute__((constructor)) cpuinfo_init(void) { if ((bv & 6) == 6) { info |= CPUINFO_AVX1; info |= (b7 & bit_AVX2 ? CPUINFO_AVX2 : 0); + info |= (c7 & bit_GFNI ? CPUINFO_GFNI : 0); if ((bv & 0xe0) == 0xe0) { info |= (b7 & bit_AVX512F ? CPUINFO_AVX512F : 0); @@ -74,7 +75,7 @@ unsigned __attribute__((constructor)) cpuinfo_init(void) { * of their memory operands to be 16-byte aligned. * * AMD has provided an even stronger guarantee that processors - * with AVX provide 16-byte atomicity for all cachable, + * with AVX provide 16-byte atomicity for all cacheable, * naturally aligned single loads and stores, e.g. MOVDQU. * * See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104688 From 5b059a57c07fcc55f9d9c27614b318f0dd54f527 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Tue, 18 Aug 2026 16:35:14 +0000 Subject: [PATCH 09/52] skills: recorded the utils deviations in the libtcg upgrade skill Adds the three deviations found while upgrading utils, and corrects the claim that most of utils/ lags the TCG core: it no longer does. What still lags is the set of hand written subsets flagged in mapping.tsv. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- .claude/skills/upgrade-libtcg/SKILL.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/.claude/skills/upgrade-libtcg/SKILL.md b/.claude/skills/upgrade-libtcg/SKILL.md index 1934b585e..7f5a9d4f9 100644 --- a/.claude/skills/upgrade-libtcg/SKILL.md +++ b/.claude/skills/upgrade-libtcg/SKILL.md @@ -34,8 +34,10 @@ include block or where S2E's `extern "C"` guard meets appended upstream code. cat libtcg/scripts/upgrade/BASELINE # the tag libtcg currently tracks git -C ~/qemu log --oneline .. -- tcg/ include/tcg/ -**libtcg is not uniformly at one version.** Only the TCG core tracks `BASELINE`; -much of `utils/` still sits at v8.1.0. Before assuming a file's baseline, check +**libtcg is not uniformly at one version.** The TCG core, `fpu/` and most of +`utils/` track `BASELINE`, but the hand-written subsets flagged in `mapping.tsv` +(`osdep.h`, `cutils.*`, `log.*`, `bitmap.h`, `bswap.h`) are still v8.1.0-era and +are not vendored. Before assuming a file's baseline, check it: format the file at several candidate tags and pick the smallest diff. A file that is stale relative to its neighbours is a bug waiting to happen — the 11.1 upgrade found `tcg-gvec-desc.h` stranded at an old descriptor encoding while @@ -126,6 +128,13 @@ body, especially for anything that deviates from upstream. - **`accel/getpc.h`** drops upstream's `#ifndef CONFIG_TCG #error` guard. - **`exec/helper-head.h.inc`** keeps its `#ifdef TARGET_LONG_BITS` guard instead of including `exec/target_long.h`. +- **`host/generic/atomic128-cas.h`** renames the `new` parameter to `_new`. + These headers are included from C++, where `new` is a keyword. +- **`utils/bitops.h`** wraps `#define BIT(nr)` in `#ifndef BIT`, because + `libcpu/include/cpu/kvm.h` also defines it. +- **`utils/osdep.h`** carries what upstream keeps in `include/qemu/compiler.h` + (`QEMU_FLATTEN`, `QEMU_ALWAYS_INLINE`, `typeof_strip_qual`, ...). When a merge + pulls in code that needs a new compiler macro, add it here. ## The libcpu fallout From 097a4635e5b1b9e8ebb66e1ab0a6e5422db3655f Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Tue, 18 Aug 2026 16:45:00 +0000 Subject: [PATCH 10/52] libtcg: reclassified memalign.h as hand written utils/memalign.h is a three declaration stub, not a reduced copy of upstream's header, which is why its diff against upstream never moved across any release. Group it with the other hand written subsets so the mapping does not imply it tracks BASELINE. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- libtcg/scripts/upgrade/mapping.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libtcg/scripts/upgrade/mapping.tsv b/libtcg/scripts/upgrade/mapping.tsv index c895b7bd5..e68360543 100644 --- a/libtcg/scripts/upgrade/mapping.tsv +++ b/libtcg/scripts/upgrade/mapping.tsv @@ -78,7 +78,6 @@ include/tcg/utils/debug-assert.h include/tcg/debug-assert.h include/tcg/utils/host-utils.h include/qemu/host-utils.h include/tcg/utils/int128.h include/qemu/int128.h include/tcg/utils/interval-tree.h include/qemu/interval-tree.h -include/tcg/utils/memalign.h include/qemu/memalign.h include/tcg/utils/qtree.h include/qemu/qtree.h include/tcg/utils/units.h include/qemu/units.h include/tcg/utils/registerfields.h include/hw/core/registerfields.h @@ -91,6 +90,7 @@ src/elf.h include/elf.h # Heavily reduced S2E-specific subsets, still v8.1.0-era: these are hand # written rather than vendored, so merge by hand, not mechanically. include/tcg/utils/bswap.h include/qemu/bswap.h +include/tcg/utils/memalign.h include/qemu/memalign.h include/tcg/utils/bitmap.h include/qemu/bitmap.h include/tcg/utils/cutils.h include/qemu/cutils.h include/tcg/utils/log.h include/qemu/log.h From c2720354518adf62be8deedf82cd0dd7d2c15db4 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Wed, 19 Aug 2026 14:55:56 +0000 Subject: [PATCH 11/52] Avoid raw_string_ostream::str() and redundant stringstream copies llvm::raw_string_ostream::str() is on its way out upstream ("In most cases it is better to simply use the underlying std::string directly. TODO: Consider removing this API."). Flush the stream and use the backing std::string instead, matching the idiom already used elsewhere in the tree. In KModule::evalConstantExpr the raw_string_ostream wrappers were only ever used to fetch the message back out, so they are dropped entirely. Also stop building asio buffers from `ss.str().c_str()` with a second `ss.str().length()` call: that materialized two temporary strings per write. Take the string once and let asio::buffer deduce the length. Co-Authored-By: Claude Opus 5 --- klee/include/klee/Expr.h | 6 ++++-- klee/include/klee/util/PrintContext.h | 3 ++- klee/lib/Core/ExecutionState.cpp | 4 +++- klee/lib/Module/KModule.cpp | 16 +++++++++------- klee/lib/Solver/QueryLoggingSolver.cpp | 2 +- libs2ecore/src/s2e-qmp.cpp | 3 ++- .../src/s2e/Plugins/Analyzers/CFIChecker.cpp | 6 ++++-- .../src/s2e/Plugins/Support/KeyValueStore.cpp | 13 ++++++++----- libvmi/src/PEFile.cpp | 3 ++- 9 files changed, 35 insertions(+), 21 deletions(-) diff --git a/klee/include/klee/Expr.h b/klee/include/klee/Expr.h index 5a24d2a1a..976060086 100644 --- a/klee/include/klee/Expr.h +++ b/klee/include/klee/Expr.h @@ -317,7 +317,8 @@ inline std::ostream &operator<<(std::ostream &out, const Expr::Kind kind) { std::string ss; llvm::raw_string_ostream ros(ss); Expr::printKind(ros, kind); - out << ros.str(); + ros.flush(); + out << ss; return out; } @@ -325,7 +326,8 @@ inline std::ostream &operator<<(std::ostream &out, const klee::ref & std::string ss; llvm::raw_string_ostream ros(ss); ros << expr; - out << ros.str(); + ros.flush(); + out << ss; return out; } diff --git a/klee/include/klee/util/PrintContext.h b/klee/include/klee/util/PrintContext.h index ef30388cb..93a8c2528 100644 --- a/klee/include/klee/util/PrintContext.h +++ b/klee/include/klee/util/PrintContext.h @@ -85,7 +85,8 @@ class PrintContext { std::string str; llvm::raw_string_ostream ss(str); ss << elt; - write(ss.str()); + ss.flush(); + write(str); return *this; } }; diff --git a/klee/lib/Core/ExecutionState.cpp b/klee/lib/Core/ExecutionState.cpp index 99b671064..e2f2af41a 100644 --- a/klee/lib/Core/ExecutionState.cpp +++ b/klee/lib/Core/ExecutionState.cpp @@ -339,7 +339,9 @@ ref ExecutionState::toConstant(ref e, const std::string &rea os << " to value " << value; - klee_warning_external(reason.c_str(), "%s", os.str().c_str()); + os.flush(); + + klee_warning_external(reason.c_str(), "%s", s.c_str()); if (!addConstraint(EqExpr::create(e, value))) { abort(); diff --git a/klee/lib/Module/KModule.cpp b/klee/lib/Module/KModule.cpp index 1efc6677a..ca24d2a9c 100644 --- a/klee/lib/Module/KModule.cpp +++ b/klee/lib/Module/KModule.cpp @@ -647,7 +647,12 @@ ref KModule::evalConstant(const GlobalAddresses &globalAddre } else { std::string msg("Cannot handle constant "); llvm::raw_string_ostream os(msg); - klee_error("%s", os.str().c_str()); + os << *c << " of type " << *c->getType(); + if (ki && ki->inst) { + os << " at " << *ki->inst; + } + os.flush(); + klee_error("%s", msg.c_str()); } } } @@ -674,8 +679,7 @@ klee::ref KModule::evalConstantExpr(const GlobalAddresses &g case Instruction::URem: if (op2->getLimitedValue() == 0) { std::string msg("Division/modulo by zero during constant folding at location "); - llvm::raw_string_ostream os(msg); - klee_error("%s", os.str().c_str()); + klee_error("%s", msg.c_str()); } break; case Instruction::Shl: @@ -683,17 +687,15 @@ klee::ref KModule::evalConstantExpr(const GlobalAddresses &g case Instruction::AShr: if (op2->getLimitedValue() >= op1->getWidth()) { std::string msg("Overshift during constant folding at location "); - llvm::raw_string_ostream os(msg); - klee_error("%s", os.str().c_str()); + klee_error("%s", msg.c_str()); } } std::string msg("Unknown ConstantExpr type"); - llvm::raw_string_ostream os(msg); switch (ce->getOpcode()) { default: - klee_error("%s", os.str().c_str()); + klee_error("%s", msg.c_str()); case Instruction::Trunc: return op1->Extract(0, getWidthForLLVMType(type)); diff --git a/klee/lib/Solver/QueryLoggingSolver.cpp b/klee/lib/Solver/QueryLoggingSolver.cpp index 26a46c7de..bceebf7ca 100644 --- a/klee/lib/Solver/QueryLoggingSolver.cpp +++ b/klee/lib/Solver/QueryLoggingSolver.cpp @@ -60,7 +60,7 @@ QueryLoggingSolver::~QueryLoggingSolver() { void QueryLoggingSolver::flushBufferConditionally(bool writeToFile) { logBuffer.flush(); if (writeToFile) { - *os << logBuffer.str(); + *os << BufferString; os->flush(); } // prepare the buffer for reuse diff --git a/libs2ecore/src/s2e-qmp.cpp b/libs2ecore/src/s2e-qmp.cpp index c075c6bb4..a1221df4b 100644 --- a/libs2ecore/src/s2e-qmp.cpp +++ b/libs2ecore/src/s2e-qmp.cpp @@ -89,7 +89,8 @@ void S2EQMPClient::emitJson(QObject *obj) { qobject_unref(obj); try { - boost::asio::write(m_socket, boost::asio::buffer(data.str().c_str(), data.str().length())); + auto payload = data.str(); + boost::asio::write(m_socket, boost::asio::buffer(payload)); } catch (std::exception &e) { std::cerr << "s2e-qmp: could not write to socket\n"; m_socket.close(); diff --git a/libs2eplugins/src/s2e/Plugins/Analyzers/CFIChecker.cpp b/libs2eplugins/src/s2e/Plugins/Analyzers/CFIChecker.cpp index 66558aeca..2975ffcda 100644 --- a/libs2eplugins/src/s2e/Plugins/Analyzers/CFIChecker.cpp +++ b/libs2eplugins/src/s2e/Plugins/Analyzers/CFIChecker.cpp @@ -174,7 +174,8 @@ struct CFIViolation { llvm::raw_string_ostream ss1(s1); if (state->disassemble(ss1, destPc, 32)) { os << "Disassembly at " << hexval(destPc) << "\n"; - os << ss1.str() << "\n"; + ss1.flush(); + os << s1 << "\n"; } else { os << "Could not disassemble " << hexval(destPc) << "\n"; } @@ -184,7 +185,8 @@ struct CFIViolation { llvm::raw_string_ostream ss2(s2); if (state->disassemble(ss2, expectedDestPc, 32)) { os << "Disassembly at " << hexval(expectedDestPc) << "\n"; - os << ss2.str() << "\n"; + ss2.flush(); + os << s2 << "\n"; } else { os << "Could not disassemble " << hexval(expectedDestPc) << "\n"; } diff --git a/libs2eplugins/src/s2e/Plugins/Support/KeyValueStore.cpp b/libs2eplugins/src/s2e/Plugins/Support/KeyValueStore.cpp index 9a9b0409e..16c1e0ca5 100644 --- a/libs2eplugins/src/s2e/Plugins/Support/KeyValueStore.cpp +++ b/libs2eplugins/src/s2e/Plugins/Support/KeyValueStore.cpp @@ -98,7 +98,8 @@ void KeyValueStore::connectNative() { if (m_session_id.size() == 0) { ss << "get-session-id\n"; - boost::asio::write(m_socket, boost::asio::buffer(ss.str().c_str(), ss.str().length())); + auto request = ss.str(); + boost::asio::write(m_socket, boost::asio::buffer(request)); boost::asio::streambuf streamBuf; if (!syncReadUntil(streamBuf, "\n")) { @@ -111,7 +112,8 @@ void KeyValueStore::connectNative() { getDebugStream() << "KeyValueStore: got session id " << m_session_id << "\n"; } else { ss << "set-session-id " << m_session_id << "\n"; - boost::asio::write(m_socket, boost::asio::buffer(ss.str().c_str(), ss.str().length())); + auto request = ss.str(); + boost::asio::write(m_socket, boost::asio::buffer(request)); } } catch (std::exception &e) { @@ -188,8 +190,8 @@ bool KeyValueStore::put(const std::string &key, const std::string &value) { } else if (m_server_type == ST_NATIVE) { std::stringstream ss; ss << "set-value " << key << "=" << value << "\n"; - boost::asio::write(m_socket, boost::asio::buffer(ss.str().c_str(), ss.str().length()), - boost::asio::transfer_all()); + auto request = ss.str(); + boost::asio::write(m_socket, boost::asio::buffer(request), boost::asio::transfer_all()); return true; } else if (m_server_type == ST_LOCAL) { m_global_storage[key] = value; @@ -226,7 +228,8 @@ bool KeyValueStore::get(const std::string &key, std::string &val) { } else if (m_server_type == ST_NATIVE) { std::stringstream ss; ss << "get-value " << key << "\n"; - boost::asio::write(m_socket, boost::asio::buffer(ss.str().c_str(), ss.str().length())); + auto request = ss.str(); + boost::asio::write(m_socket, boost::asio::buffer(request)); boost::asio::streambuf streamBuf; if (!syncReadUntil(streamBuf, "\n")) { diff --git a/libvmi/src/PEFile.cpp b/libvmi/src/PEFile.cpp index 2ef66ea64..ccc89a2fd 100644 --- a/libvmi/src/PEFile.cpp +++ b/libvmi/src/PEFile.cpp @@ -168,7 +168,8 @@ bool PEFile::initExports(void) { std::string _str; llvm::raw_string_ostream FunctionName(_str); FunctionName << i; - m_exports[FuncRva + m_loadAddress] = FunctionName.str(); + FunctionName.flush(); + m_exports[FuncRva + m_loadAddress] = _str; } return true; From 5b698e2424ec8914e29543a92f2438c6b3a2d862 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Wed, 19 Aug 2026 15:30:43 +0000 Subject: [PATCH 12/52] klee: stripped the aliasing hints that broke module preparation Upgrading softfloat to qemu 11.1 brought in the parts128/float128 code. Its helpers take noalias qualified pointers, so clang emits llvm.experimental.noalias.scope.decl at every inlining site, and the op_helper bitcode now carries fourteen of them. The engine died before executing a single instruction: KLEE: ERROR: Cannot handle constant !58 = !{!59} of type metadata at tail call void @llvm.experimental.noalias.scope.decl(metadata !58) The hint is a pure aliasing annotation with no run time semantics, but IntrinsicCleaner did not know it and only warned, so the call survived into the constant table. Erase it instead, which is what its lack of semantics allows. That the metadata reached evalConstant() at all is a second defect. KFunction had two copies of the operand classification: getOperandNum() for calls and an inline one for everything else. Only the inline copy tried to reject metadata, and its isa(ValueAsMetadata::get(v)) test can never be true, since ValueAsMetadata::get() returns a ValueAsMetadata and never an MDNode. Metadata arguments therefore fell through to assert(isa(v)), which in a release build degrades into the error above. Test for MetadataAsValue in getOperandNum() and route the non-call operands through it, so the two paths cannot drift apart again. Two unit tests cover this. NoAliasScopeDeclDoesNotBreakThePreparePasses runs a function built from a fixture that clang compiles with the hints in place, and MetadataOperandsAreNotInterned pins the classification using llvm.type.test, an intrinsic the cleaner deliberately leaves alone. Both abort without the fix. Co-Authored-By: Claude Opus 5 --- klee/lib/Module/IntrinsicCleaner.cpp | 10 +++ klee/lib/Module/KModule.cpp | 21 +++---- klee/unittests/Core/CMakeLists.txt | 13 +++- klee/unittests/Core/ExecutorTest.cpp | 91 ++++++++++++++++++++++++++++ klee/unittests/Core/LLVM/noalias.c | 36 +++++++++++ 5 files changed, 155 insertions(+), 16 deletions(-) create mode 100644 klee/unittests/Core/LLVM/noalias.c diff --git a/klee/lib/Module/IntrinsicCleaner.cpp b/klee/lib/Module/IntrinsicCleaner.cpp index df1b566f3..f122d1641 100644 --- a/klee/lib/Module/IntrinsicCleaner.cpp +++ b/klee/lib/Module/IntrinsicCleaner.cpp @@ -474,6 +474,16 @@ bool IntrinsicCleanerPass::runOnBasicBlock(BasicBlock &b, Module &M) { break; } + case Intrinsic::experimental_noalias_scope_decl: { + // A pure aliasing hint with no semantics, emitted by clang when + // it inlines a function with noalias/restrict parameters. Its + // only operand is metadata, which evalConstant() cannot + // evaluate, so the call has to go rather than merely warn. + ii->eraseFromParent(); + dirty = true; + break; + } + // The following intrinsics are currently handled by LowerIntrinsicCall // (Invoking LowerIntrinsicCall with any intrinsics not on this // list throws an exception.) diff --git a/klee/lib/Module/KModule.cpp b/klee/lib/Module/KModule.cpp index ca24d2a9c..06c406d7a 100644 --- a/klee/lib/Module/KModule.cpp +++ b/klee/lib/Module/KModule.cpp @@ -30,6 +30,7 @@ #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LegacyPassManager.h" +#include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" #include "llvm/IR/Operator.h" #include "llvm/IR/ValueSymbolTable.h" @@ -823,7 +824,11 @@ static int getOperandNum(Value *v, std::map ®isterMa return registerMap[inst]; } else if (Argument *a = dyn_cast(v)) { return a->getArgNo(); - } else if (isa(v) || isa(v)) { + } else if (isa(v) || isa(v) || isa(v)) { + // Metadata carries no value, so there is nothing to read at run time. + // Intrinsics that take it (llvm.experimental.noalias.scope.decl and + // friends) must be stripped by IntrinsicCleaner, but do not crash the + // constant table if one slips through. return -1; } else { assert(isa(v)); @@ -901,19 +906,7 @@ KFunction::KFunction(llvm::Function *_function, KModule *km) : function(_functio unsigned numOperands = it->getNumOperands(); ki->operands = new int[numOperands]; for (unsigned j = 0; j < numOperands; j++) { - Value *v = it->getOperand(j); - - if (Instruction *inst = dyn_cast(v)) { - ki->operands[j] = registerMap[inst]; - } else if (Argument *a = dyn_cast(v)) { - ki->operands[j] = a->getArgNo(); - } else if (isa(v) || isa(v) || isa(ValueAsMetadata::get(v))) { - ki->operands[j] = -1; - } else { - assert(isa(v)); - Constant *c = cast(v); - ki->operands[j] = -(km->getConstantID(c, ki) + 2); - } + ki->operands[j] = getOperandNum(it->getOperand(j), registerMap, km, ki); } } diff --git a/klee/unittests/Core/CMakeLists.txt b/klee/unittests/Core/CMakeLists.txt index fd6fe33fd..df08296ec 100644 --- a/klee/unittests/Core/CMakeLists.txt +++ b/klee/unittests/Core/CMakeLists.txt @@ -10,10 +10,10 @@ target_link_libraries(ExecutorTest PRIVATE kleeCore kleeModule kleaverSolver kle # Compile C sources to LLVM bitcode and expose their paths to the test. find_program(CLANG_EXECUTABLE NAMES clang-19 clang REQUIRED) -foreach(src add compute function) +function(add_bitcode_fixture src) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${src}.bc - COMMAND ${CLANG_EXECUTABLE} -emit-llvm -c -O0 + COMMAND ${CLANG_EXECUTABLE} -emit-llvm -c ${ARGN} ${CMAKE_CURRENT_SOURCE_DIR}/LLVM/${src}.c -o ${CMAKE_CURRENT_BINARY_DIR}/${src}.bc DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/LLVM/${src}.c @@ -21,10 +21,19 @@ foreach(src add compute function) ) add_custom_target(${src}_bc DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${src}.bc) add_dependencies(ExecutorTest ${src}_bc) +endfunction() + +foreach(src add compute function) + add_bitcode_fixture(${src} -O0) endforeach() +# The aliasing hints only show up once the inliner has run. Contraction is +# turned off to keep the fixture down to the hints and plain arithmetic. +add_bitcode_fixture(noalias -O2 -ffp-contract=off) + target_compile_definitions(ExecutorTest PRIVATE ADD_BC_PATH="${CMAKE_CURRENT_BINARY_DIR}/add.bc" COMPUTE_BC_PATH="${CMAKE_CURRENT_BINARY_DIR}/compute.bc" FUNCTION_BC_PATH="${CMAKE_CURRENT_BINARY_DIR}/function.bc" + NOALIAS_BC_PATH="${CMAKE_CURRENT_BINARY_DIR}/noalias.bc" ) diff --git a/klee/unittests/Core/ExecutorTest.cpp b/klee/unittests/Core/ExecutorTest.cpp index eec722ffa..8051084ea 100644 --- a/klee/unittests/Core/ExecutorTest.cpp +++ b/klee/unittests/Core/ExecutorTest.cpp @@ -177,6 +177,15 @@ class TestExecutor : public Executor { return nullptr; } + /// Build the KFunction for \p fn without running it. + /// + /// Constructing a KFunction is what walks the operands of every + /// instruction and interns the constant ones, so this is enough to + /// exercise the operand classification on its own. + KFunction *prepareFunction(llvm::Function *fn) { + return m_kmodule->bindFunctionConstants(m_globalAddresses, fn); + } + /// Execute the state until a ret instruction is reached. /// /// Stops just before executing ret so that the caller can inspect @@ -1551,4 +1560,86 @@ TEST(ExecutorTest, ICmpSLE) { EXPECT_EQ(evalICmp(ICmpInst::ICMP_SLE, 1, 0xFFFFFFFFu), 0u); // 1 <=s -1 → false } +// ============================================================ +// llvm.experimental.noalias.scope.decl +// +// Its only operand is metadata, which has no value to read at run time. +// Leaving the call in place used to abort the engine while interning the +// constants of the enclosing function. +// ============================================================ + +TEST(ExecutorTest, NoAliasScopeDeclDoesNotBreakThePreparePasses) { + llvm::LLVMContext ctx; + + // The hints must be in the fixture, otherwise the test proves nothing. + auto buf = llvm::MemoryBuffer::getFile(NOALIAS_BC_PATH); + ASSERT_TRUE(!!buf); + auto raw = llvm::parseBitcodeFile(buf.get()->getMemBufferRef(), ctx); + ASSERT_TRUE(!!raw); + ASSERT_NE(raw.get()->getFunction("llvm.experimental.noalias.scope.decl"), nullptr) + << "the fixture no longer contains any aliasing hint"; + + llvm::LLVMContext execCtx; + TestExecutor executor(execCtx, NOALIAS_BC_PATH); + auto *m = executor.getLLVMModule(); + + auto *hint = m->getFunction("llvm.experimental.noalias.scope.decl"); + EXPECT_TRUE(hint == nullptr || hint->use_empty()) << "the aliasing hints should have been stripped"; + + llvm::Function *fn = m->getFunction("noalias_dot2"); + ASSERT_NE(fn, nullptr); + + double a[2] = {1.5, 2.5}; + double b[2] = {3.0, 4.0}; + + ExecutionStatePtr state = executor.createState(); + state->addExternalObject(a, sizeof(a), /*isReadOnly=*/true, /*isSharedConcrete=*/false); + state->addExternalObject(b, sizeof(b), /*isReadOnly=*/true, /*isSharedConcrete=*/false); + + unsigned ptrWidth = executor.getModule()->getDataLayout()->getPointerSizeInBits(); + auto result = executor.runFunction( + *state, fn, + {klee::ConstantExpr::create((uint64_t) a, ptrWidth), klee::ConstantExpr::create((uint64_t) b, ptrWidth)}); + + ASSERT_NE(result.get(), nullptr); + auto *ce = dyn_cast(result); + ASSERT_NE(ce, nullptr); + // 1.5 * 3.0 + 2.5 * 4.0 = 14.5 + EXPECT_EQ(ce->getZExtValue(), 0x402D000000000000ULL); +} + +// ============================================================ +// Metadata operands +// +// An intrinsic that the cleaner does not know about keeps its metadata +// operand. Such an operand carries no value, so it must be classified as +// invalid instead of being interned as a constant. +// ============================================================ + +TEST(ExecutorTest, MetadataOperandsAreNotInterned) { + llvm::LLVMContext ctx; + TestExecutor executor(ctx); + auto *mod = executor.getLLVMModule(); + + // llvm.type.test(ptr, metadata) is not handled by IntrinsicCleaner, so it + // reaches the constant table with its metadata operand intact. + auto *hint = llvm::Intrinsic::getDeclaration(mod, llvm::Intrinsic::type_test); + + auto *i32Ty = llvm::Type::getInt32Ty(ctx); + auto *fn = llvm::Function::Create(llvm::FunctionType::get(i32Ty, false), llvm::Function::ExternalLinkage, + "with_metadata", mod); + llvm::IRBuilder<> builder(llvm::BasicBlock::Create(ctx, "entry", fn)); + auto *call = builder.CreateCall(hint, {llvm::ConstantPointerNull::get(llvm::PointerType::getUnqual(ctx)), + llvm::MetadataAsValue::get(ctx, llvm::MDString::get(ctx, "typeid"))}); + builder.CreateRet(llvm::ConstantInt::get(i32Ty, 42)); + + auto *kf = executor.prepareFunction(fn); + ASSERT_NE(kf, nullptr); + + auto *ki = kf->getInstruction(call); + ASSERT_NE(ki, nullptr); + // operands[0] is the callee, then one entry per argument. + EXPECT_EQ(ki->operands[2], -1) << "the metadata operand must not have a constant table entry"; +} + } // namespace diff --git a/klee/unittests/Core/LLVM/noalias.c b/klee/unittests/Core/LLVM/noalias.c new file mode 100644 index 000000000..c4d4bbd45 --- /dev/null +++ b/klee/unittests/Core/LLVM/noalias.c @@ -0,0 +1,36 @@ +/// +/// Copyright (C) 2026, Vitaly Chipounov +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy +/// of this software and associated documentation files (the "Software"), to deal +/// in the Software without restriction, including without limitation the rights +/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +/// copies of the Software, and to permit persons to whom the Software is +/// furnished to do so, subject to the following conditions: +/// +/// The above copyright notice and this permission notice shall be included in all +/// copies or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +/// SOFTWARE. +/// + +// Reproduces the aliasing hints that broke the engine when softfloat was +// upgraded to qemu 11.1: inlining a function with restrict qualified pointer +// parameters makes clang emit llvm.experimental.noalias.scope.decl, whose only +// operand is metadata. +// +// Must be compiled at -O2, the hints only appear once the inliner has run. + +static inline double dot2(const double *restrict a, const double *restrict b) { + return a[0] * b[0] + a[1] * b[1]; +} + +double noalias_dot2(const double *a, const double *b) { + return dot2(a, b); +} From 40397913a73d852d293389651e6e429035904d93 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Wed, 19 Aug 2026 15:31:32 +0000 Subject: [PATCH 13/52] klee: handled the fp intrinsics of the hard float fast paths softfloat only falls back to its own arithmetic when the host cannot do the job, and the fast paths it takes instead compile down to intrinsics that the engine did not know. float64_add() and float64_sub() classify their operands with __builtin_isnormal(), which clang 19 lowers to llvm.is.fpclass, and float32_muladd()/float64_muladd() call fma(). helper_fprem1() has been using llvm.rint and llvm.fmuladd for longer. IntrinsicCleaner only warned about all of these, and an unhandled intrinsic reaching executeCall() is a klee_error, so the first guest double addition executed as bitcode would have taken the engine down. llvm.is.fpclass is expanded into integer tests on the raw encoding of its operand: exponent and mantissa are compared against the constants that delimit each class, and the requested classes are or-ed together. Testing the encoding rather than concretizing keeps the predicate symbolic when the operand is, which matters because these tests guard which arithmetic path softfloat takes. x86_fp80 is left out, it stores the leading significand bit explicitly and the tests do not apply. llvm.fmuladd is expanded into a multiply and an add. Contraction is optional for it, so the unfused form is a valid lowering and it also keeps its operands symbolic. llvm.fma has to round once and cannot be expressed that way, so it is evaluated in the Executor with APFloat::fusedMultiplyAdd() on concretized operands, as llvm.fabs already is. llvm.rint and llvm.nearbyint round the same way, through roundToIntegral(). The guest rounding mode is emulated by softfloat itself, so the host one stays at its default of round to nearest, ties to even. The tests run one function per intrinsic out of a fixture that must be compiled at -O0, since at -O1 and above clang folds most of the class predicates into comparisons and the intrinsics disappear. The class predicates are checked against every class and both signs so that a wrong bit shows up as a mismatch rather than cancelling out, and the fused and unfused multiply-adds are separated by an input whose exact result, 2^-104, only survives a single rounding. Co-Authored-By: Claude Opus 5 --- klee/lib/Core/Executor.cpp | 34 +++++ klee/lib/Module/IntrinsicCleaner.cpp | 93 ++++++++++++ klee/unittests/Core/CMakeLists.txt | 5 + klee/unittests/Core/ExecutorTest.cpp | 186 ++++++++++++++++++++++++ klee/unittests/Core/LLVM/fpintrinsics.c | 77 ++++++++++ 5 files changed, 395 insertions(+) create mode 100644 klee/unittests/Core/LLVM/fpintrinsics.c diff --git a/klee/lib/Core/Executor.cpp b/klee/lib/Core/Executor.cpp index d9a60cdd6..4c2d7f1ae 100644 --- a/klee/lib/Core/Executor.cpp +++ b/klee/lib/Core/Executor.cpp @@ -377,6 +377,40 @@ void Executor::executeCall(ExecutionState &state, KInstruction *ki, Function *f, break; } + case Intrinsic::fma: { + ref a = state.toConstant(arguments[0], "floating point"); + ref b = state.toConstant(arguments[1], "floating point"); + ref c = state.toConstant(arguments[2], "floating point"); + auto semantics = fpWidthToSemantics(a->getWidth()); + if (!semantics) { + throw LLVMExecutorException("Unsupported intrinsic llvm.fma call"); + } + + llvm::APFloat Res(*semantics, a->getAPValue()); + Res.fusedMultiplyAdd(llvm::APFloat(*semantics, b->getAPValue()), + llvm::APFloat(*semantics, c->getAPValue()), llvm::APFloat::rmNearestTiesToEven); + + llvmState.bindLocal(ki, ConstantExpr::alloc(Res.bitcastToAPInt())); + break; + } + + case Intrinsic::nearbyint: + case Intrinsic::rint: { + ref arg = state.toConstant(arguments[0], "floating point"); + auto semantics = fpWidthToSemantics(arg->getWidth()); + if (!semantics) { + throw LLVMExecutorException("Unsupported intrinsic llvm.rint call"); + } + + // The guest rounding mode is emulated by softfloat, the host one + // is left at its default of round to nearest, ties to even. + llvm::APFloat Res(*semantics, arg->getAPValue()); + Res.roundToIntegral(llvm::APFloat::rmNearestTiesToEven); + + llvmState.bindLocal(ki, ConstantExpr::alloc(Res.bitcastToAPInt())); + break; + } + case Intrinsic::abs: { if (isa(i->getOperand(0)->getType())) { throw LLVMExecutorException("llvm.abs with vectors is not supported"); diff --git a/klee/lib/Module/IntrinsicCleaner.cpp b/klee/lib/Module/IntrinsicCleaner.cpp index f122d1641..3d76c4813 100644 --- a/klee/lib/Module/IntrinsicCleaner.cpp +++ b/klee/lib/Module/IntrinsicCleaner.cpp @@ -12,6 +12,8 @@ #include #include #include "klee/Config/config.h" +#include "llvm/ADT/APFloat.h" +#include "llvm/ADT/FloatingPointMode.h" #include "llvm/Analysis/MemoryBuiltins.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" @@ -199,6 +201,73 @@ void IntrinsicCleanerPass::injectIntrinsicAddImplementation(Module &M, const std builder.CreateRet(cmp1); } +/// Expand llvm.is.fpclass into integer bit tests on the raw encoding of the +/// operand. Clang emits it for isnormal()/isnan()/fpclassify(), which the +/// hard float fast paths of softfloat use on every guest fp operation. +/// Testing the encoding rather than calling out to libm keeps the result +/// symbolic when the operand is. +static bool expandIsFPClass(IntrinsicInst *ii) { + Value *val = ii->getArgOperand(0); + Type *ty = val->getType(); + + // x86_fp80 stores the leading significand bit explicitly, so the tests + // below do not apply to it. Vectors are handled by the scalarizer pass. + if (!ty->isHalfTy() && !ty->isFloatTy() && !ty->isDoubleTy() && !ty->isFP128Ty()) { + return false; + } + + const uint64_t mask = cast(ii->getArgOperand(1))->getZExtValue(); + + IRBuilder<> builder(ii); + + unsigned bits = ty->getPrimitiveSizeInBits(); + unsigned mantissaBits = APFloat::semanticsPrecision(ty->getFltSemantics()) - 1; + + auto intTy = IntegerType::get(ii->getContext(), bits); + auto constant = [&](const APInt &v) { return ConstantInt::get(intTy, v); }; + + APInt signMask = APInt::getSignedMinValue(bits); + APInt minNormal = APInt::getOneBitSet(bits, mantissaBits); // exp == 1, mantissa == 0 + APInt infinity = APInt::getBitsSetFrom(bits, mantissaBits) & ~signMask; + APInt quietBit = APInt::getOneBitSet(bits, mantissaBits - 1); + + Value *raw = builder.CreateBitCast(val, intTy, "fpclass.bits"); + Value *abs = builder.CreateAnd(raw, constant(~signMask), "fpclass.abs"); + + Value *isNeg = builder.CreateICmpNE(builder.CreateAnd(raw, constant(signMask)), constant(APInt(bits, 0))); + Value *isPos = builder.CreateNot(isNeg); + + Value *isZero = builder.CreateICmpEQ(abs, constant(APInt(bits, 0))); + Value *isSubnormal = builder.CreateAnd(builder.CreateNot(isZero), builder.CreateICmpULT(abs, constant(minNormal))); + Value *isInf = builder.CreateICmpEQ(abs, constant(infinity)); + Value *isNan = builder.CreateICmpUGT(abs, constant(infinity)); + Value *isNormal = builder.CreateAnd(builder.CreateICmpUGE(abs, constant(minNormal)), + builder.CreateICmpULT(abs, constant(infinity))); + Value *isQuiet = builder.CreateICmpNE(builder.CreateAnd(abs, constant(quietBit)), constant(APInt(bits, 0))); + + Value *result = builder.getFalse(); + auto testClass = [&](FPClassTest test, Value *cond) { + if (mask & test) { + result = builder.CreateOr(result, cond); + } + }; + + testClass(fcSNan, builder.CreateAnd(isNan, builder.CreateNot(isQuiet))); + testClass(fcQNan, builder.CreateAnd(isNan, isQuiet)); + testClass(fcNegInf, builder.CreateAnd(isInf, isNeg)); + testClass(fcNegNormal, builder.CreateAnd(isNormal, isNeg)); + testClass(fcNegSubnormal, builder.CreateAnd(isSubnormal, isNeg)); + testClass(fcNegZero, builder.CreateAnd(isZero, isNeg)); + testClass(fcPosZero, builder.CreateAnd(isZero, isPos)); + testClass(fcPosSubnormal, builder.CreateAnd(isSubnormal, isPos)); + testClass(fcPosNormal, builder.CreateAnd(isNormal, isPos)); + testClass(fcPosInf, builder.CreateAnd(isInf, isPos)); + + ii->replaceAllUsesWith(result); + ii->eraseFromParent(); + return true; +} + bool IntrinsicCleanerPass::runOnModule(Module &M) { bool dirty = true; @@ -229,8 +298,11 @@ bool IntrinsicCleanerPass::runOnBasicBlock(BasicBlock &b, Module &M) { case Intrinsic::vastart: case Intrinsic::vaend: case Intrinsic::fabs: + case Intrinsic::fma: case Intrinsic::fshr: case Intrinsic::fshl: + case Intrinsic::nearbyint: + case Intrinsic::rint: case Intrinsic::abs: case Intrinsic::smax: @@ -474,6 +546,27 @@ bool IntrinsicCleanerPass::runOnBasicBlock(BasicBlock &b, Module &M) { break; } + case Intrinsic::is_fpclass: { + if (!expandIsFPClass(ii)) { + klee_warning_once((void *) ii->getCalledFunction(), "unsupported llvm.is.fpclass operand type"); + break; + } + dirty = true; + break; + } + + case Intrinsic::fmuladd: { + // The fused form is optional, so the unfused expansion is a + // valid lowering and keeps the operands symbolic. + IRBuilder<> builder(ii); + Value *mul = builder.CreateFMul(ii->getArgOperand(0), ii->getArgOperand(1)); + Value *add = builder.CreateFAdd(mul, ii->getArgOperand(2)); + ii->replaceAllUsesWith(add); + ii->eraseFromParent(); + dirty = true; + break; + } + case Intrinsic::experimental_noalias_scope_decl: { // A pure aliasing hint with no semantics, emitted by clang when // it inlines a function with noalias/restrict parameters. Its diff --git a/klee/unittests/Core/CMakeLists.txt b/klee/unittests/Core/CMakeLists.txt index df08296ec..f35bb6995 100644 --- a/klee/unittests/Core/CMakeLists.txt +++ b/klee/unittests/Core/CMakeLists.txt @@ -27,6 +27,10 @@ foreach(src add compute function) add_bitcode_fixture(${src} -O0) endforeach() +# The floating point class predicates must stay unfolded: at -O1 and above +# clang rewrites most of them into comparisons and llvm.is.fpclass disappears. +add_bitcode_fixture(fpintrinsics -O0 -ffp-contract=on) + # The aliasing hints only show up once the inliner has run. Contraction is # turned off to keep the fixture down to the hints and plain arithmetic. add_bitcode_fixture(noalias -O2 -ffp-contract=off) @@ -35,5 +39,6 @@ target_compile_definitions(ExecutorTest PRIVATE ADD_BC_PATH="${CMAKE_CURRENT_BINARY_DIR}/add.bc" COMPUTE_BC_PATH="${CMAKE_CURRENT_BINARY_DIR}/compute.bc" FUNCTION_BC_PATH="${CMAKE_CURRENT_BINARY_DIR}/function.bc" + FPINTRINSICS_BC_PATH="${CMAKE_CURRENT_BINARY_DIR}/fpintrinsics.bc" NOALIAS_BC_PATH="${CMAKE_CURRENT_BINARY_DIR}/noalias.bc" ) diff --git a/klee/unittests/Core/ExecutorTest.cpp b/klee/unittests/Core/ExecutorTest.cpp index 8051084ea..c4fe16141 100644 --- a/klee/unittests/Core/ExecutorTest.cpp +++ b/klee/unittests/Core/ExecutorTest.cpp @@ -1560,6 +1560,192 @@ TEST(ExecutorTest, ICmpSLE) { EXPECT_EQ(evalICmp(ICmpInst::ICMP_SLE, 1, 0xFFFFFFFFu), 0u); // 1 <=s -1 → false } +// ============================================================ +// Intrinsics emitted by softfloat's hard float fast paths +// +// fpintrinsics.bc holds one function per intrinsic (see LLVM/fpintrinsics.c). +// llvm.is.fpclass and llvm.fmuladd are expanded by IntrinsicCleaner, llvm.fma +// and llvm.rint are evaluated by the Executor itself. +// ============================================================ + +// ── helpers ───────────────────────────────────────────────── + +/// Run a function from fpintrinsics.bc and return the raw bits of its result. +static uint64_t evalFPIntrinsic(const char *name, const std::vector> &args) { + llvm::LLVMContext ctx; + TestExecutor executor(ctx, FPINTRINSICS_BC_PATH); + llvm::Function *fn = executor.getLLVMModule()->getFunction(name); + assert(fn && "function not found in fpintrinsics.bc"); + ExecutionStatePtr s = executor.createState(); + auto r = executor.runFunction(*s, fn, args); + return dyn_cast(r)->getZExtValue(); +} + +/// A double operand given by its raw encoding. +static ref f64Bits(uint64_t bits) { + return klee::ConstantExpr::create(bits, Expr::Int64); +} + +/// A float operand given by its raw encoding. +static ref f32Bits(uint32_t bits) { + return klee::ConstantExpr::create(bits, Expr::Int32); +} + +/// Run one of the double class predicates on \p bits. +static uint64_t evalFPClass(const char *name, uint64_t bits) { + return evalFPIntrinsic(name, {f64Bits(bits)}); +} + +// Representative encodings, one per class and sign. +static const uint64_t kQNaN = 0x7FF8000000000000ULL; +static const uint64_t kSNaN = 0x7FF0000000000001ULL; +static const uint64_t kPosInf = 0x7FF0000000000000ULL; +static const uint64_t kNegInf = 0xFFF0000000000000ULL; +static const uint64_t kPosNormal = 0x3FF0000000000000ULL; // 1.0 +static const uint64_t kNegNormal = 0xC004000000000000ULL; // -2.5 +static const uint64_t kPosSubnormal = 0x0000000000000001ULL; // smallest denormal +static const uint64_t kNegSubnormal = 0x8000000000000001ULL; +static const uint64_t kPosZero = 0x0000000000000000ULL; +static const uint64_t kNegZero = 0x8000000000000000ULL; + +// ── llvm.is.fpclass ───────────────────────────────────────── +// +// Every predicate is checked against every class so that a wrong bit in the +// expansion shows up as a mismatch somewhere in the matrix rather than +// cancelling out. + +namespace { +struct FPClassCase { + const char *what; + uint64_t bits; + bool signaling; + bool nan; + bool inf; + bool finite; + bool normal; + bool subnormal; + bool zero; +}; +} // namespace + +TEST(ExecutorTest, IsFPClassPredicates) { + static const FPClassCase cases[] = { + // what bits sig nan inf fin norm subn zero + {"quiet nan", kQNaN, false, true, false, false, false, false, false}, + {"signaling nan", kSNaN, true, true, false, false, false, false, false}, + {"+inf", kPosInf, false, false, true, false, false, false, false}, + {"-inf", kNegInf, false, false, true, false, false, false, false}, + {"+normal", kPosNormal, false, false, false, true, true, false, false}, + {"-normal", kNegNormal, false, false, false, true, true, false, false}, + {"+subnormal", kPosSubnormal, false, false, false, true, false, true, false}, + {"-subnormal", kNegSubnormal, false, false, false, true, false, true, false}, + {"+zero", kPosZero, false, false, false, true, false, false, true}, + {"-zero", kNegZero, false, false, false, true, false, false, true}, + }; + + for (const auto &c : cases) { + SCOPED_TRACE(c.what); + EXPECT_EQ(evalFPClass("is_signaling_d", c.bits), c.signaling ? 1u : 0u); + EXPECT_EQ(evalFPClass("is_nan_d", c.bits), c.nan ? 1u : 0u); + EXPECT_EQ(evalFPClass("is_inf_d", c.bits), c.inf ? 1u : 0u); + EXPECT_EQ(evalFPClass("is_finite_d", c.bits), c.finite ? 1u : 0u); + EXPECT_EQ(evalFPClass("is_normal_d", c.bits), c.normal ? 1u : 0u); + EXPECT_EQ(evalFPClass("is_subnormal_d", c.bits), c.subnormal ? 1u : 0u); + EXPECT_EQ(evalFPClass("is_zero_d", c.bits), c.zero ? 1u : 0u); + } +} + +TEST(ExecutorTest, IsFPClassOnFloats) { + // The expansion derives the exponent and mantissa widths from the type, + // so the single precision variant needs its own check. + EXPECT_EQ(evalFPIntrinsic("is_normal_f", {f32Bits(0x3F800000u)}), 1u); // 1.0f + EXPECT_EQ(evalFPIntrinsic("is_normal_f", {f32Bits(0x00000001u)}), 0u); // smallest denormal + EXPECT_EQ(evalFPIntrinsic("is_normal_f", {f32Bits(0x00000000u)}), 0u); // +0.0f + EXPECT_EQ(evalFPIntrinsic("is_normal_f", {f32Bits(0x7F800000u)}), 0u); // +inf + EXPECT_EQ(evalFPIntrinsic("is_normal_f", {f32Bits(0x7FC00000u)}), 0u); // nan +} + +// ── llvm.fma ──────────────────────────────────────────────── + +TEST(ExecutorTest, FmaRoundsOnlyOnce) { + // (1 + 2^-52)^2 - (1 + 2^-51) is exactly 2^-104. Rounding the product + // first loses that term and yields zero, so the result tells the fused + // form apart from a plain multiply followed by an add. + EXPECT_EQ(evalFPIntrinsic("fma_d", {f64Bits(0x3FF0000000000001ULL), f64Bits(0x3FF0000000000001ULL), + f64Bits(0xBFF0000000000002ULL)}), + 0x3970000000000000ULL); // 2^-104 + + // (1 + 2^-23)^2 - (1 + 2^-22) = 2^-46 for the single precision variant. + EXPECT_EQ(evalFPIntrinsic("fma_f", {f32Bits(0x3F800001u), f32Bits(0x3F800001u), f32Bits(0xBF800002u)}), + 0x28800000u); // 2^-46 + + // 2.0 * 1.5 + 1.0 = 4.0, no rounding involved. + EXPECT_EQ(evalFPIntrinsic("fma_d", {f64Bits(0x4000000000000000ULL), f64Bits(0x3FF8000000000000ULL), + f64Bits(0x3FF0000000000000ULL)}), + 0x4010000000000000ULL); +} + +// ── llvm.rint ─────────────────────────────────────────────── + +TEST(ExecutorTest, RintRoundsToNearestEven) { + auto rint = [](uint64_t bits) { return evalFPIntrinsic("rint_d", {f64Bits(bits)}); }; + + EXPECT_EQ(rint(0x4004000000000000ULL), 0x4000000000000000ULL); // 2.5 → 2.0, ties to even + EXPECT_EQ(rint(0x400C000000000000ULL), 0x4010000000000000ULL); // 3.5 → 4.0, ties to even + EXPECT_EQ(rint(0xC004000000000000ULL), 0xC000000000000000ULL); // -2.5 → -2.0 + EXPECT_EQ(rint(0x3FF6666666666666ULL), 0x3FF0000000000000ULL); // 1.4 → 1.0 + EXPECT_EQ(rint(0xBFE0000000000000ULL), 0x8000000000000000ULL); // -0.5 → -0.0, keeps the sign +} + +// ── llvm.fmuladd ──────────────────────────────────────────── + +TEST(ExecutorTest, FMulAddIsUnfused) { + // 2.0 * 3.0 + 4.0 = 10.0 + EXPECT_EQ(evalFPIntrinsic("muladd_d", {f64Bits(0x4000000000000000ULL), f64Bits(0x4008000000000000ULL), + f64Bits(0x4010000000000000ULL)}), + 0x4024000000000000ULL); + + // Contraction is optional and the expansion does not fuse, so the input + // that yields 2^-104 through llvm.fma cancels to zero here. + EXPECT_EQ(evalFPIntrinsic("muladd_d", {f64Bits(0x3FF0000000000001ULL), f64Bits(0x3FF0000000000001ULL), + f64Bits(0xBFF0000000000002ULL)}), + 0x0ULL); +} + +// ── the fixture itself ────────────────────────────────────── + +TEST(ExecutorTest, FPIntrinsicsAreCleanedUpAsExpected) { + llvm::LLVMContext ctx; + + // Guard against a compiler that stops emitting the intrinsics: without + // them in the bitcode the tests above would pass without proving anything. + auto buf = llvm::MemoryBuffer::getFile(FPINTRINSICS_BC_PATH); + ASSERT_TRUE(!!buf); + auto raw = llvm::parseBitcodeFile(buf.get()->getMemBufferRef(), ctx); + ASSERT_TRUE(!!raw); + for (const char *name : {"llvm.is.fpclass.f64", "llvm.is.fpclass.f32", "llvm.fma.f64", "llvm.fma.f32", + "llvm.rint.f64", "llvm.fmuladd.f64"}) { + EXPECT_NE(raw.get()->getFunction(name), nullptr) << name << " is missing from the fixture"; + } + + // After the prepare passes the expanded ones are gone, while the two the + // Executor evaluates natively are still there. + llvm::LLVMContext execCtx; + TestExecutor executor(execCtx, FPINTRINSICS_BC_PATH); + auto *m = executor.getLLVMModule(); + + for (const char *name : {"llvm.is.fpclass.f64", "llvm.is.fpclass.f32", "llvm.fmuladd.f64"}) { + auto *fn = m->getFunction(name); + EXPECT_TRUE(fn == nullptr || fn->use_empty()) << name << " should have been expanded"; + } + + for (const char *name : {"llvm.fma.f64", "llvm.rint.f64"}) { + auto *fn = m->getFunction(name); + ASSERT_NE(fn, nullptr) << name << " should have been left for the Executor"; + EXPECT_FALSE(fn->use_empty()) << name << " should have been left for the Executor"; + } +} + // ============================================================ // llvm.experimental.noalias.scope.decl // diff --git a/klee/unittests/Core/LLVM/fpintrinsics.c b/klee/unittests/Core/LLVM/fpintrinsics.c new file mode 100644 index 000000000..7d98a9acb --- /dev/null +++ b/klee/unittests/Core/LLVM/fpintrinsics.c @@ -0,0 +1,77 @@ +/// +/// Copyright (C) 2026, Vitaly Chipounov +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy +/// of this software and associated documentation files (the "Software"), to deal +/// in the Software without restriction, including without limitation the rights +/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +/// copies of the Software, and to permit persons to whom the Software is +/// furnished to do so, subject to the following conditions: +/// +/// The above copyright notice and this permission notice shall be included in all +/// copies or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +/// SOFTWARE. +/// + +// Floating point intrinsics that clang emits for the hard float fast paths of +// softfloat: llvm.is.fpclass for the class predicates, llvm.fma for the fused +// multiply-add, llvm.rint for the rounding helpers and llvm.fmuladd for a +// contractable a * b + c. +// +// Must be compiled at -O0: at -O1 and above clang folds most of the class +// predicates into plain comparisons and the intrinsics disappear. + +int is_signaling_d(double x) { + return __builtin_issignaling(x); +} + +int is_nan_d(double x) { + return __builtin_isnan(x); +} + +int is_inf_d(double x) { + return __builtin_isinf(x); +} + +int is_finite_d(double x) { + return __builtin_isfinite(x); +} + +int is_normal_d(double x) { + return __builtin_isnormal(x); +} + +int is_subnormal_d(double x) { + return __builtin_issubnormal(x); +} + +int is_zero_d(double x) { + return __builtin_iszero(x); +} + +int is_normal_f(float x) { + return __builtin_isnormal(x); +} + +double fma_d(double a, double b, double c) { + return __builtin_fma(a, b, c); +} + +float fma_f(float a, float b, float c) { + return __builtin_fmaf(a, b, c); +} + +double rint_d(double x) { + return __builtin_rint(x); +} + +double muladd_d(double a, double b, double c) { + return a * b + c; +} From 90dfd8060077ccf71bd676889182e3d6f46b26e3 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Thu, 20 Aug 2026 16:57:14 +0000 Subject: [PATCH 14/52] libcpu: added porting plan Signed-off-by: Vitaly Chipounov --- libcpu/PORTING.md | 879 +++++++++++++++++++++++++++++++++++++++++++ libcpu/tlb-update.md | 361 ++++++++++++++++++ 2 files changed, 1240 insertions(+) create mode 100644 libcpu/PORTING.md create mode 100644 libcpu/tlb-update.md diff --git a/libcpu/PORTING.md b/libcpu/PORTING.md new file mode 100644 index 000000000..4e46cabd3 --- /dev/null +++ b/libcpu/PORTING.md @@ -0,0 +1,879 @@ +# Rebuilding libcpu on QEMU 11.1 + +libtcg tracks QEMU `v11.1.0`. libcpu is the last QEMU-1.0 island in the tree, and +the gap is too wide to merge: it gets rebuilt from upstream instead. This +document is the plan for doing that **concrete execution first**, keeping S2E's +KVM-shim architecture and leaving symbolic execution to land on top afterwards. + +Measured against `~/qemu` at `v11.1.0` and this tree at `9982579d`. + +| | | +|---|---| +| Source | qemu `v11.1.0` | +| Replaces | ~22k of libcpu's 29.4k lines | +| Imports | ~51k lines | +| Targets | `{i386,x86_64}-softmmu`, then the `-s2e` and `-s2e_sp` variants | +| Estimated effort | 12-17 weeks to concrete parity, 18-26 to full parity | + + +## 1. What libcpu is today + +Two properties of the current design shape the rest of this plan. + +First, `libs2e.so` is preloaded into a stock QEMU process and impersonates +*KVM*: libcpu is the kernel module, not the emulator. Device models, machine +setup, migration and the monitor all live in the real QEMU on the other side of +the ioctl boundary. So "no hardware emulation" is not a restriction this plan +imposes; it is already the shape of the system, and it removes most of what +makes upstream QEMU hard to extract. + +Second, libtcg has already been through this exercise. It is a de-QEMU-ified +fork at `v11.1.0` with a normalize-then-three-way-merge upgrade path +(`libtcg/scripts/upgrade/`), and it is *almost* free-standing: the only symbol it +needs from libcpu today is `helper_lookup_tb_ptr`. The boundary is already clean. + +### Fate of the current tree + +| File | Lines | Fate | Replaced by / note | +|---|---:|---|---| +| `target-i386/translate.c` | 7,992 | replace | `target/i386/tcg/{translate.c, decode-new.c.inc, emit.c.inc}` | +| `target-i386/op_helper.c` | 5,972 | replace | splits into 12 upstream helper files | +| `target-i386/ops_sse.h` | 1,891 | replace | `target/i386/ops_sse.h` (2,672) | +| `target-i386/helper.c` | 1,119 | replace | `helper.c` + `cpu-dump.c` + `tcg/excp_helper.c` | +| `target-i386/cpu.h` | 480 | replace | merged into the new `include/cpu/i386/cpu.h` | +| `softmmu_{template,header,exec}.h` | 1,162 | replace | `cputlb.c` + `ldst_common.c.inc` | +| `cpu-exec.c`, `exec-tb.c`, `exec-tlb.c`, `exec-phystb.c`, `exec-bp.c`, `translate-all.c`, `exec.c` | 2,766 | replace | `accel/tcg/{cpu-exec, tb-maint, cputlb, translate-all, translator, watchpoint}.c` | +| `target-i386/cpuid.c` | 1,029 | replace | the CPUID/feature-model subset of `target/i386/cpu.c` (~8.0k lines) | +| `include/cpu/i386/cpuid.h` | 176 | replace | `cpuid_t` and its 2011-era feature bits die; `FeatureWordArray` replaces them | +| `exec-ram.c`, `exec-phys.c`, `exec-memdbg.c`, `memory.c`, `ioport.c` | 1,241 | adapt | S2E's `MemoryDesc` layer, the replacement for `MemoryRegion`; count includes the matching headers | +| `cpus.c`, `timer.c`, `disas.c` | 555 | keep | reduced QEMU files plus the S2E-original capstone disassembler | +| `precise-pc.c` | 221 | reconcile | upstream `translate-all.c` restore machinery + S2E's `tb_get_instruction_size()`; collides with the phase 2 import (see section 8) | +| `include/cpu/kvm.h` | 1,335 | keep | the ioctl ABI; untouched by this work | + +Roughly 22k lines go away and ~51k arrive: 8.3k from `accel/tcg/`, 31.5k from +`target/i386/` plus ~8.0k of CPUID machinery from `target/i386/cpu.c`, and ~3.2k +of utilities. The line count grows because upstream's i386 frontend (the new +table-driven decoder, full AVX/AVX2 emit paths, XSAVE, MPX) and its feature model +are much larger than the 2011 ones. That growth is most of the point of doing +this. + + +## 2. The method: reuse libtcg's, don't invent one + +"Start from scratch" should mean *start from upstream files*, not hand-write new +ones. Take the same route libtcg took, so that the second upgrade (11.1 to +12.x) is a three-way merge and not another rebuild: + +1. Run each upstream file through `clang-format` with the S2E style *before* it + enters the tree. +2. Rewrite its includes to libcpu/libtcg paths and add `extern "C"` guards. +3. Record the pairing in `libcpu/scripts/upgrade/mapping.tsv`, with `BASELINE` = + `v11.1.0`. +4. Confirm normalization by merging the tag onto itself: + `./merge.sh v11.1.0 v11.1.0` must report zero conflicts. + +`libtcg/scripts/upgrade/{normalize.sh,merge.sh}` already do steps 1 and 4; they +need a tree-root parameter so they can serve both components. Every S2E +deviation introduced from here on gets a comment saying *why*, because the merge +tool cannot preserve intent it cannot see. + +libcpu's current state is exactly what happens without this discipline: fourteen +years of drift that can no longer be merged. The tooling is cheap, a day or two +in phase 0, and it is the only thing that stops the next upgrade from being +another rebuild. + + +## 3. Five decisions that constrain the rest + +Everything else follows from these. They should be settled before any code is +imported. + +### 3.1 Hand-write a slim `CPUState`; do not import QOM + +Upstream splits the CPU into `ArchCPU { CPUState parent_obj; CPUX86State env; }`, +where `CPUState` derives from `DeviceState` -> `Object`. Importing that chain +means `qom/object.c`, `hw/core/qdev*.c`, properties, resettable and hotplug, a +large device-oriented dependency for a component with no devices. + +That chain is not needed. Measured over the accel/tcg files we import, only +about twenty `CPUState` fields are ever touched: `neg` (59 uses), `cc` (26, all +of them `cpu->cc->tcg_ops->...`), `exception_index`, `cflags_next_tb`, +`tb_jmp_cache`, +`jmp_env`, `interrupt_request`, `exit_request`, `halted`, `breakpoints`, +`watchpoints`, and a handful more. So: define a plain struct with exactly those +fields, keep upstream's *layout contract* (`CPUNegativeOffsetState neg` last in +`CPUState`, `CPUX86State` immediately after it, so `cpu_env()` / `env_cpu()` and +the negative TLB offsets work unmodified), and replace `cpu->cc` with a direct +`const TCGCPUOps *`. `TCGCPUOps` itself is a plain function-pointer struct and +imports as-is. + +- Cost: ~200 lines of hand-written header, in `libcpu/include/cpu/state.h`. +- Buys: accel/tcg and target/i386/tcg compile essentially unmodified. +- Risk: **low**. Fields are added on demand; a missing one is a compile error, + not a silent bug. + +### 3.2 Keep `MemoryDesc`; graft it into `CPUTLBEntryFull` + +S2E already has the right abstraction. `MemoryDesc` wraps a +`kvm_userspace_memory_region` plus a `{read, write}` op pair; `mem_desc_find(gpa)` +returns NULL for MMIO. That is exactly the information `MemoryRegionSection` +carries for our purposes, without FlatView, AddressSpace, RCU flatview swaps or +the `MemoryRegion` type hierarchy. + +The coupling in `cputlb.c` is concentrated in about eight places, all of which we +rewrite: + +- `tlb_set_page_full()`: drop `address_space_translate_for_iotlb`, + `memory_region_is_ram/romd`, `memory_region_get_ram_ptr/addr`. +- `io_prepare()` / `io_failed()`. +- `int_ld_mmio_beN` / `int_st_mmio_leN`: dispatch through `MemoryDescOps` + instead of `memory_region_dispatch_read/write`. + +Replace `CPUTLBEntryFull`'s `MemoryRegionSection *section` pointer and +`xlat_offset` with `const MemoryDesc *` plus an offset. 11.1's `io_prepare()` +already dereferences `full->section` directly, which keeps the graft local. +Dirty-page tracking keeps the existing `exec-ram.h` +byte-per-page mask rather than upstream's bitmap trio. + +- Cost: ~300 lines of rewritten `cputlb.c` plus a compatibility header. +- Buys: no MemoryRegion, no AddressSpace, no BQL around memory dispatch. +- Risk: **medium**. These functions are re-touched by upstream regularly, so they + will conflict at every future merge. Isolate them behind a thin `s2e_mem_*` + layer so the conflicts stay small. + +### 3.3 Adopt upstream's TLB, and take it out of the execution state + +libtcg's x86_64 backend is already the v11.1 one and already knows about the S2E +TLB: it emits the `se_addend` load on the hit path (under `CONFIG_SYMBEX_MP` +only; the non-MP symbex build uses the plain `addend`), and it locates the TLB +through `TCGContext::tlb_fast_offset`. That is the *only* live geometry field: +`tlbe_size`, `tlbe_offset_*`, `cpu_tlb_size`, `cpu_tlb_entry_bits` and +`env_ptr` are set by `translate-all.c` and read by nothing. The backend +hard-codes `offsetof(CPUTLBEntry, ...)` and `CPU_TLB_ENTRY_BITS`, so a +`CPUTLBEntry` layout change still means editing the backend in lock-step. What +makes this decision cheap is narrower but sufficient: the generated code reads +`mask` and `table` out of `CPUTLBDescFast` at run time, so a dynamically sized +table needs no codegen change. Point `tlb_fast_offset` at +`offsetof(ArchCPU, neg.tlb.f) - offsetof(ArchCPU, env)`, the value the current +`translate-all.c` already documents in a comment next to the S2E override. + +Take upstream's dynamic, heap-allocated TLB as-is, and **stop storing it in the +execution state**, flushing it on every state switch instead. It is a cache of a +mapping derivable from the guest page tables and the KLEE address space, and a +state switch already discards the whole translation block cache and round-trips +the entire QEMU device model, both of which cost far more than refilling it. +Disable the victim TLB initially, and move S2E's flags into +`CPUTLBEntryFull.slow_flags[]`. Section 9 is the full analysis; the summary: + +- Cost: mostly deletion. `exec-tlb.c` goes away, and so do ~216 KB of per-state + cache. The main-TLB `CPU_TLB_SIZE` sites in libs2ecore become run-time mask + reads (the `se_ram_tlb` sites keep a pinned size; see 9.2). +- Buys: smaller per-state memory, faster state switches, and `objectState` gets + a better home in `CPUTLBEntryFull` than in the fast entry. `cputlb.c` still + needs one contained deviation (a pinned TLB size, two functions) because + the TLB stays KLEE-visible and KLEE bindings cannot be re-created per state. + See `tlb-update.md` section 5. +- Risk: **medium**. `CPUTLBEntry` must stay a power-of-two size; the + `TCGContext` geometry fields must track the layout; and codegen and C code must + agree on whether the `CPUTLBDescFast` array index is inverted. + +### 3.4 Move to upstream's helper ABI and retire the global `env` + +Today's helpers take no `env` (`DEF_HELPER_0(cpuid, void)`) and reach a +file-scope `CPUArchState *env`, with `EAX`-style macros expanding to +`RR_cpu()` (`EIP` and `DF` deliberately bypass it; they live outside the +symbolic prefix). Upstream passes `env` explicitly +(`DEF_HELPER_1(cpuid, void, env)`) and writes `env->regs[R_EAX]` directly. +Trying to keep the old convention would mean rewriting every imported helper. + +Take upstream's convention. Two consequences to plan for now, not later: + +- The per-target helper list currently lives in libtcg + (`libtcg/include/tcg/helper.h`, hard-wired via `HELPER_H` in + `exec/helper-gen.h`). That is a layering wart: the file is target-specific and + belongs in libcpu. Make `HELPER_H` resolve to a libcpu path as part of phase 3, + not as cleanup afterwards. +- The `RR_cpu` / `WR_cpu` discipline that makes helpers correct inside KLEE has + to be reintroduced mechanically over the new helper sources in phase 6. See + section 7. + +Cost: the helper list moves; the dead `tcg_ctx->env_ptr` and geometry fields +(see 3.3) get deleted; the live handle in 11.1 is `tcg_env`. Buys: +helper files import unmodified, and it fixes the current ABI smell where libcpu +installs `(env, addr, mmu_idx, retaddr)` helpers into slots libtcg marshals as +`(env, addr, oi, retaddr)`. Risk: **high, deferred**. This is the decision most +entangled with symbolic execution. It is still the right one; section 7 lists the +invariants that keep it safe. + + +### 3.5 Take the CPUID and feature model from 11.1 too + +The current `cpuid.c` is a QEMU-1.0 artifact and it is the *definition* of the +CPU S2E exposes, not just a consumer of it. The data flow is: +`cpu_x86_register(&m_cpuid, model, is64)` builds a `cpuid_t` from libcpu's own +model table; `KVM_GET_SUPPORTED_CPUID` answers the QEMU process out of it via +`cpu_x86_cpuid()`; QEMU filters and hands the result back through +`KVM_SET_CPUID2`. Whatever `cpuid_t` cannot express, the guest never sees. + +`cpuid_t` has seven feature words, all of them pre-2011. Upstream has 48 +`FeatureWord`s, and 11.1's decoder gates on them: `FEAT_7_0_EBX` for +AVX2/BMI1/BMI2, `FEAT_XSAVE`, `FEAT_7_1_EAX`, and so on. Keeping the old +`cpuid_t` would mean importing the new frontend and then being unable to +advertise most of what it can now emulate. So `cpuid.c` and +`include/cpu/i386/cpuid.h` are replaced, not kept. + +What to take from `target/i386/cpu.c`: + +| Piece | Lines | Why | +|---|---:|---| +| `TCG_*_FEATURES` masks + `feature_word_info[]` | 2,668 | The feature word model, and `.tcg_features`, the ceiling on what TCG can actually emulate, which is exactly the right bound for what S2E advertises. The count includes the cache-descriptor tables between the two, which `cpu_x86_cpuid()` needs anyway. | +| `builtin_x86_defs[]` | 3,813 | The named CPU models (`qemu64`, `Skylake-Client`, ...) that `-cpu` selects. | +| `cpu_x86_cpuid()` | 735 | The leaf implementation itself. | +| `x86_cpu_expand_features()`, `x86_cpu_filter_features()` | 367 | Applies the tcg mask and expands dependent features. | +| `x86_cpu_get_supported_feature_word()` | 244 | Reduce to the TCG branch; drop kvm/hvf/whpx/nvmm/mshv. | +| `x86_cpu_load_model()` | 155 | Model name to feature words. | +| `x86_update_hflags()` | 42 | Needed regardless. | +| | **~8,000** | of `cpu.c`'s 11,034 | + +The remaining ~3k lines are QOM: `x86_cpu_realizefn`, class init, property +tables, hyperv plumbing. Those we replace with a direct call path, consistent +with decision 3.1. + +Note that `cpu_x86_cpuid()` reaches `X86CPU` fields through `env_archcpu(env)`: +`phys_bits`, `guest_phys_bits`, `enable_l3_cache`, `legacy_cache`, +`cache_info_cpuid4` and friends. Those become plain fields on the slim `ArchCPU` +from decision 3.1, set once at init instead of through QOM properties. + +## 4. Dependencies, and where they should live + +**libcpu uses exactly one header from libutils today: `qqueue.h`** (QTAILQ, for +breakpoint and watchpoint lists). Everything else in libutils (QAPI, +QObject/QDict/QJSON, the visitors, coroutines, fsigc++) is consumed by libs2e +and libs2ecore, not by the CPU emulator. libutils is therefore *not* on the +critical path for this port; the question is only where the new dependencies go. + +### 4.1 The placement rule: platform-independent code belongs in libutils + +libtcg is configured per target: the build produces six trees per build type +(`{i386,x86_64}` x `{plain, s2e, s2e_sp}`), and every one of them rebuilds +libtcg from scratch. libutils is configured once per build type. So anything that +does not depend on `TARGET_LONG_BITS`, `TARGET_PAGE_BITS`, `CONFIG_SYMBEX` or the +CPU state belongs in libutils, and putting it in libtcg costs six compilations of +the same object. + +libtcg already declares `find_package(LIBUTILS REQUIRED)`, so the dependency edge +exists and nothing new has to be wired up. + +**This applies to what is already there, not only to the new imports.** Of +libtcg's 7,683-line `utils/` subset, ~7,140 lines are platform-independent +today. Two files reference a target or config macro: `utils/log.c`, in three +`#ifdef TARGET_I386` / `#ifdef CONFIG_SYMBEX` blocks that populate the +`CPU_LOG_*` mask table (`log.h` itself is clean), and `utils/bswap.h`, which +tests `TARGET_WORDS_BIGENDIAN` and `TARGET_LONG_SIZE` in live code, and is +mapped to upstream `include/qemu/bswap.h`, so it cannot be edited to drop the +dependency without creating a merge deviation. Move the rest to libutils; +either leave log and bswap behind, or make the log-mask table registrable and +split bswap's target-dependent tail into a libcpu header. + +Two consequences to plan for: + +- The include prefix changes from `` to whatever libutils adopts + (proposal: ``, matching libutils' existing flat `` / + `` shape). 54 files tree-wide include `tcg/utils/` (33 in + libtcg, 18 in libcpu, 3 in libs2e), so the rewrite is mechanical but wide; it + should land as its own commit, ahead of any libcpu work, and be re-verified + with `merge.sh v11.1.0 v11.1.0` reporting zero conflicts afterwards. +- The upgrade tooling follows the files. libutils becomes a home for vendored + QEMU code and needs its own `scripts/upgrade/{BASELINE,mapping.tsv}`, or, if + the scripts are parameterized by component root in phase 0, a second mapping + driven by the same driver. + +### 4.2 What 11.1 needs that we do not have + +Resolving the include closure of the accel/tcg import set against libtcg's +vendored utils gives a short list. Placement follows the rule above. + +| Needed by 11.1 | Lines | Status | Recommendation | +|---|---:|---|---| +| `qemu/qht.{h,c}` | 1,254 | missing | Import into **libutils**. The TB hash table; `tb-maint.c` and `cpu-exec.c` use it directly. | +| `qemu/rcu.{h,c}` | 693 | missing | Import into **libutils**. Required by qht. Could be stubbed for the single-vCPU case, but importing costs less than reasoning about the stub. | +| `qemu/thread{,-posix}.h`, `util/qemu-thread-posix.c` | 934 | missing | Import a reduced subset (mutex, cond, thread) into **libutils**. libtcg's `utils/mutex.h` is a partial stand-in that should be folded into it. | +| `qemu/xxhash.h`, `qemu/seqlock.h` | ~330 | missing | Import into **libutils**; header-only, no further deps. | +| `qemu/qdist.{h,c}` | ~440 | missing | **Skip.** Only feeds `qht_statistics`; compile it out. | +| `qemu/error-report.h`, `qemu/qemu-print.h` | ~120 | missing | Thin S2E versions in **libutils**, routing to the log. | +| `qemu/main-loop.h` (BQL) | n/a | missing | **Stub** in libcpu. `bql_lock`/`bql_unlock` as no-ops; one vCPU, no MTTCG. | +| `exec/icount.h`, `exec/replay-core.h`, `system/tcg.h`, `qemu/plugin.h`, `qemu/target-info.h` | n/a | missing | **Stub** in libcpu; these are configuration-dependent. icount off, replay off, `tcg_enabled()` is true, plugins compiled out. | +| `qemu/queue.h` | n/a | have | libutils `qqueue.h`, already in the right place. | +| glib allocation shims (`g_new`, `g_try_new`, `g_free`, `GArray`) | n/a | verify | Used by `qht.c`, `cputlb.c`, `tb-maint.c`; confirm libtcg's existing glib-compat covers the import closure, extend in **libutils** if not. | +| osdep, cutils, bitops, bitmap, int128, host-utils, atomic, atomic128, interval-tree, qtree, memalign, cacheinfo, units, cpuid | ~7,140 | have, misplaced | In `libtcg/include/tcg/utils/`; move to **libutils** per 4.1. | +| bswap | 308 | have, target-dependent | Tests `TARGET_WORDS_BIGENDIAN` / `TARGET_LONG_SIZE`; stays behind with log unless its target tail is split out (see 4.1). | +| log | 238 | have, target-dependent | Stays in libtcg unless the `CPU_LOG_*` mask table is made registrable. | + +Net: about 3.2k lines of newly imported utility code, plus a ~7.1k-line +relocation that removes five redundant compilations of each object per build +type. The dependency work is not what makes this project long. + +## 5. What is deliberately not ported + +| Upstream | Why not | +|---|---| +| `hw/**`, `system/memory.c`, `system/physmem.c` | Devices and machine memory live in the host QEMU process, behind the KVM ioctl boundary. `MemoryDesc` replaces the parts we need. | +| `qom/**`, `hw/core/qdev*` | Decision 3.1. No devices means no object model. | +| `target/i386/cpu.c`, the QOM half (~3k lines) | `x86_cpu_realizefn`, class init, property tables, hyperv and accel glue. The other ~8.0k lines (the feature model and CPUID) *are* ported; see section 3.5. | +| `target/i386/machine.c`, `migration/**` | Snapshots are handled by vanilla QEMU, not by libcpu. | +| `accel/tcg/tcg-accel-ops*.c`, `icount-common.c` | MTTCG, round-robin scheduling and icount. One vCPU, driven by `KVM_RUN`; `cpus.c` and `timer.c` stay. | +| `accel/tcg/plugin-gen.c`, `plugins/**` | TCG's plugin API duplicates what S2E's core-plugin hooks already do. Compile out; revisit only if it turns out to be a cheaper hook point than patching `translate.c`. | +| `gdbstub/**`, `monitor/**`, `disas/**` | Debugger and monitor belong to host QEMU. Disassembly stays on capstone via `disas.c`. | +| `target/i386/{kvm,hvf,whpx,nvmm,mshv,sev}/**` | Other accelerators. TCG only. | +| `target/i386/tcg/user/**`, `accel/tcg/user-exec*.c` | linux-user mode. Softmmu only. | + + +## 6. The plan, phase by phase + +Phases 0-4 deliver a working concrete emulator. Phases 5-6 put S2E back on top. +Each phase ends at something you can build and check, so the tree is never left +in a state nobody can reason about. Estimates assume one person familiar with the +codebase. + +### Phase 0: Tooling and scaffolding (~1 week) + +- Generalize `libtcg/scripts/upgrade/{normalize.sh,merge.sh}` to take a component + root, so libcpu can drive them; or fork them into `libcpu/scripts/upgrade/` if + that turns out cleaner. +- Create `libcpu/scripts/upgrade/{BASELINE,mapping.tsv,README.md}`. `BASELINE` is + `v11.1.0` from the start; `mapping.tsv` grows as files land. +- Settle the target directory layout. Proposal, mirroring libtcg: `src/accel/` + for accel/tcg files, `src/target-i386/` for the frontend and helpers, + `src/s2e/` for S2E originals (exec-ram, exec-phys, memory, ioport, cpus, timer, + disas, precise-pc), `include/cpu/` unchanged as the public surface. +- Create a scratch branch that builds the *current* tree with `CONFIG_SYMBEX` + off, so the concrete-only configuration is known-good before anything moves. + +**Exit:** `./merge.sh v11.1.0 v11.1.0` runs clean over an empty mapping; +`normalize.sh` can emit any 11.1 file into its intended libcpu path; +`x86_64-softmmu` builds and boots on the old code. + +### Phase 1: Substrate, utilities, CPUState, memory shim (2-3 weeks) + +- **Relocate libtcg's platform-independent utils to libutils** (section 4.1), as + a standalone commit before anything else in this phase: 7,445 of 7,683 lines, + 33 include-site rewrites, `utils/log.{h,c}` left behind. Give libutils its own + `scripts/upgrade/{BASELINE,mapping.tsv}` and move the corresponding rows out of + libtcg's. Verify with `merge.sh v11.1.0 v11.1.0` on both components. +- Import qht, rcu, thread, xxhash, seqlock into **libutils** per section 4.2; add + them to libutils' new `mapping.tsv`. Fold libtcg's `utils/mutex.h` into the + real thread header. +- Write `libcpu/include/cpu/state.h`: slim `CPUState`, `CPUNegativeOffsetState`, + `ArchCPU`, `cpu_env()` / `env_cpu()`, and the `TCGCPUOps` pointer that replaces + `cpu->cc`. +- Write the memory shim: upstream's `iotlb_to_section`, + `memory_region_dispatch_*`, `qemu_ram_addr_from_host*` and the dirty-tracking + predicates, expressed over `MemoryDesc` and `exec-ram.h`. +- Write the stub headers: BQL, icount, replay, plugins, `tcg_enabled()`, + target-info. + +**Exit:** the substrate compiles standalone against libtcg. A small unit test +drives qht insert/lookup/remove/resize. + +### Phase 2: accel/tcg core (2-3 weeks) + +- Normalize and import: `cpu-exec.c`, `cpu-exec-common.c`, `cputlb.c`, + `tb-maint.c`, `translate-all.c`, `translator.c`, `watchpoint.c`, plus + `tb-hash.h`, `tb-context.h`, `tb-internal.h`, `tb-jmp-cache.h`, + `internal-common.h`, `backend-ldst.h`, `tlb-bounds.h`, `vcpu-state.h`, + `ldst_common.c.inc`, `ldst_atomicity.c.inc`, and the atomic helpers + `atomic_common.c.inc` / `atomic_template.h` that `cputlb.c` pulls in + (`tcg-runtime*` already lives in libtcg). +- Rewrite the eight `MemoryRegion` touch points in `cputlb.c` against the phase 1 + shim. +- Apply the TLB decisions from section 9: disable the victim TLB, move S2E's flag + bits into `slow_flags[]`, and move `objectState` into `CPUTLBEntryFull`. If + `tlb-update.md` has landed first, the ownership half of this is already done + and `cputlb.c` imports without S2E-side surprises. Bring + `libtcg/include/tcg/tlb.h` forward to the 11.1 flag scheme at the same time. It + is an S2E-original that was never upgraded and still describes the pre-11.1 + bit allocation. +- Delete `cpu-exec.c`, `exec.c`, `exec-tb.c`, `exec-tlb.c`, `exec-phystb.c`, + `exec-bp.c`, `translate-all.c`, `softmmu_*.h`, `cpu-all.h`, `cpu-defs.h`, + `exec-all.h`. +- Reconcile `libtcg/include/tcg/tb.h` with upstream's `TranslationBlock`: the S2E + copy has drifted (it still carries `phys_hash_next` and `page_next` from the + pre-qht era, alongside 11.1's `jmp_*` fields). +- Reconcile `precise-pc.c` with the imported `translate-all.c`: upstream owns + `encode_search()` and `cpu_restore_state()` there, which `precise-pc.c` + carries as its own copies, and `precise-pc.c` calls `restore_state_to_opc()`, + defined in the old `translate.c` that phase 3 replaces and reached in + 11.1 through `TCGCPUOps.restore_state_to_opc`. Keep only the S2E extensions + (`tb_get_instruction_size()`, `se_restore_state_to_opc()`) and re-home them + explicitly. + +**Exit:** `libcpu.a` builds and links against libtcg with only `target-i386` +symbols undefined. + +### Phase 3: The i386 frontend, helpers and CPUID model (5-7 weeks, the bulk) + +- Write the new `include/cpu/i386/cpu.h` from upstream's `cpu.h`: strip QOM and + the model/feature machinery, merge the fields S2E's `X86CPU` equivalents need + into `ArchCPU`, and **order the fields so the symbolic-capable prefix still + ends at `eip`** (see section 7). +- Import `helper.h`, `ops_sse.h`, `svm.h`, `cpu-param.h`, `helper.c`, + `cpu-dump.c`; and from `tcg/`: `translate.c`, `decode-new.{c.inc,h}`, + `emit.c.inc`, `cc_helper.c`, `cc_helper_template.h.inc`, `excp_helper.c`, + `fpu_helper.c`, `int_helper.c`, `mem_helper.c`, `misc_helper.c`, + `mpx_helper.c`, `seg_helper.c`, `seg_helper.h`, `bpt_helper.c`, + `access.{c,h}`, `tcg-cpu.{c,h}`, `helper-tcg.h`, and the `tcg/system/` variants + (`smm_helper.c`, `svm_helper.c`, and the system-mode halves of + excp/misc/seg/bpt/fpu). +- Move `HELPER_H` from `libtcg/include/tcg/helper.h` to a libcpu path; drop + libtcg's `tcg/ops_sse_header.h` in favor of upstream's `.h.inc`. +- Import the CPUID and feature model per decision 3.5: the `TCG_*_FEATURES` + masks, `feature_word_info[]`, `builtin_x86_defs[]`, `cpu_x86_cpuid()`, + `x86_cpu_expand_features()`, `x86_cpu_filter_features()`, + `x86_cpu_get_supported_feature_word()` (TCG branch only), + `x86_cpu_load_model()` and `x86_update_hflags()`. Delete `cpuid.c` and + `include/cpu/i386/cpuid.h`. Re-add `CPUID_EXT_S2E` on top (see section 8). +- Rename `env->mflags` to `env->eflags`. Upstream's `eflags` has *exactly* S2E's + `mflags` semantics ("CC flags and DF are set to zero because they are stored + elsewhere"), so this is a rename, not a redesign, and it removes a + long-standing divergence. + +**Exit:** `x86_64-softmmu` and `i386-softmmu` build clean with `CONFIG_SYMBEX` +off, in both release and debug trees. + +### Phase 4: Wire to the KVM shim and boot (2-3 weeks) + +- Update libs2e for fields that moved from `CPUX86State` into `CPUState`: + `jmp_env` (~30 sites), `interrupt_request`, `exception_index`, `halted`, + `current_tb`, `tlb_table`. Mostly mechanical; `s2e-kvm-vcpu.cpp` and + `s2e-kvm-state.cpp` carry most of it. +- **Extend the per-state snapshot to the non-cache part of `CPUState`.** Today + `interrupt_request`, `exception_index`, `halted` and `jmp_env` are saved + implicitly because they sit inside the snapshotted `CPUX86State` window; once + they move into the slim `CPUState` they land in the `[&g_cpu, &g_cpu.env)` + region that `tlb-update.md` registers as shared-concrete and *never + snapshots*. They are per-state execution state, not caches, so + `saveConcreteState()` / `restoreConcreteState()` (or a separate registered + object) must cover them explicitly, or state switches corrupt silently. +- Map libcpu's exit reasons onto `kvm_run` as before; `cpu_x86_exec()` keeps its + shape, `cpu_exec()` gains upstream's `cpu_exec_setjmp` structure. +- Re-derive `cpu_get_pic_interrupt()`, `do_cpu_init()`, `cpu_state_reset()` + against the new state layout, including `cpu_init_fp_statuses()`, which must + run after every reset memset. +- Move the TLB, `se_ram_tlb`, `se_tlb_current` and `tb_jmp_cache` out of the + snapshotted concrete region, and flush them in `doStateSwitch()` after the new + state is activated + and `g_se_disable_tlb_flush` is cleared. Collapse the per-state + `S2EExecutionStateTlb` into executor-owned data. (Phase 6 work in spirit, but + the struct layout change belongs here.) +- Rewire libs2e's CPUID plumbing to the new feature model: `S2EKVM::init()`'s + `x86_cpudef_setup()` + `cpu_x86_register(&m_cpuid, model, is64)` pair becomes + `x86_cpu_load_model()` + + `x86_cpu_expand_features()`; `getSupportedCPUID()`'s hardcoded + `s_cpuid_entries[]` leaf list has to be regenerated to cover leaf 7 subleaves, + leaf 0xD subleaves, 0x24 and the extended leaves; the per-target + `nent == 15` (x86-64) / `nent == 21` (i386) build-mismatch guards in + `setCPUID2()` have to be re-derived from the new counts; and `setCPUID2()` + should apply the guest-requested mask across all feature words instead of only + MMX/SSE/SSE2 in leaf 1. +- Rebuild the concrete `testsuite/` baseline. + +**Exit:** a Linux guest image boots to a shell under `x86_64-softmmu` and +`i386-softmmu`, and the concrete testsuite passes. Phases 0-4 exist to reach +this milestone. + +### Phase 5: Re-implant the S2E instrumentation (2-3 weeks) + +The 40-odd `g_sqi.events.*` call sites in the old `translate.c` have to be +re-placed in upstream's decoder, which is structured completely differently: a +table-driven `decode-new.c.inc` feeding `emit.c.inc`, under `translator_loop()`. +Instruction-start/end hooks land naturally on `translator_loop`'s per-insn +callbacks; block start/end and complete on `tb_start` / `tb_stop`. The ones that +need real thought are the instruction-shape hooks (jump start, indirect CTI +start, LEA-RIP-relative, and the special-instruction hook for +`RDTSC`/`SYSENTER`/`SYSCALL`/`PUSHIM`), because they were written against the old +hand-rolled decoder's control flow. Budget for reading the new decoder properly +rather than pattern-matching the old hooks onto it. + +**Exit:** core-plugin events fire with the same semantics as before, verified +against a recorded trace from the pre-port build. + +### Phase 6: Symbolic execution back on top (4-6 weeks) + +- Reintroduce the `RR_cpu` / `WR_cpu` discipline across the imported helper + sources mechanically, with a checker that fails the build on a direct + `env->field` access inside a helper translation unit. +- Re-add the symbolic softmmu: the `TLB_SYMB` / `TLB_NOT_OURS` / `TLB_MEM_TRACE` + paths, `objectState` plumbing, and `g_sqi.mem.*` hooks, now inside upstream's + `do_ld_mmu` / `do_st_mmu` rather than `softmmu_template.h`. +- Rebuild the bitcode target. `op_helper.c` was one translation unit compiled to + `op_helper.bc`; upstream's helpers are twelve files, so either `llvm-link` them + all or add a unity `.c` that includes them. Note the ld/st helper names + changed upstream (the 32-bit load is `helper_ldul_mmu`); the KLEE-side + handlers and handler tables must follow. +- Check `tcg-llvm.cpp`'s opcode switch against 11.1's `tcg-opc.h`, and re-verify + the `se_addend` / `fast_concrete_invocation` invariants end to end. Keep in + mind `se_addend` is a native-execution concern only: the bitcode softmmu path + is compiled with `SYMBEX_LLVM_LIB` and reads the plain `addend`, and the + backend emits the `se_addend` load only under `CONFIG_SYMBEX_MP`. + +**Exit:** `{i386,x86_64}-s2e-softmmu` and `-s2e_sp-softmmu` build and pass the +full testsuite, including `basic4-xmm`. + + +## 7. Symbex constraints to honor during the concrete phases + +Symbolic execution comes last, but four of its invariants constrain decisions +taken in phases 1-3. Getting them wrong means redoing that work. + +**The CPU state has a symbolic prefix.** Everything before +`offsetof(CPUX86State, eip)` may hold symbolic data; everything after it may not. +`__RR_env_dyn` asserts on exactly that boundary. Upstream's field order is +different (`regs`, `eip`, `eflags`, `cc_*`, segments, ..., with +`ZMMReg xmm_regs[]` far down). When writing the new `CPUX86State` in phase 3, +keep the S2E order (GPRs, `cc_op`/`cc_src`/`cc_dst`/`cc_tmp`, FPU, MMX/XMM, +*then* `eip` and everything concrete), and leave a comment saying why. Rewriting +this later means re-auditing every helper. Note that 11.1 sizes the register +files for APX (`regs[CPU_NB_EREGS]`, 32 GPRs, and `xmm_regs[CPU_NB_EREGS]`), +so the symbolic prefix is larger than the old layout suggests; size the KLEE +objects from `offsetof`, never from carried-over constants. + +**Fields must be addressable by `(offset, size)`.** `RR_cpu` / `WR_cpu` are built +on `offsetof` and `sizeof`, so no bitfields anywhere in the symbolic prefix. This +is already why `float_status.float_rounding_mode` is a plain field in libtcg +rather than upstream's bitfield; the same rule applies to anything new that lands +in `CPUX86State`. + +**Helper code must be compilable to bitcode as one unit.** Whatever file +organization phase 3 lands on, the helper set has to reach a single +`op_helper.bc`. Keep the helper translation units free of anything that will not +survive `clang -emit-llvm` and `llvm-link` against `softfloat.bc`: no inline asm, +no host intrinsics in a helper path, nothing pulled in from the KVM shim. + +**The TLB entry is shared with the code generator.** libtcg's x86_64 backend +emits a load from `offsetof(CPUTLBEntry, se_addend)` on the TLB hit path, sized by +`CPU_TLB_ENTRY_BITS`. Any change to `CPUTLBEntry` in phase 2 has to move in +lock-step with `libtcg/include/tcg/tlb.h` and the `TCGContext` geometry fields, +and the `QEMU_BUILD_BUG_ON` on entry size has to keep holding. + + +## 8. Failure modes + +**Never replace `RR_cpu` / `WR_cpu` with direct struct access to silence a +compiler error.** Under `CONFIG_SYMBEX` those route through +`g_sqi.regs.read_concrete()` when `fast_concrete_invocation` is false, that is, +when the helper is running as bitcode inside KLEE. Direct access reads the native +copy of the CPU state instead of KLEE's, silently, on exactly the paths that +matter. If upstream makes a field unaddressable, change the field. + +**Softfloat initialization builds clean and aborts later.** Softfloat asserts at +run time when a NaN-propagation rule or default-NaN pattern was never set, and +`cpu_state_reset()` memsets the CPU state. Anything of that kind must be +reapplied after every reset; `cpu_init_fp_statuses()` in `helper.c` exists for +this reason. When phase 3 imports upstream's initialization, grep for setters the +new reset path does not call. + +**Two components, one struct.** `libtcg/include/tcg/tb.h` defines +`TranslationBlock` but `libcpu/include/cpu/tb.h` also declares TB functions, and +libtcg's copy has drifted from upstream. The `tb-maint.c` import in phase 2 will +expose this immediately. Decide the ownership boundary explicitly rather than +patching both. + +**`precise-pc.c` is not S2E-original either.** It carries copies of upstream +`translate-all.c`'s restore machinery (`encode_sleb128`, `encode_search`, +`cpu_restore_state_from_tb`) plus the S2E-only `tb_get_instruction_size()`, and +it calls `restore_state_to_opc()`, defined today in `target-i386/translate.c`, +which phase 3 replaces, and reached in 11.1 through +`TCGCPUOps.restore_state_to_opc`. The phase 2 `translate-all.c` import collides +with it exactly the way `tb-maint.c` collides with `tb.h`; decide its ownership +there, not after the frontend lands. + +**Target-specific code in a target-independent library.** libtcg currently ships +the i386 helper list and SSE header. Any plan that leaves them there will hit a +circular dependency the moment upstream's helper signatures arrive, because +`HELPER_H` is resolved inside libtcg's `helper-gen.h`. Move it in phase 3, before +importing the helpers, not after. + +**`CPUID_EXT_S2E` has to be re-added by hand.** S2E advertises itself to the +guest through bit 16 of `CPUID.01H:ECX`, which upstream leaves reserved. The +bit is free, but nothing in upstream's `feature_word_info[]` will carry it. Add +it as an explicit, commented S2E deviation when importing the feature model in +phase 3, and make sure `x86_cpu_filter_features()` does not mask it off. + +**Codegen and C must agree on the `CPUTLBDescFast` index convention.** Upstream +inverts it (`mmuidx_to_fast_index()` = `NB_MMU_MODES - 1 - mmu_idx`); libtcg's +`tlb_mask_table_ofs()` does not. S2E already deviates by placing the TLB at a +positive offset from `env`, so either convention works. But if the generated +code and `cputlb.c` disagree, the fast path reads another mode's table, which +compiles clean and is wrong at run time. + +**Softfloat and decoder changes are guest-visible.** Fifteen years of x86 errata +fixes, denormal handling and rounding corrections are all in scope. Existing +guest images and any recorded traces should be re-baselined at phase 4 rather +than diffed against the old build. + +## 9. The new TLB in detail + +Decision 3.3 says "adopt upstream's TLB wholesale". That is still the +recommendation, but the TLB changed more between 1.0 and 11.1 than any other +part of accel/tcg, and three of the changes interact with S2E in ways that are +not obvious. This section is the detail behind that decision. + +### 9.1 What actually changed + +| | libcpu (QEMU 1.0) | QEMU 11.1 | +|---|---|---| +| Size | fixed, `CPU_TLB_SIZE` = 1024 | dynamic, 2^6 .. 2^20 entries, resized on flush | +| Entry | one struct, 64 B (S2E) / 32 B | split: `CPUTLBEntry` (32 B fast) + `CPUTLBEntryFull` (~48 B slow) | +| Victim TLB | none | 8 entries per mmu_idx, swapped into the main table on hit | +| Flag bits | `TARGET_PAGE_BITS-1 .. -7`, all in the entry | fixed bits 6-8 in the entry, plus `slow_flags[3]` in `CPUTLBEntryFull` | +| Large pages | `tlb_flush_addr` / `tlb_flush_mask` in env | `large_page_addr` / `large_page_mask` per `CPUTLBDesc` | +| MMU modes | 2 (kernel, user) | `NB_MMU_MODES` = 22 declared; x86 uses 8 | +| Storage | inline in `CPUX86State` | heap, via `fast->table` / `desc->fulltlb` | + +Two changes look like problems but are not: + +**Huge pages are a non-issue.** TLB entries are `TARGET_PAGE_SIZE` granular in +11.1 exactly as they were in 1.0. `tlb_set_page_full()` stores +`addr & TARGET_PAGE_MASK` and an addend computed at 4K granularity; a 2 MB guest +mapping produces up to 512 separate 4K entries as they are touched. +`full->lg_page_size` and `tlb_add_large_page()` exist only so that +`tlb_flush_range_locked()` can escalate to a full flush when an invalidated +range overlaps a region that large pages were mapped into, the same mechanism +libcpu's `tlb_add_large_page()` already uses with `env->tlb_flush_addr`. +**The `SE_RAM_OBJECT_BITS == 12` invariant is untouched**: one KLEE memory +object still corresponds to one 4K page, and nothing in the new code maps a TLB +entry to more than 4K. + +**Dynamic sizing is already supported by the generated code.** libtcg's +x86_64 backend loads `mask` and `table` out of `CPUTLBDescFast` at run time +(`tlb_mask_table_ofs()`), so a changing table size needs no codegen change. +`tcg_ctx->cpu_tlb_size` is vestigial, like every `TCGContext` geometry field +except `tlb_fast_offset` (see 3.3). + +### 9.2 Where it collides with S2E + +S2E does not treat the TLB as a pure cache. `S2EExecutionStateTlb` keeps +`m_tlbMap`: a map from KLEE `ObjectState` to the list of `(mmu_idx, index)` +coordinates of every TLB entry that points at it, so that when an object is +copied on write (a fork, or a concrete-to-symbolic transition), every cached +`se_addend` and `objectState` can be patched. Three of the 11.1 changes break +that. + +**(a) The victim TLB moves entries behind S2E's back.** `victim_tlb_hit()` +*swaps* a main-table entry with a victim entry, and `tlb_set_page_full()` +*evicts* the old main entry into the victim table. Both carry `objectState` and +`se_addend` with them. `m_tlbMap` coordinates address only the main table, so +after either operation the recorded coordinate points at a slot that no longer +holds that object, and `updateTlb()` will patch the wrong entry. This fails +silently; `audit()` would catch it, but it is debug-only. + +**(b) Resizing invalidates every coordinate.** `tlb_mmu_resize_locked()` does +`g_free(fast->table); g_free(desc->fulltlb)` and allocates fresh arrays; there +is no rehash. Every index in `m_tlbMap` becomes meaningless. This one is nearly +self-correcting, because resizing only ever happens inside +`tlb_flush_one_mmuidx_locked()`, and a flush already drives +`g_sqi.tlb.flush_tlb_cache()` (skipped in single-path mode, where the map is +unused, and while `g_se_disable_tlb_flush` is set, when flushes do not run at +all). But the flush is now *per mmu_idx* +(`tlb_flush_by_mmuidx()`), whereas `flushTlbCache()` clears the whole map, so +the hook needs either per-index granularity or a documented decision to be +conservative. x86 in 11.1 only uses a partial flush in two places, both +`tlb_flush_by_mmuidx(cs, 1 << MMU_NESTED_IDX)` in `svm_helper.c`, so the +conservative option is cheap. + +**(c) Heap tables are not part of the state snapshot.** This collision is the +most involved of the three. S2E registers exactly two KLEE objects over the CPU +state: `[0, offsetof(CPUX86State, eip))` symbolic and +`[offsetof(eip), sizeof(CPUX86State))` concrete. The TLB is inside the second +one *because it is inline in the struct*. That object is registered +shared-concrete, so KLEE never copies it; what gives every execution state its +own TLB with its own `objectState` pointers is the explicit +`saveConcreteState()` / `restoreConcreteState()` memcpy, which is correct by an +explicit ~216 KB copy per state switch rather than by construction. Move the +tables to the heap as upstream does, and all states share one TLB: state A's +`se_addend` would point into state A's concrete buffer while state B runs. That +is only a problem if the TLB survives the switch; section 9.3 argues it should +not. + +Three smaller collisions: + +**Flag bits.** 11.1 fixed the fast-path flags at bits 6, 7 and 8 +(`TLB_INVALID_MASK`, `TLB_NOTDIRTY`, `TLB_FORCE_SLOW`) and documents bits [9:6] +as the whole budget, leaving one free bit. S2E needs three: `TLB_SYMB`, +`TLB_NOT_OURS`, `TLB_MEM_TRACE`, currently at `TARGET_PAGE_BITS-5/-6/-7` where +they now collide with `TLB_NOTDIRTY` and `TLB_INVALID_MASK`. Note that libtcg's +`include/tcg/tlb.h` is an S2E-original that was never brought forward, so it +still describes the pre-11.1 scheme. It even retains `TLB_RECHECK` (removed +upstream in 4.1) and omits `TLB_MEM_TRACE` from `TLB_FLAGS_MASK`, which is why +every consumer hand-masks that bit. This has to be fixed regardless. + +**`mmuidx_to_fast_index()`.** Upstream inverts the `f[]` array index +(`NB_MMU_MODES - 1 - mmu_idx`) so lower mmu indices sit closer to `env`. +libtcg's `tlb_mask_table_ofs()` is *not* inverted. Since S2E puts the TLB at a +positive offset from `env` rather than upstream's negative one, it already +deviates. But codegen and C code must agree on the convention, or the fast path +will read another mode's table, which compiles clean and is wrong at run time. + +**`CPU_TLB_SIZE` as a compile-time constant.** It is baked into ten places in +libs2ecore: four outside the TLB code itself (`ExprInterface.cpp:184`, +`MMUFunctionHandlers.cpp:232` and `:458`, which re-implement the softmmu fast +path on the KLEE side, and `S2EExecutionState.cpp:833`), and six inside +`S2EExecutionStateTlb.cpp` (`updateRamTlb`, `updateTlbEntry`, +`updateTlbEntryConcreteStatus`, `clearRamTlb`, `clearTlbOwnership`, `audit`). +Three of the four outside sites index `se_ram_tlb`, not the main TLB. The +RAM TLB has no `CPUTLBDescFast`, so the run-time mask read prescribed in 9.3 +does not apply to them; the RAM TLB keeps its own pinned size. + +### 9.3 Recommendation: take the TLB out of the execution state + +The TLB is a cache of a mapping that is fully derivable from the guest page +tables and the KLEE address space. It is in the execution state only because it +happens to be inline in `CPUX86State`. Take it out, heap-allocate it as upstream +does, and **flush it on every state switch**. + +The objection is that state switches are frequent and a flush costs refills. +Set against what a state switch already does, that cost is small: + +| Already happens on every state switch | Cost | +|---|---| +| `s2e_kvm_flush_disk()` | drain + flush all block devices | +| `s2e_kvm_save_device_state()` -> `kvm_dev_save_snapshot()` | full vmstate serialize of the machine | +| `s2e_kvm_restore_device_state()` -> `kvm_dev_restore_snapshot()` | full vmstate deserialize | +| `FlushTBsOnStateSwitch` (**default true**) -> `se_tb_safe_flush()` | **the entire translation cache is discarded and every block retranslated** | +| `saveConcreteState` / `restoreConcreteState` | ~216 KB memcpy (see below) | + +A TB flush forces retranslation of every block that executes afterwards, at tens +of microseconds each across a working set of thousands of blocks. A TLB flush +costs one page-table walk per page actually touched afterwards. The TLB is +already the cheapest of the caches discarded at a switch, so keeping it +per-state saves little. + +**What this buys.** + +*`cputlb.c` imports nearly unpatched.* The one contained deviation remains the +pinned size (or fixed arena) in `tlb_mmu_init` / `tlb_mmu_resize_locked` plus +`tlb-bounds.h`, because the TLB stays KLEE-visible and bindings cannot be +re-created per state (decision 3.3, `tlb-update.md` section 5). Collisions (b) +and (c) from 9.2 disappear outright: (c) because heap tables not being in the +snapshot is now the intended behavior, and (b) because a resize only ever +happens inside a flush, and a flush already clears `m_tlbMap`. + +*Per-state memory drops sharply.* The concrete region carries, per state: + +| Field | Bytes | +|---|---:| +| `_tlb_table[2][1024]` @ 64 B | 128 KB | +| `iotlb[2][1024]` @ 8 B | 16 KB | +| `iotlb_ramaddr[2][1024]` @ 8 B (`CONFIG_SYMBEX_MP`) | 16 KB | +| `se_ram_tlb[1024]` @ 24 B | 24 KB | +| `tb_jmp_cache[4096]` @ 8 B | 32 KB | +| **total pure cache** | **~216 KB** | + +The TLB changes constantly, so copy-on-write never shares it between states: +that is ~216 KB of live memory per state today, and it would have been ~1 MB +per state at upstream's 8 mmu modes. At a thousand live states that is the +difference between ~200 MB and ~1 GB of cache nobody reads across a switch. + +*State switches get faster, not slower.* The `saveConcreteState` / +`restoreConcreteState` memcpy shrinks from ~216 KB to a few KB. + +**What it requires.** + +- Flush the TLB, the RAM TLB and `m_tlbMap` on state switch. Placement matters: + `doStateSwitch()` sets `g_se_disable_tlb_flush = 1` for the duration precisely + to suppress flushes during save/restore, so the flush belongs after the new + state is activated and the guard is cleared. +- `m_tlbMap` becomes executor data rather than state data. Today that is *not* + true: `S2EExecutionState`'s copy constructor does `m_tlb = state.m_tlb`, + handing every forked child a populated map, and `doStateSwitch()` leaves the + suspended state's map intact (coherent, because inactive maps index the + snapshot buffer via `getCpuState()`). Once the flush-on-switch lands and + `clone()` stops copying the map, it is only ever non-empty for the active + state and the per-state `S2EExecutionStateTlb` collapses into a single + instance. +- The compile-time `CPU_TLB_SIZE` sites in libs2ecore that index the *main* TLB + must read the mask at run time + (`cpu_tlb_fast(cpu, mmu_idx)->mask >> CPU_TLB_ENTRY_BITS`). The `se_ram_tlb` + sites are excluded: the RAM TLB has no `CPUTLBDescFast` and keeps its pinned + size (see 9.2). With the pinned-size option the rewrite is optional; it + becomes mandatory only with the arena option. +- `se_ram_tlb` and `tb_jmp_cache` move out of the snapshot on the same argument. + 11.1 already holds `tb_jmp_cache` as a heap pointer in `CPUState`, and since + TBs are flushed on switch anyway, its contents are already worthless across + one. +- `clearTlbOwnership()` at fork stays. The forking state keeps executing with a + live TLB whose entries are now shared, so the `TLB_NOT_OURS` sweep is still + needed; only the cross-switch persistence goes away. + +**Why it is sound.** The TLB caches (guest page tables -> host address, KLEE +`ObjectState`). Both inputs are per-state, so a cache that is never consulted +across a state boundary cannot leak one state's mapping into another. Verified: +no plugin reads `env->tlb_table`; every reader is an execution fast path in +libs2ecore (`MMUFunctionHandlers.cpp`, `ExprInterface.cpp`, +`S2EExecutionState.cpp`). One plugin *mutates* it: `MergingSearcher` calls +`tlb_flush(env, 1)` before merging. Once the TLB no longer persists across +switches, that call is dead and should be removed with this change. + +**Residual risk.** `flush-tbs-on-state-switch` can be set to false, at which +point the TLB flush becomes a larger share of the per-switch cost. Device-state +save/restore still dominates, and that option is documented as "faster but +possibly incorrect", so this does not change the recommendation. + +### 9.4 The victim TLB is a separate question + +Collision (a) is orthogonal to all of the above: `m_tlbMap` is needed *within* a +single state's execution to patch entries when an `ObjectState` is copied on +write, and the victim TLB moves entries around inside that execution. Making the +TLB non-persistent does not help. + +Start with the victim TLB disabled, skipping the eviction in +`tlb_set_page_full()` and the swap in `victim_tlb_hit()`. It is a pure cache; +the cost is extra `tlb_fill` calls. + +To enable it later, extend `m_tlbMap`'s coordinate space to address victim slots +(a `(mmu_idx, is_victim, index)` triple rather than a pair, not +`index + n_entries`, since `n_entries` now moves) and add two hooks: a swap for +`victim_tlb_hit()` and a move for the eviction in `tlb_set_page_full()`. Worth +doing only if profiling says the misses matter. + +### 9.5 Doing this before the upgrade + +The ownership change above is entangled with S2E's state management rather than +with QEMU's code, so it is the part of the port least helped by being done in +the middle of a 43k-line import. It can be landed on the current tree first +(introduce the `ArchCPU` layout, move the caches out of the registered KLEE +region entirely, flush at state switch) and validated on its own, on a tree +that still boots. `tlb-update.md` is that plan; it also shows why upstream's +dynamic sizing needs a pinned size or a fixed arena rather than an +allocator hook. + +### 9.6 What still has to be pinned or checked + +Nothing about the TLB size remains open. What remains from the earlier +analysis: + +- **S2E's flags go in `CPUTLBEntryFull.slow_flags[]`** (bits 5, 6, 7 are free, + exactly the three S2E needs; `TLB_MMIO` moved into the slow set at bit 4, + which is why only three remain), driven by `TLB_FORCE_SLOW`. No new fast-path + bit, no change to `TLB_FLAGS_MASK`, no codegen change. `softmmu_header.h` and + the KLEE-side handlers change from testing `tlb_entry->addr_read & TLB_SYMB` + to `full->slow_flags[MMU_DATA_LOAD] & TLB_SYMB`. +- **`se_addend` stays in `CPUTLBEntry`** (the backend loads it inline on the hit + path); **`objectState` moves to `CPUTLBEntryFull`** (only the helpers read it). + `CPUTLBEntry` becomes upstream's union, including `addr_idx[]`, whose layout + `tlb_read_idx()` asserts. +- **`NB_MMU_MODES`**: x86 uses 8 against S2E's 2. This no longer costs snapshot + bytes, but it still multiplies `tlb_init()` allocations and the + `clearTlbOwnership` / `audit` sweeps. Declare it as x86's 8 rather than + inheriting upstream's 22-mode maximum. +- **The `CPUTLBDescFast` index convention** must match between libtcg's + `tlb_mask_table_ofs()` and upstream's `mmuidx_to_fast_index()`. See section 8. +- **`env->se_tlb_current`** is a cached `CPUTLBEntry *` inside the snapshotted + state, written by the softmmu IO path and read from bitcode. Once the tables + are executor-owned it becomes a raw pointer from per-state data into a + reallocatable array: move it next to the TLB in `CPUNegativeOffsetState`, or + demote it to an index. +- **`libtcg/include/tcg/tlb.h`** is an S2E-original that was never brought + forward and still describes the pre-11.1 flag scheme (including `TLB_RECHECK`, + removed upstream in 4.1, and a `TLB_FLAGS_MASK` that omits `TLB_MEM_TRACE`). + It has to be fixed regardless of anything else here. diff --git a/libcpu/tlb-update.md b/libcpu/tlb-update.md new file mode 100644 index 000000000..ef00677b6 --- /dev/null +++ b/libcpu/tlb-update.md @@ -0,0 +1,361 @@ +# Making the TLB upgrade-ready, before the upgrade + +`PORTING.md` section 9 concludes that the TLB should stop living in the +execution state: it is a cache of a mapping derivable from the guest page tables +and the KLEE address space, and a state switch already discards the whole +translation block cache and round-trips the QEMU device model, both of which +cost far more than refilling it. + +That conclusion can be acted on now, on the QEMU-1.0 tree. +It is the one part of the port that is entangled with S2E's state management +rather than with QEMU's code, so it is the part least helped by doing it in the +middle of a 43k-line import. Done first, on a tree that still boots, it can be +validated on its own. Done later, a TLB bug and a `cputlb.c` port bug are hard +to tell apart. + +**Scope.** This changes *where the TLB lives and who owns it*. It does not adopt +any of 11.1's TLB algorithms: no dynamic sizing, no victim TLB, no +`CPUTLBEntryFull`, no flag-bit reallocation, no change to `NB_MMU_MODES` or +`CPU_TLB_SIZE`. Those arrive with the import. This work is what makes that +import a drop-in. + +Estimated effort: 1.5-2 weeks. + + +## 1. Target shape + +```c +/* libcpu/include/cpu/state.h */ + +typedef struct CPUTLB { + CPUTLBDesc d[NB_MMU_MODES]; /* iotlb today; fulltlb after the import */ + CPUTLBDescFast f[NB_MMU_MODES]; +} CPUTLB; + +typedef struct CPUNegativeOffsetState { + CPUTLB tlb; + CPUTLBRAMEntry se_ram_tlb[CPU_TLB_SIZE]; /* S2E */ + CPUTLBEntry *se_tlb_current; /* S2E */ + struct TranslationBlock *tb_jmp_cache[TB_JMP_CACHE_SIZE]; +} CPUNegativeOffsetState; + +struct CPUState { + /* ... the ~20 fields accel/tcg actually touches ... */ + CPUNegativeOffsetState neg; /* MUST BE LAST */ +}; + +struct ArchCPU { + CPUState parent_obj; + CPUX86State env; /* immediately after neg */ +}; +``` + +One global `ArchCPU`; `env` points at `&g_cpu.env`. Code generation addresses +the TLB at a **negative** offset from `env`, as upstream does: + +```c +tcg_ctx->tlb_fast_offset = offsetof(ArchCPU, neg.tlb.f) - offsetof(ArchCPU, env); +``` + +libtcg needs no change for this: it kept `TCGContext::tlb_fast_offset` as an S2E +deviation (upstream 11.1 dropped the field and computes the offset from +`CPUNegativeOffsetState` directly in `tlb_mask_table_ofs()`), the field is +`int`, and x86 displacements are signed. Keep the `f[]` array **non-inverted** +and define `cpu_tlb_fast(cpu, i)` as `&cpu->neg.tlb.f[i]`; upstream's +`mmuidx_to_fast_index()` inversion is a code-size optimization, and since we +hand-write that header anyway (`PORTING.md` decision 3.1) the deviation costs +one line and a comment. Inverting instead would mean teaching libtcg's +`tlb_mask_table_ofs()` about `NB_MMU_MODES`. + +Two KLEE objects over the CPU, as today, plus one for the caches: + +| Region | Kind | Snapshotted per state | +|---|---|---| +| `[env, env + offsetof(CPUX86State, eip))` | symbolic | yes (KLEE-managed) | +| `[env + offsetof(eip), env + sizeof(CPUX86State))` | shared concrete | yes (explicit memcpy) | +| `[&g_cpu, &g_cpu.env)`, the caches | shared concrete | **no** | + +During this work `CPUState` holds *only* the caches. When the port later moves +per-state execution fields (`interrupt_request`, `exception_index`, `halted`, +`jmp_env`) into the slim `CPUState`, they must not silently inherit this +never-snapshotted region; the snapshot boundary has to be revisited at that +point (`PORTING.md` phase 4). + +**The caches must stay KLEE-visible even though they are never snapshotted.** +`use-fast-helpers` defaults to *off*, so `replaceExternalFunctionsWithSpecialHandlers()` +never runs and the special handlers in `MMUFunctionHandlers.cpp` are not +installed. The bodies of `cpu_ld*_kernel` / `cpu_st*_kernel` and +`helper_ld*_mmu` / `helper_st*_mmu` therefore execute as bitcode inside KLEE, +and those bodies contain the inline TLB fast path. It is visible in the +built bitcode: `cpu_ldl_kernel` in `op_helper.bc` loads +`env + offsetof(tlb_table)`, dereferences `.table`, indexes it, reads +`addr_read`, and on a hit reads the plain `addend` at offset 24 before calling +`helper_ldl_mmu` only on a miss. (The bitcode build defines `SYMBEX_LLVM_LIB`, +so `softmmu_header.h` selects `addend`, the host RAM address KLEE binds RAM +objects at; `se_addend`, at offset 32, is used only by natively executed code.) +Every one of those is a KLEE memory operation and must resolve to a bound +object. + +`isSharedConcrete` is the right kind of registration: `ObjectState::readConcrete8()` +short-circuits to `((uint8_t *) m_address)[offset]`, so KLEE resolves the address +and then reads native memory, with no per-state buffer and no copy-on-write. The +registration is what is needed; the snapshot is not. + +## 2. Invariants to establish + +- **I1.** After `doStateSwitch()` returns, every TLB entry is invalid, + `se_ram_tlb` is cleared, `tb_jmp_cache` is cleared, and `m_tlbMap` is empty. +- **I2.** `m_tlbMap` and the live TLB agree at all times, which is what + `audit()` already checks. +- **I3.** Nothing reads or writes the TLB of an inactive state. +- **I4.** The cache region stays inside a registered shared-concrete KLEE + object, bound once in the initial state so every state inherits it, and never + rebound. See section 5 for why "never rebound" is the part that matters. + + +## 3. Steps + +Each step builds and passes the testsuite on its own. Only step 4 changes +behavior. + +### Step 0: Baseline and harness (half a day) + +- Record testsuite results, and two numbers to compare against later: + `doStateSwitch()` wall time, and resident memory at a fixed state count. +- Promote `audit()` from the `S2E_DEBUG_TLBCACHE` compile-time switch to a + runtime flag (`--tlb-audit`) so it can be turned on for a whole suite run. + +### Step 1: Fix two latent inconsistencies first (half a day) + +Both are pre-existing and both start to matter after step 4. Fixing them +against the current layout, where they are still testable, is cheaper than +fixing them afterwards. + +- **`S2EExecutionStateTlb` disagrees with itself about which CPU state it + means.** `flushTlbCachePage()` and `clearRamTlb()` write through the global + `env`; `updateTlb()`, `updateRamTlb()`, `clearTlbOwnership()` and `audit()` + go through `m_registers->getCpuState()`, which returns the *snapshot buffer* + for an inactive state; and `updateTlbEntry()` / + `updateTlbEntryConcreteStatus()` take `env` as a parameter, with a latent + mixed-accessor bug: `updateTlbEntry()` indexes its parameter, but the + `flushTlbCachePage()` it calls clears the global. Route all of them through + one accessor, a three-way unification rather than a two-way one. +- **`addressSpaceChangeUpdateTlb()` can fire on an inactive state.** + `AddressSpace::getWriteable()` notifies whichever state owns the address + space. The merge path runs with `!m_active`, and, in the dominant case, any + plugin write to guest memory of a *suspended* state + (`S2EExecutionStateMemory::write()` has no `m_active` guard) lands here too. + `addressSpaceSymbolicStatusChange()` and `addressSpaceObjectSplit()` are two + more unguarded entry points into `updateTlb()`. Decide the intended + behavior now and document it; step 4 makes all of them an early return. + +### Step 2: Introduce `ArchCPU`, no ownership change (2-3 days) + +- Add `libcpu/include/cpu/state.h` per section 1: `CPUTLB`, + `CPUNegativeOffsetState`, the slim `CPUState`, `ArchCPU`, `cpu_env()`, + `env_cpu()`, `cpu_tlb_fast()`. +- Move out of `CPU_COMMON` / `CPU_COMMON_TLB` / `CPU_COMMON_PHYSRAM_TLB`: + `tlb_table` (already a `CPUTLBDescFast[]` whose `.table` points into the + inline `_tlb_table` backing store), `_tlb_table`, `iotlb`, `iotlb_ramaddr`, + `se_ram_tlb`, `tb_jmp_cache`, and `se_tlb_current`, the cached + `CPUTLBEntry *` the softmmu IO path keeps in the CPU state; it points into + `_tlb_table` and must move with it. +- `cpu_x86_init()` allocates the single `ArchCPU`. +- Set `tcg_ctx->tlb_fast_offset` to the negative value. +- Rewrite the accessors: about a dozen sites in libcpu (`exec-tlb.c`, + `softmmu_header.h`, `softmmu_template.h`, `exec.c`, `cpu-exec.c`, + `translate-all.c`) and five in libs2ecore (`ExprInterface.cpp:187`, + `MMUFunctionHandlers.cpp:236` and `:461`, `S2EExecutionState.cpp:835`, plus + the `S2EExecutionStateTlb` loops). +- **Register `[&g_cpu, offsetof(ArchCPU, env))` as its own shared-concrete + object** in the initial state, alongside the existing two. Keep it snapshotted + for this step by copying it explicitly, so behavior is unchanged. + +Exit: `tlb_fast_offset < 0`, TLB addressed through `cpu_tlb_fast()`, behavior +unchanged, testsuite green. + +### Step 3: Confirm the binding is inherited, not per-state (1 day) + +The cache object is bound in the initial state's address space and inherited by +every fork. Confirm that, because step 4 depends on it and section 5 depends on +it never changing: + +- Add a check that a memory operation resolving into `[&g_cpu, &g_cpu.env)` + finds the object in *every* state, not just descendants of the initial one. +- Run the suite with both `use-fast-helpers` off (the default, bitcode bodies + execute) and on (handlers installed, bodies skipped). Both must pass; only the + first exercises the KLEE-visible TLB path. + +Exit: suite green in both modes. The explicit cache save/restore from step 2 is +still in place, so semantics are unchanged. + +### Step 4: Stop snapshotting, flush on switch (2-3 days) + +This step changes behavior; the earlier ones do not. + +- Drop the cache object from `saveConcreteState()` / `restoreConcreteState()`. +- In `doStateSwitch()`, **after** `newState->m_active = true` and **after** + `g_se_disable_tlb_flush = 0`: `tlb_flush(env, 1)` (which already clears + `tb_jmp_cache` and, in multi-path mode, drives `g_sqi.tlb.flush_tlb_cache()`, + always against the *active* state), `clearRamTlb()`, and an explicit + `m_tlbMap.clear()` on the *outgoing* state, which the hook does not touch. + Ordering matters, because `tlb_flush()` returns early while the guard is set. +- `addressSpaceChangeUpdateTlb()`: early-return when the state is not active. + Sound, because an inactive state has no TLB; it gets one when it is + activated. +- Assert `m_tlbMap.empty()` whenever `!m_active`. This needs one edit first: + `S2EExecutionState`'s copy constructor does `m_tlb = state.m_tlb`, handing + every forked child the parent's populated map, so `clone()` must clear the + child's map (or stop copying `m_tlb`) or the assertion fires on the first + fork. Keeping the class per-state with that assertion is a smaller diff than + hoisting it to the executor and gives the same guarantee; hoist later if it + reads better. + +Exit: testsuite green; the two step-0 numbers re-measured. Expect +`doStateSwitch()` to get *faster* (the memcpy drops by ~216 KB) and per-state +memory to drop by the same amount. + +### Step 5: Test the assumption directly (1 day) + +- Add a debug flag that flushes the TLB and `m_tlbMap` before **every** TB + execution, not just at state switches. If the suite passes with it on, nothing + anywhere depends on TLB persistence at any granularity, which is the claim + this change rests on. +- Run the suite with `--tlb-audit` on. + +### Step 6: Cleanups this enables (half a day) + +- `compareArchitecturalConcreteState()` currently does two `memcmp`s to skip the + `se_common_start` .. `se_common_end` window. That window does *not* exist only + for the caches: it also hides `current_tb`, `jmp_env`, the breakpoint and + watchpoint list heads, `opaque`, `temp_buf` and friends, which remain in + `CPUX86State` after this work. The window shrinks, but the two-`memcmp` shape + and the marker fields stay; they can only be deleted once the full port moves + the rest of `CPU_COMMON` into the slim `CPUState`. +- State merging becomes strictly more permissive as a side effect: it stops + comparing cache contents that were never architecturally meaningful. (The + `tlb_flush(env, 1)` that `MergingSearcher` performs before merging becomes + dead code at the same time and should be removed here.) + + +## 4. Hazards + +**`flushTlbCachePage()` asserts the object is in `m_tlbMap`.** After step 4 the +map is emptied at every switch, so any path that still expects an entry there +will abort rather than corrupt. That is the behavior we want, but expect to hit +it during bring-up; it is the most likely failure mode of step 4. The assert +is live in every build: libs2e strips `-DNDEBUG` from the release flags. + +**The flush must land outside `g_se_disable_tlb_flush`.** `doStateSwitch()` sets +that guard for the duration of save/restore because "some state save/restore +logic flushes the cache" and doing so mid-memory-operation is unsafe. The new +flush belongs after the guard is cleared, at the end of the function. + +**`clearTlbOwnership()` at fork stays.** The forking state keeps executing with +a live TLB whose entries are now shared with the child, so the `TLB_NOT_OURS` +sweep is still required. Only cross-switch persistence goes away. + +**`registerCpu()` checks `sizeof(*cpuEnv) == cpuEnv->size`**, against +`m_env->size = sizeof(*m_env)` set in libs2e. Both move together, but keep the +check; it is a cheap tripwire for exactly the kind of layout skew this work +introduces. + +**Do not assume the special function handlers are installed.** +`replaceExternalFunctionsWithSpecialHandlers()` is guarded by +`if (UseFastHelpers)`, and `use-fast-helpers` defaults to false and is not +enabled by any config in the tree. In the default configuration the bitcode +bodies of `cpu_*_kernel` and `helper_*_mmu` run inside KLEE and read the TLB +through KLEE's memory model. Any reasoning that starts from "the handler +intercepts it" is reasoning about the non-default path. + +**S2E snapshots are unaffected.** Guest snapshots are handled by vanilla QEMU, +not by libcpu, so changing `CPUX86State`'s layout does not invalidate existing +images. + + +## 5. Dynamic sizing, and why it is not an allocator problem + +**`malloc`/`free` do not have to be intercepted.** The reason is not that the +TLB is invisible to KLEE; it is visible (section 1). The reason is that the +reallocation should be removed rather than tracked. + +Upstream resizes by `g_free(fast->table); g_free(desc->fulltlb)` followed by +`g_try_new` for both, inside `tlb_mmu_resize_locked()`, which is only ever +reached from `tlb_flush_one_mmuidx_locked()`. Both the address and the size +change, and there is no rehash; the caller immediately runs +`tlb_mmu_flush_locked()`. + +Tracking that in KLEE would mean unbinding the old object and binding a new one +at each resize. The mechanics are easy: there are exactly three allocation +sites (`tlb_mmu_init`, `tlb_mmu_resize_locked`, `tlb_destroy`), so nothing +generic like an allocator hook is required. The difficulty is in the binding +model: + +**KLEE bindings are per-address-space, and address spaces are per-state.** +`ExecutionState::addExternalObject()` calls `m_addressSpace.bindObject()`, so a +binding created at time T exists only in that state and in states forked from it +after T. Every existing S2E registration (the CPU state, RAM, the dirty mask) +is done once in the *initial* state precisely so that every state inherits +it. A TLB rebind at run time would leave every sibling state resolving the TLB +address to nothing, and its next bitcode TLB read would fault. + +So the reallocation has to go. Two ways: + +**Pin the size (recommended for the port).** Set +`CPU_TLB_DYN_MIN_BITS == CPU_TLB_DYN_DEFAULT_BITS == CPU_TLB_DYN_MAX_BITS` so +`tlb_mmu_resize_locked()` returns on the `new_size == old_size` path it already +has, and point `tlb_mmu_init()` at a statically allocated region instead of +`g_new`. One registration at init, inherited by everyone, never rebound. Two +patched functions plus `tlb-bounds.h`. + +**Fixed arena, variable in-use sub-range (the upgrade path).** Register a +maximum-size arena once at init and have `tlb_mmu_init()` / +`tlb_mmu_resize_locked()` hand out slots inside it rather than calling +`g_new`/`g_free`. Dynamic sizing then works exactly as upstream intends and the +KLEE binding never changes. Same two functions patched, so no extra deviation +cost. One caveat to fix first: `ObjectState`'s constructor allocates a +`ConcreteBuffer` of the object's size whenever `size > FAST_CONCRETE_BUFFER_SIZE`, +and `setSharedConcrete()` is only called *afterwards* by +`addExternalObject()`, so today a large arena would allocate a matching buffer +it never uses. Passing the shared-concrete flag into the constructor is a small +KLEE change and a prerequisite for this option, but it must be per-object +opt-in rather than a blanket skip: the existing CPU concrete object *uses* its +`ConcreteBuffer` as the `saveConcreteState()` / `restoreConcreteState()` +snapshot store and must keep it. + +Everything else about sizing is already fine: + +- **Code generation** needs nothing. libtcg's backend loads `mask` and `table` + out of `CPUTLBDescFast` at run time; the only compile-time constant on that + path is `CPU_TLB_ENTRY_BITS`, and the entry size does not change. +- **`m_tlbMap`** coordinates are invalidated by a resize, but a resize only + happens inside a flush and a flush already clears the map. +- **libs2ecore's index arithmetic**, the compile-time `CPU_TLB_SIZE` uses (ten + in all; the `se_ram_tlb` ones keep their own pinned size), must become + run-time mask reads mirroring upstream's `tlb_index()` / + `tlb_entry()`. Needed for the arena option, not for the pinned one. +- **Cached entry pointers**: one. `m_tlbMap` stores indices and + `S2EExecutionStateTlb` only takes `CPUTLBEntry *` locally within a call, but + `env->se_tlb_current` is a live `CPUTLBEntry *` in the CPU state, written by + the softmmu IO path and read from bitcode. Step 2 moves it next to the + tables; under the arena option it must be rebased or demoted to an index when + the in-use sub-range changes. + +One thing to check rather than assume if the arena option is ever taken: +`tlb_mmu_resize_locked()` reads `get_clock_realtime()` for its window, so table +size would vary run to run. It is not architectural state and is not +snapshotted, so it cannot change guest-visible behavior. But if bit-for-bit +replay determinism matters, drive the heuristic from an instruction counter +instead. + +## 6. What this deliberately leaves alone + +Dynamic TLB sizing, the victim TLB, `CPUTLBEntryFull`, the 11.1 flag-bit +allocation, `NB_MMU_MODES`, and `CPU_TLB_SIZE` all stay exactly as they are. +Stopping here keeps the split clean: every one of those is a *QEMU* change that +arrives with `cputlb.c`, whereas everything above is an *S2E* change that would +otherwise have to be debugged simultaneously with a 43k-line import. + +After this lands, `PORTING.md` phase 2's TLB work reduces to importing +`cputlb.c` and mapping `CPUTLBEntryFull` onto `MemoryDesc`, with the state +management already in the shape the imported code expects. From ce765976f691d53179a8badd0eeccde3eec85073 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Thu, 20 Aug 2026 17:22:15 +0000 Subject: [PATCH 15/52] claude.md: updated writing style Signed-off-by: Vitaly Chipounov --- CLAUDE.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index a4a75d58a..bea3497b4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -45,3 +45,24 @@ Examples: - `libs2e: implemented basic device manager` - `libcpu: removed unused ymm fields` - `libs2ecore: allow any sizes for read/writes from/to concrete regions` + +## Comments and Documentation +- Write accurate and concise comments. Conciseness does not mean loss of important information and should not make readability worse. +- Comments are accurate first. Verify every claim a comment makes against the code it describes. A comment that promises behavior ("retried later", "cannot happen") must name the mechanism, and the mechanism must exist. Re-derive constants that carry units in their comment (a timeout "in seconds" computed in the wrong unit is a live bug the comment helps find). +- When shortening or rewording a comment, every fact in the old text is either kept or consciously discarded as wrong. +- Do not use "we" in comments. Be specific (e.g., the driver, the caller, etc.). +- Do not overuse semicolons or em-dashes. +- Use doxygen-style comments where appropriate (`///`, `@param`, `@return`). Use proper markers for parameters, etc. Every file starts (after the license header) with a `/// @file` block saying what the module does. +- Comments should be easy to read and sound natural. +- Do not use passive voice when the subject would actually convey additional information. +- In a multi-line comment, do not leave one or two words alone on the last line. +- Do not overuse the word "classic" (e.g., classic cause), "load bearing", "bearing", "seam", "wedged", "latch", "worth stating plainly", "full stop", "carry the argument", "the trap", "isn't just X — it's Y". and other LLMisms. +- Do not use adjectives and other words that bring no value (e.g., honest). +- Minimize jargon and uncommon words. Non-experts should be able to read and understand everything reasonably well. +- When introducing a new term or abbreviation for the first time, define it, especially if it is driver-specific. Common knowledge does not need to be defined (e.g., any standard driver terminology). +- Use plain English in comments and documentation. Do not coin aphorisms or metaphor slogans. A documentation heading must state its point plainly and be understandable before reading the body. +- No punchy fragments for drama. Write complete sentences. +- You are writing technical documentation, not marketing material. +- Some comments are functional and must keep their exact form: formatter on/off markers, and similar tool-consumed comments. Never restyle them. +- Comments justify designs on technical grounds. They do not narrate history, compare against previous implementations, reference external documentation, or paraphrase the code. +- Use American English. From 3f167705be5674f1bc3bba7ca3e8eed7b4c9776d Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Fri, 21 Aug 2026 15:46:38 +0000 Subject: [PATCH 16/52] libutils: relocated libtcg's platform-independent utils libtcg is configured per target: the build produces six trees per build type ({i386,x86_64} x {plain, s2e, s2e_sp}), and each rebuilds libtcg from scratch. libutils is configured once per build type, so keeping target-independent code in libtcg compiled every one of these objects six times. libtcg already declared find_package(LIBUTILS REQUIRED) and libs2e already linked libutils.a after libtcg.a, so no new dependency edge was needed. Moved 25 headers to libutils/include/utils/ and 8 sources to libutils/src/utils/. The include prefix becomes , matching libutils' existing flat / shape; 77 include lines across 46 files in libtcg, libcpu and libs2e follow. Three files stayed behind. log.c tests TARGET_I386 and CONFIG_SYMBEX to build its CPU_LOG_* mask table. bswap.h tests TARGET_WORDS_BIGENDIAN and TARGET_LONG_SIZE in live code and is mapped to upstream include/qemu/bswap.h, so it cannot be edited to drop the dependency without creating a merge deviation. cpu-float.h needs libtcg's fpu/softfloat-types.h. libutils now defines CONFIG_INT128, HOST_BIG_ENDIAN=0 and HAVE_GLIB_WITH_SLICE_ALLOCATOR, which int128.h, host-utils.h and qtree.h read. Consumers of those headers have to define them identically or the struct layouts disagree across translation units. The upgrade tooling follows the files: libutils gets its own scripts/upgrade/{BASELINE,mapping.tsv,merge.sh,normalize.sh} and the 28 corresponding rows move out of libtcg's mapping. merge.sh v11.1.0 v11.1.0 reports zero conflicts on both components. Signed-off-by: Vitaly Chipounov Co-Authored-By: Claude Opus 5 (1M context) --- libcpu/PORTING.md | 69 +++++------ libcpu/src/cpu-defs.h | 2 +- libcpu/src/exec-all.h | 2 +- libcpu/src/exec-bp.c | 2 +- libcpu/src/exec-memdbg.c | 2 +- libcpu/src/exec-phys.c | 2 +- libcpu/src/exec-phystb.c | 2 +- libcpu/src/exec-ram.c | 4 +- libcpu/src/exec-tb.c | 2 +- libcpu/src/exec-tlb.c | 2 +- libcpu/src/exec.c | 2 +- libcpu/src/target-i386/cpuid.c | 2 +- libcpu/src/target-i386/op_helper.c | 2 +- libcpu/src/translate-all.c | 4 +- libs2e/src/s2e-kvm-vcpu.cpp | 2 +- libtcg/include/fpu/softfloat-macros.h | 2 +- libtcg/include/fpu/softfloat-types.h | 2 +- libtcg/include/fpu/softfloat.h | 2 +- libtcg/include/tcg/exec/helper-proto-common.h | 2 +- libtcg/include/tcg/tb.h | 2 +- libtcg/include/tcg/tcg-gvec-desc.h | 2 +- libtcg/include/tcg/tcg-memop.h | 2 +- libtcg/include/tcg/tcg.h | 8 +- libtcg/include/tcg/tlb.h | 2 +- libtcg/include/tcg/x86_64/tcg-target-has.h | 2 +- libtcg/scripts/upgrade/README.md | 19 +-- libtcg/scripts/upgrade/mapping.tsv | 41 ++----- libtcg/src/CMakeLists.txt | 3 +- libtcg/src/fpu/softfloat.c | 4 +- libtcg/src/optimize.c | 6 +- libtcg/src/region.c | 18 +-- libtcg/src/tcg-common.c | 2 +- libtcg/src/tcg-op-gvec.c | 2 +- libtcg/src/tcg-op-ldst.c | 2 +- libtcg/src/tcg-op-vec.c | 2 +- libtcg/src/tcg-rt/tcg-runtime-gvec.c | 4 +- libtcg/src/tcg-rt/tcg-runtime.c | 4 +- libtcg/src/tcg.c | 12 +- libtcg/src/utils/log.c | 2 +- .../tcg => libutils/include}/utils/atomic.h | 0 .../include}/utils/atomic128.h | 6 +- .../tcg => libutils/include}/utils/bitmap.h | 0 .../tcg => libutils/include}/utils/bitops.h | 0 .../tcg => libutils/include}/utils/cache.h | 0 .../tcg => libutils/include}/utils/cpuid.h | 0 .../tcg => libutils/include}/utils/cutils.h | 0 .../include}/utils/debug-assert.h | 0 .../include}/utils/host-utils.h | 0 .../utils/host/generic/atomic128-cas.h | 0 .../utils/host/generic/atomic128-ldst.h | 0 .../host/generic/load-extract-al16-al8.h | 0 .../utils/host/generic/store-insert-al16.h | 0 .../utils/host/x86_64/atomic128-ldst.h | 2 +- .../include}/utils/host/x86_64/cpuinfo.h | 0 .../tcg => libutils/include}/utils/int128.h | 0 .../include}/utils/interval-tree.h | 0 .../tcg => libutils/include}/utils/memalign.h | 0 .../tcg => libutils/include}/utils/mutex.h | 0 .../tcg => libutils/include}/utils/osdep.h | 0 .../tcg => libutils/include}/utils/qtree.h | 0 .../include}/utils/registerfields.h | 2 +- .../tcg => libutils/include}/utils/rounding.h | 0 .../tcg => libutils/include}/utils/spinlock.h | 0 .../tcg => libutils/include}/utils/units.h | 0 libutils/scripts/upgrade/.gitignore | 1 + libutils/scripts/upgrade/BASELINE | 1 + libutils/scripts/upgrade/README.md | 75 ++++++++++++ libutils/scripts/upgrade/mapping.tsv | 42 +++++++ libutils/scripts/upgrade/merge.sh | 113 ++++++++++++++++++ libutils/scripts/upgrade/normalize.sh | 29 +++++ libutils/src/CMakeLists.txt | 13 ++ {libtcg => libutils}/src/utils/cache.c | 2 +- {libtcg => libutils}/src/utils/cpuinfo-i386.c | 4 +- {libtcg => libutils}/src/utils/cutils.c | 2 +- {libtcg => libutils}/src/utils/host-utils.c | 4 +- .../src/utils/interval-tree.c | 6 +- {libtcg => libutils}/src/utils/memalign.c | 4 +- {libtcg => libutils}/src/utils/osdep.c | 2 +- {libtcg => libutils}/src/utils/qtree.c | 4 +- 79 files changed, 405 insertions(+), 155 deletions(-) rename {libtcg/include/tcg => libutils/include}/utils/atomic.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/atomic128.h (94%) rename {libtcg/include/tcg => libutils/include}/utils/bitmap.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/bitops.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/cache.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/cpuid.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/cutils.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/debug-assert.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/host-utils.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/host/generic/atomic128-cas.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/host/generic/atomic128-ldst.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/host/generic/load-extract-al16-al8.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/host/generic/store-insert-al16.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/host/x86_64/atomic128-ldst.h (97%) rename {libtcg/include/tcg => libutils/include}/utils/host/x86_64/cpuinfo.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/int128.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/interval-tree.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/memalign.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/mutex.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/osdep.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/qtree.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/registerfields.h (99%) rename {libtcg/include/tcg => libutils/include}/utils/rounding.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/spinlock.h (100%) rename {libtcg/include/tcg => libutils/include}/utils/units.h (100%) create mode 100644 libutils/scripts/upgrade/.gitignore create mode 100644 libutils/scripts/upgrade/BASELINE create mode 100644 libutils/scripts/upgrade/README.md create mode 100644 libutils/scripts/upgrade/mapping.tsv create mode 100755 libutils/scripts/upgrade/merge.sh create mode 100755 libutils/scripts/upgrade/normalize.sh rename {libtcg => libutils}/src/utils/cache.c (98%) rename {libtcg => libutils}/src/utils/cpuinfo-i386.c (98%) rename {libtcg => libutils}/src/utils/cutils.c (99%) rename {libtcg => libutils}/src/utils/host-utils.c (99%) rename {libtcg => libutils}/src/utils/interval-tree.c (99%) rename {libtcg => libutils}/src/utils/memalign.c (97%) rename {libtcg => libutils}/src/utils/osdep.c (99%) rename {libtcg => libutils}/src/utils/qtree.c (99%) diff --git a/libcpu/PORTING.md b/libcpu/PORTING.md index 4e46cabd3..be58ca113 100644 --- a/libcpu/PORTING.md +++ b/libcpu/PORTING.md @@ -264,29 +264,31 @@ the same object. libtcg already declares `find_package(LIBUTILS REQUIRED)`, so the dependency edge exists and nothing new has to be wired up. -**This applies to what is already there, not only to the new imports.** Of -libtcg's 7,683-line `utils/` subset, ~7,140 lines are platform-independent -today. Two files reference a target or config macro: `utils/log.c`, in three -`#ifdef TARGET_I386` / `#ifdef CONFIG_SYMBEX` blocks that populate the -`CPU_LOG_*` mask table (`log.h` itself is clean), and `utils/bswap.h`, which -tests `TARGET_WORDS_BIGENDIAN` and `TARGET_LONG_SIZE` in live code, and is -mapped to upstream `include/qemu/bswap.h`, so it cannot be edited to drop the -dependency without creating a merge deviation. Move the rest to libutils; -either leave log and bswap behind, or make the log-mask table registrable and -split bswap's target-dependent tail into a libcpu header. - -Two consequences to plan for: - -- The include prefix changes from `` to whatever libutils adopts - (proposal: ``, matching libutils' existing flat `` / - `` shape). 54 files tree-wide include `tcg/utils/` (33 in - libtcg, 18 in libcpu, 3 in libs2e), so the rewrite is mechanical but wide; it - should land as its own commit, ahead of any libcpu work, and be re-verified - with `merge.sh v11.1.0 v11.1.0` reporting zero conflicts afterwards. -- The upgrade tooling follows the files. libutils becomes a home for vendored - QEMU code and needs its own `scripts/upgrade/{BASELINE,mapping.tsv}`, or, if - the scripts are parameterized by component root in phase 0, a second mapping - driven by the same driver. +**This applies to what is already there, not only to the new imports.** That +relocation is done: libtcg's `utils/` subset moved to `libutils/include/utils/` +and `libutils/src/utils/`, and the include prefix is now ``, matching +libutils' existing flat `` / `` shape. + +Three files stayed behind in `libtcg/include/tcg/utils/`. `utils/log.c` has +three `#ifdef TARGET_I386` / `#ifdef CONFIG_SYMBEX` blocks that populate the +`CPU_LOG_*` mask table (`log.h` itself is clean); `utils/bswap.h` tests +`TARGET_WORDS_BIGENDIAN` and `TARGET_LONG_SIZE` in live code and is mapped to +upstream `include/qemu/bswap.h`, so it cannot be edited to drop the dependency +without creating a merge deviation; `utils/cpu-float.h` needs the softfloat +types, which stay with libtcg. Making the log-mask table registrable and +splitting bswap's target-dependent tail into a libcpu header would let the +first two follow, but neither is on the critical path. + +`utils/qtree.h`, `utils/int128.h` and `utils/host-utils.h` read +`HAVE_GLIB_WITH_SLICE_ALLOCATOR`, `CONFIG_INT128` and `HOST_BIG_ENDIAN`. +`libutils/src/CMakeLists.txt` defines them for its own objects; every component +that includes these headers has to define them identically, or struct layouts +disagree across translation units. + +The upgrade tooling followed the files: libutils now has its own +`scripts/upgrade/{BASELINE,mapping.tsv,merge.sh,normalize.sh}`, and the 28 +corresponding rows moved out of libtcg's mapping. Both components report zero +conflicts under `merge.sh v11.1.0 v11.1.0`. ### 4.2 What 11.1 needs that we do not have @@ -305,13 +307,13 @@ vendored utils gives a short list. Placement follows the rule above. | `exec/icount.h`, `exec/replay-core.h`, `system/tcg.h`, `qemu/plugin.h`, `qemu/target-info.h` | n/a | missing | **Stub** in libcpu; these are configuration-dependent. icount off, replay off, `tcg_enabled()` is true, plugins compiled out. | | `qemu/queue.h` | n/a | have | libutils `qqueue.h`, already in the right place. | | glib allocation shims (`g_new`, `g_try_new`, `g_free`, `GArray`) | n/a | verify | Used by `qht.c`, `cputlb.c`, `tb-maint.c`; confirm libtcg's existing glib-compat covers the import closure, extend in **libutils** if not. | -| osdep, cutils, bitops, bitmap, int128, host-utils, atomic, atomic128, interval-tree, qtree, memalign, cacheinfo, units, cpuid | ~7,140 | have, misplaced | In `libtcg/include/tcg/utils/`; move to **libutils** per 4.1. | -| bswap | 308 | have, target-dependent | Tests `TARGET_WORDS_BIGENDIAN` / `TARGET_LONG_SIZE`; stays behind with log unless its target tail is split out (see 4.1). | -| log | 238 | have, target-dependent | Stays in libtcg unless the `CPU_LOG_*` mask table is made registrable. | +| osdep, cutils, bitops, bitmap, int128, host-utils, atomic, atomic128, interval-tree, qtree, memalign, cacheinfo, units, cpuid | ~7,140 | have | Moved to `libutils/include/utils/` and `libutils/src/utils/` per 4.1. | +| bswap | 308 | have, target-dependent | Tests `TARGET_WORDS_BIGENDIAN` / `TARGET_LONG_SIZE`; stayed in libtcg with log unless its target tail is split out (see 4.1). | +| log | 238 | have, target-dependent | Stayed in libtcg unless the `CPU_LOG_*` mask table is made registrable. | -Net: about 3.2k lines of newly imported utility code, plus a ~7.1k-line -relocation that removes five redundant compilations of each object per build -type. The dependency work is not what makes this project long. +Net: about 3.2k lines of newly imported utility code, on top of the ~7.1k-line +relocation that already removed five redundant compilations of each object per +build type. The dependency work is not what makes this project long. ## 5. What is deliberately not ported @@ -355,11 +357,10 @@ codebase. ### Phase 1: Substrate, utilities, CPUState, memory shim (2-3 weeks) -- **Relocate libtcg's platform-independent utils to libutils** (section 4.1), as - a standalone commit before anything else in this phase: 7,445 of 7,683 lines, - 33 include-site rewrites, `utils/log.{h,c}` left behind. Give libutils its own - `scripts/upgrade/{BASELINE,mapping.tsv}` and move the corresponding rows out of - libtcg's. Verify with `merge.sh v11.1.0 v11.1.0` on both components. +- **Relocate libtcg's platform-independent utils to libutils** (section 4.1) + — done. 33 files moved, 77 include lines across 46 files rewritten to + ``, `utils/{log.h,log.c,bswap.h,cpu-float.h}` left behind, and 28 + mapping rows moved into libutils' new `scripts/upgrade/`. - Import qht, rcu, thread, xxhash, seqlock into **libutils** per section 4.2; add them to libutils' new `mapping.tsv`. Fold libtcg's `utils/mutex.h` into the real thread header. diff --git a/libcpu/src/cpu-defs.h b/libcpu/src/cpu-defs.h index 1a9a56a30..a108bb627 100644 --- a/libcpu/src/cpu-defs.h +++ b/libcpu/src/cpu-defs.h @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include "qqueue.h" #ifdef CONFIG_SYMBEX diff --git a/libcpu/src/exec-all.h b/libcpu/src/exec-all.h index 721813e73..e9bc56a92 100644 --- a/libcpu/src/exec-all.h +++ b/libcpu/src/exec-all.h @@ -119,7 +119,7 @@ static inline unsigned int tb_phys_hash_func(tb_page_addr_t pc) { extern TranslationBlock *tb_phys_hash[CODE_GEN_PHYS_HASH_SIZE]; -#include +#include extern spinlock_t tb_lock; diff --git a/libcpu/src/exec-bp.c b/libcpu/src/exec-bp.c index 5ac89334a..2f95a88ca 100644 --- a/libcpu/src/exec-bp.c +++ b/libcpu/src/exec-bp.c @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include "exec.h" #include "qemu-common.h" diff --git a/libcpu/src/exec-memdbg.c b/libcpu/src/exec-memdbg.c index d66edc949..5ae8fdf67 100644 --- a/libcpu/src/exec-memdbg.c +++ b/libcpu/src/exec-memdbg.c @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include "qemu-common.h" #include diff --git a/libcpu/src/exec-phys.c b/libcpu/src/exec-phys.c index 6f9825ecd..cd23446c6 100644 --- a/libcpu/src/exec-phys.c +++ b/libcpu/src/exec-phys.c @@ -20,7 +20,7 @@ #include #include -#include +#include #include "exec.h" #include "qemu-common.h" diff --git a/libcpu/src/exec-phystb.c b/libcpu/src/exec-phystb.c index 55e4b23e5..53155d56f 100644 --- a/libcpu/src/exec-phystb.c +++ b/libcpu/src/exec-phystb.c @@ -19,7 +19,7 @@ #include #include -#include +#include #include "exec-phystb.h" #include "exec.h" #include "qemu-common.h" diff --git a/libcpu/src/exec-ram.c b/libcpu/src/exec-ram.c index 135c8872b..11ab91144 100644 --- a/libcpu/src/exec-ram.c +++ b/libcpu/src/exec-ram.c @@ -21,12 +21,12 @@ #include #include -#include +#include #include "exec-ram.h" #include "exec.h" #include "qemu-common.h" -#include +#include RAMList ram_list; diff --git a/libcpu/src/exec-tb.c b/libcpu/src/exec-tb.c index 64f2ac39d..8eb45fd16 100644 --- a/libcpu/src/exec-tb.c +++ b/libcpu/src/exec-tb.c @@ -23,7 +23,7 @@ #include #include -#include +#include #include "cpu.h" #include "qemu-common.h" diff --git a/libcpu/src/exec-tlb.c b/libcpu/src/exec-tlb.c index 14cd5e8d1..f88589733 100644 --- a/libcpu/src/exec-tlb.c +++ b/libcpu/src/exec-tlb.c @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include "qemu-common.h" #include "exec-phys.h" diff --git a/libcpu/src/exec.c b/libcpu/src/exec.c index dcbf2ae3b..4ff7dbeb7 100644 --- a/libcpu/src/exec.c +++ b/libcpu/src/exec.c @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include "cpu.h" #include "qemu-common.h" diff --git a/libcpu/src/target-i386/cpuid.c b/libcpu/src/target-i386/cpuid.c index faec489a1..b6aa796b1 100644 --- a/libcpu/src/target-i386/cpuid.c +++ b/libcpu/src/target-i386/cpuid.c @@ -26,7 +26,7 @@ #include #include #include -#include +#include /* feature flags taken from "Intel Processor Identification and the CPUID * Instruction" and AMD's "CPUID Specification". In cases of disagreement diff --git a/libcpu/src/target-i386/op_helper.c b/libcpu/src/target-i386/op_helper.c index 9e7b9faa9..edbb70f00 100644 --- a/libcpu/src/target-i386/op_helper.c +++ b/libcpu/src/target-i386/op_helper.c @@ -28,8 +28,8 @@ #include // clang-format on -#include #include +#include #include "softmmu_exec.h" diff --git a/libcpu/src/translate-all.c b/libcpu/src/translate-all.c index fefd1eecb..19b4a8324 100644 --- a/libcpu/src/translate-all.c +++ b/libcpu/src/translate-all.c @@ -33,8 +33,8 @@ #define NO_CPU_IO_DEFS #include #include -#include -#include +#include +#include #include "cpu.h" #include "timer.h" diff --git a/libs2e/src/s2e-kvm-vcpu.cpp b/libs2e/src/s2e-kvm-vcpu.cpp index 4b632f145..2a43548ba 100644 --- a/libs2e/src/s2e-kvm-vcpu.cpp +++ b/libs2e/src/s2e-kvm-vcpu.cpp @@ -40,7 +40,7 @@ #include #include #include -#include +#include #endif // #define SE_KVM_DEBUG_IRQ diff --git a/libtcg/include/fpu/softfloat-macros.h b/libtcg/include/fpu/softfloat-macros.h index be68d39c1..973706076 100644 --- a/libtcg/include/fpu/softfloat-macros.h +++ b/libtcg/include/fpu/softfloat-macros.h @@ -78,7 +78,7 @@ this code that are retained. #define FPU_SOFTFLOAT_MACROS_H #include "fpu/softfloat-types.h" -#include "tcg/utils/host-utils.h" +#include "utils/host-utils.h" #ifdef __cplusplus extern "C" { diff --git a/libtcg/include/fpu/softfloat-types.h b/libtcg/include/fpu/softfloat-types.h index da1bd9eee..f67811c92 100644 --- a/libtcg/include/fpu/softfloat-types.h +++ b/libtcg/include/fpu/softfloat-types.h @@ -83,7 +83,7 @@ this code that are retained. #include #include -#include +#include #ifdef __cplusplus extern "C" { diff --git a/libtcg/include/fpu/softfloat.h b/libtcg/include/fpu/softfloat.h index dfebf31fc..3d9bceb48 100644 --- a/libtcg/include/fpu/softfloat.h +++ b/libtcg/include/fpu/softfloat.h @@ -99,7 +99,7 @@ typedef enum { #include "fpu/softfloat-helpers.h" #include "fpu/softfloat-types.h" -#include "tcg/utils/int128.h" +#include "utils/int128.h" /*---------------------------------------------------------------------------- | Routine to raise any or all of the software IEC/IEEE floating-point diff --git a/libtcg/include/tcg/exec/helper-proto-common.h b/libtcg/include/tcg/exec/helper-proto-common.h index 80b6afe77..48b537a10 100644 --- a/libtcg/include/tcg/exec/helper-proto-common.h +++ b/libtcg/include/tcg/exec/helper-proto-common.h @@ -7,7 +7,7 @@ #ifndef HELPER_PROTO_COMMON_H #define HELPER_PROTO_COMMON_H -#include "tcg/utils/atomic128.h" /* for HAVE_CMPXCHG128 */ +#include "utils/atomic128.h" /* for HAVE_CMPXCHG128 */ #define HELPER_H "tcg/accel/tcg-runtime.h" #include "tcg/exec/helper-proto.h.inc" diff --git a/libtcg/include/tcg/tb.h b/libtcg/include/tcg/tb.h index 5caa340f6..09ea0cc97 100644 --- a/libtcg/include/tcg/tb.h +++ b/libtcg/include/tcg/tb.h @@ -21,7 +21,7 @@ #define _TCG_TB_H_ #include -#include +#include #ifdef __cplusplus extern "C" { diff --git a/libtcg/include/tcg/tcg-gvec-desc.h b/libtcg/include/tcg/tcg-gvec-desc.h index 439690381..c5a1a6e35 100644 --- a/libtcg/include/tcg/tcg-gvec-desc.h +++ b/libtcg/include/tcg/tcg-gvec-desc.h @@ -20,7 +20,7 @@ #ifndef TCG_GVEC_DEC_H #define TCG_GVEC_DEC_H -#include +#include #ifdef __cplusplus extern "C" { diff --git a/libtcg/include/tcg/tcg-memop.h b/libtcg/include/tcg/tcg-memop.h index 0d9c7aca4..0294913ac 100644 --- a/libtcg/include/tcg/tcg-memop.h +++ b/libtcg/include/tcg/tcg-memop.h @@ -12,7 +12,7 @@ #ifndef MEMOP_H #define MEMOP_H -#include +#include #ifdef __cplusplus extern "C" { diff --git a/libtcg/include/tcg/tcg.h b/libtcg/include/tcg/tcg.h index c5088e7b6..29a044e82 100644 --- a/libtcg/include/tcg/tcg.h +++ b/libtcg/include/tcg/tcg.h @@ -43,11 +43,11 @@ extern "C" { #include #include #include -#include -#include -#include #include -#include +#include +#include +#include +#include #include #include diff --git a/libtcg/include/tcg/tlb.h b/libtcg/include/tcg/tlb.h index 4ba7e6721..84f145f1a 100644 --- a/libtcg/include/tcg/tlb.h +++ b/libtcg/include/tcg/tlb.h @@ -3,7 +3,7 @@ #define TCG_TLB_H #include -#include +#include #ifdef __cplusplus extern "C" { diff --git a/libtcg/include/tcg/x86_64/tcg-target-has.h b/libtcg/include/tcg/x86_64/tcg-target-has.h index d76dc50c4..4d559ebe4 100644 --- a/libtcg/include/tcg/x86_64/tcg-target-has.h +++ b/libtcg/include/tcg/x86_64/tcg-target-has.h @@ -7,7 +7,7 @@ #ifndef TCG_TARGET_HAS_H #define TCG_TARGET_HAS_H -#include +#include #define have_bmi1 (cpuinfo & CPUINFO_BMI1) #define have_popcnt (cpuinfo & CPUINFO_POPCNT) diff --git a/libtcg/scripts/upgrade/README.md b/libtcg/scripts/upgrade/README.md index ba28a2f43..7ee29aba7 100644 --- a/libtcg/scripts/upgrade/README.md +++ b/libtcg/scripts/upgrade/README.md @@ -6,6 +6,13 @@ libtcg is a fork of QEMU's TCG that has been de-QEMU-ified (headers moved out of `git cherry-pick` or `patch` against upstream therefore never applies: every line differs because of reformatting alone. +Most of what used to sit in `tcg/utils/` now lives in libutils under +`utils/`, with its own copy of this tooling in `libutils/scripts/upgrade/`. +Only `utils/bswap.h`, `utils/cpu-float.h` and `utils/log.*` stayed here: the +first two depend on the target and on the softfloat types, and `log.c` tests +`TARGET_I386` and `CONFIG_SYMBEX` to build its mask table. Bumping a QEMU tag +means running both components' `merge.sh`. + The trick that makes upgrades tractable is to *normalize the formatting first*. Running an upstream file through `clang-format` with the S2E style reduces the difference against its libtcg counterpart to the genuine S2E delta. For @@ -40,11 +47,10 @@ reports files that were deleted upstream or added since the old tag, both of which need a human decision. Not every libtcg file tracks upstream closely. The utility files below the -"hand written" marker in `mapping.tsv` (`utils/osdep.h`, `utils/cutils.*`, -`utils/log.*`, `utils/bitmap.h`, `utils/bswap.h`) are heavily reduced -S2E-specific subsets rather than vendored copies, and are still v8.1.0-era. -They are listed for reference but want a manual look rather than a mechanical -merge. +"hand written" marker in `mapping.tsv` (`utils/log.*`, `utils/bswap.h`) are +heavily reduced S2E-specific subsets rather than vendored copies, and are still +v8.1.0-era. They are listed for reference but want a manual look rather than a +mechanical merge. Several S2E deviations in the merged code are deliberate and must survive future merges: @@ -53,9 +59,6 @@ merges: S2E addresses the CPU state by (offset, size) so helpers running as bitcode inside KLEE can read it back, which `offsetof`/`sizeof` on a bitfield cannot express. -- `host/generic/atomic128-cas.h` renames the `new` parameter to `_new`, since - these headers are included from C++. -- `utils/osdep.h` carries what upstream keeps in `include/qemu/compiler.h`. - `utils/cpu-float.h` holds the float/integer reinterpretation unions that upstream keeps in `include/qemu/cpu-float.h`. Leaving them in `bswap.h`, as older libtcg did, creates an include cycle through `softfloat-types.h` -> diff --git a/libtcg/scripts/upgrade/mapping.tsv b/libtcg/scripts/upgrade/mapping.tsv index e68360543..9d919346b 100644 --- a/libtcg/scripts/upgrade/mapping.tsv +++ b/libtcg/scripts/upgrade/mapping.tsv @@ -2,10 +2,11 @@ # # Only files that track upstream appear here. S2E-original files # (tcg-s2e.c, tcg-llvm.cpp, tcg/tb.h, tcg/tlb.h, tcg/regs.h, tcg/cpu.h, -# tcg/helper.h, tcg/ops_sse_header.h, utils/cache.h, utils/mutex.h, -# utils/spinlock.h, utils/rounding.h, tcg/qemu-plugin.h) are deliberately +# tcg/helper.h, tcg/ops_sse_header.h, tcg/qemu-plugin.h) are deliberately # absent: they have no upstream counterpart to merge from. # +# The platform-independent utilities live in libutils; see +# libutils/scripts/upgrade/mapping.tsv for their rows. # --- TCG core ----------------------------------------------------------- include/tcg/tcg.h include/tcg/tcg.h include/tcg/tcg-op.h include/tcg/tcg-op.h @@ -59,45 +60,17 @@ src/tcg-rt/tcg-runtime.c accel/tcg/tcg-runtime.c src/tcg-rt/tcg-runtime-gvec.c accel/tcg/tcg-runtime-gvec.c src/atomic_common.c.inc accel/tcg/atomic_common.c.inc src/atomic_template.h accel/tcg/atomic_template.h -# --- host support ------------------------------------------------------- -include/tcg/utils/host/x86_64/cpuinfo.h host/include/x86_64/host/cpuinfo.h -include/tcg/utils/host/x86_64/atomic128-ldst.h host/include/x86_64/host/atomic128-ldst.h.inc -include/tcg/utils/host/generic/atomic128-cas.h host/include/generic/host/atomic128-cas.h.inc -include/tcg/utils/host/generic/atomic128-ldst.h host/include/generic/host/atomic128-ldst.h.inc -include/tcg/utils/host/generic/load-extract-al16-al8.h host/include/generic/host/load-extract-al16-al8.h.inc -include/tcg/utils/host/generic/store-insert-al16.h host/include/generic/host/store-insert-al16.h.inc -src/utils/cpuinfo-i386.c util/cpuinfo-i386.c -# --- utilities ---------------------------------------------------------- -# These track BASELINE. Files not listed as changing upstream since v8.1.0 -# were simply never touched there, so they are current by definition. -include/tcg/utils/atomic.h include/qemu/atomic.h -include/tcg/utils/atomic128.h include/qemu/atomic128.h -include/tcg/utils/bitops.h include/qemu/bitops.h -include/tcg/utils/cpuid.h include/qemu/cpuid.h -include/tcg/utils/debug-assert.h include/tcg/debug-assert.h -include/tcg/utils/host-utils.h include/qemu/host-utils.h -include/tcg/utils/int128.h include/qemu/int128.h -include/tcg/utils/interval-tree.h include/qemu/interval-tree.h -include/tcg/utils/qtree.h include/qemu/qtree.h -include/tcg/utils/units.h include/qemu/units.h -include/tcg/utils/registerfields.h include/hw/core/registerfields.h +# --- target-dependent utilities ----------------------------------------- +# What is left of the old utils/ subset: everything platform-independent +# moved to libutils. cpu-float.h needs the softfloat types, and bswap.h and +# log.c test TARGET_* / CONFIG_SYMBEX macros, so all three stay here. include/tcg/utils/cpu-float.h include/qemu/cpu-float.h -src/utils/host-utils.c util/host-utils.c -src/utils/interval-tree.c util/interval-tree.c -src/utils/memalign.c util/memalign.c -src/utils/qtree.c util/qtree.c src/elf.h include/elf.h # Heavily reduced S2E-specific subsets, still v8.1.0-era: these are hand # written rather than vendored, so merge by hand, not mechanically. include/tcg/utils/bswap.h include/qemu/bswap.h -include/tcg/utils/memalign.h include/qemu/memalign.h -include/tcg/utils/bitmap.h include/qemu/bitmap.h -include/tcg/utils/cutils.h include/qemu/cutils.h include/tcg/utils/log.h include/qemu/log.h -include/tcg/utils/osdep.h include/qemu/osdep.h -src/utils/cutils.c util/cutils.c src/utils/log.c util/log.c -src/utils/osdep.c util/osdep.c # --- fpu ---------------------------------------------------------------- include/fpu/softfloat.h include/fpu/softfloat.h include/fpu/softfloat-types.h include/fpu/softfloat-types.h diff --git a/libtcg/src/CMakeLists.txt b/libtcg/src/CMakeLists.txt index 59c743789..9b3e1d9b5 100644 --- a/libtcg/src/CMakeLists.txt +++ b/libtcg/src/CMakeLists.txt @@ -21,8 +21,7 @@ set (TCG_SOURCES) list (APPEND TCG_SOURCES - utils/cutils.c utils/osdep.c utils/memalign.c utils/cache.c utils/log.c - utils/cpuinfo-i386.c utils/qtree.c utils/host-utils.c utils/interval-tree.c + utils/log.c region.c tcg.c tcg-s2e.c tcg-op-ldst.c tcg-common.c tcg-op.c optimize.c tcg-op-gvec.c tcg-op-vec.c tcg-rt/tcg-runtime-gvec.c tcg-rt/tcg-runtime.c atomic-helpers.c diff --git a/libtcg/src/fpu/softfloat.c b/libtcg/src/fpu/softfloat.c index f7ab2df18..05df0977e 100644 --- a/libtcg/src/fpu/softfloat.c +++ b/libtcg/src/fpu/softfloat.c @@ -88,8 +88,8 @@ this code that are retained. #include #include #include -#include -#include +#include +#include /* We only need stdlib for abort() */ diff --git a/libtcg/src/optimize.c b/libtcg/src/optimize.c index 8e2c3c2e4..481575a82 100644 --- a/libtcg/src/optimize.c +++ b/libtcg/src/optimize.c @@ -26,9 +26,9 @@ #include #include "tcg/utils/bswap.h" -#include "tcg/utils/int128.h" -#include "tcg/utils/interval-tree.h" -#include "tcg/utils/osdep.h" +#include "utils/int128.h" +#include "utils/interval-tree.h" +#include "utils/osdep.h" // clang-format off #include "tcg/tcg.h" diff --git a/libtcg/src/region.c b/libtcg/src/region.c index c1e6567b3..60552e64e 100644 --- a/libtcg/src/region.c +++ b/libtcg/src/region.c @@ -35,15 +35,15 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // clang-format off #include diff --git a/libtcg/src/tcg-common.c b/libtcg/src/tcg-common.c index b3e7faf91..c24789d22 100644 --- a/libtcg/src/tcg-common.c +++ b/libtcg/src/tcg-common.c @@ -23,7 +23,7 @@ */ #include -#include +#include const TCGOpDef tcg_op_defs[] = { #define DEF(s, oargs, iargs, cargs, flags) {#s, oargs, iargs, cargs, iargs + oargs + cargs, flags}, diff --git a/libtcg/src/tcg-op-gvec.c b/libtcg/src/tcg-op-gvec.c index 1b26ca90d..836b3be98 100644 --- a/libtcg/src/tcg-op-gvec.c +++ b/libtcg/src/tcg-op-gvec.c @@ -19,7 +19,7 @@ // Order of includes is important // clang-format off -#include +#include #include #include #include diff --git a/libtcg/src/tcg-op-ldst.c b/libtcg/src/tcg-op-ldst.c index 76787a6e7..af547fe5b 100644 --- a/libtcg/src/tcg-op-ldst.c +++ b/libtcg/src/tcg-op-ldst.c @@ -23,7 +23,7 @@ */ #include -#include +#include // clang-format off #include diff --git a/libtcg/src/tcg-op-vec.c b/libtcg/src/tcg-op-vec.c index 2f3c167de..82b144424 100644 --- a/libtcg/src/tcg-op-vec.c +++ b/libtcg/src/tcg-op-vec.c @@ -24,7 +24,7 @@ #include #include #include -#include +#include // clang-format on /* diff --git a/libtcg/src/tcg-rt/tcg-runtime-gvec.c b/libtcg/src/tcg-rt/tcg-runtime-gvec.c index 982765074..cd16f1e9a 100644 --- a/libtcg/src/tcg-rt/tcg-runtime-gvec.c +++ b/libtcg/src/tcg-rt/tcg-runtime-gvec.c @@ -19,8 +19,8 @@ #include -#include -#include +#include +#include // clang-format off #include diff --git a/libtcg/src/tcg-rt/tcg-runtime.c b/libtcg/src/tcg-rt/tcg-runtime.c index d7cd0066e..74f0a7efa 100644 --- a/libtcg/src/tcg-rt/tcg-runtime.c +++ b/libtcg/src/tcg-rt/tcg-runtime.c @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include // clang-format off #include diff --git a/libtcg/src/tcg.c b/libtcg/src/tcg.c index 7559125df..0da6257b9 100644 --- a/libtcg/src/tcg.c +++ b/libtcg/src/tcg.c @@ -40,13 +40,13 @@ #undef DEBUG_JIT #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -#include +#include #include diff --git a/libtcg/src/utils/log.c b/libtcg/src/utils/log.c index 3c35b57f3..b602ae670 100644 --- a/libtcg/src/utils/log.c +++ b/libtcg/src/utils/log.c @@ -22,7 +22,7 @@ #include #include -#include +#include extern uint8_t *code_gen_buffer; diff --git a/libtcg/include/tcg/utils/atomic.h b/libutils/include/utils/atomic.h similarity index 100% rename from libtcg/include/tcg/utils/atomic.h rename to libutils/include/utils/atomic.h diff --git a/libtcg/include/tcg/utils/atomic128.h b/libutils/include/utils/atomic128.h similarity index 94% rename from libtcg/include/tcg/utils/atomic128.h rename to libutils/include/utils/atomic128.h index 8053d05e7..a865d4582 100644 --- a/libtcg/include/tcg/utils/atomic128.h +++ b/libutils/include/utils/atomic128.h @@ -13,7 +13,7 @@ #ifndef QEMU_ATOMIC128_H #define QEMU_ATOMIC128_H -#include "tcg/utils/int128.h" +#include "utils/int128.h" #ifdef __cplusplus extern "C" { @@ -62,8 +62,8 @@ extern "C" { * Therefore, special case each platform. */ -#include "tcg/utils/host/generic/atomic128-cas.h" -#include "tcg/utils/host/x86_64/atomic128-ldst.h" +#include "utils/host/generic/atomic128-cas.h" +#include "utils/host/x86_64/atomic128-ldst.h" #ifdef __cplusplus } diff --git a/libtcg/include/tcg/utils/bitmap.h b/libutils/include/utils/bitmap.h similarity index 100% rename from libtcg/include/tcg/utils/bitmap.h rename to libutils/include/utils/bitmap.h diff --git a/libtcg/include/tcg/utils/bitops.h b/libutils/include/utils/bitops.h similarity index 100% rename from libtcg/include/tcg/utils/bitops.h rename to libutils/include/utils/bitops.h diff --git a/libtcg/include/tcg/utils/cache.h b/libutils/include/utils/cache.h similarity index 100% rename from libtcg/include/tcg/utils/cache.h rename to libutils/include/utils/cache.h diff --git a/libtcg/include/tcg/utils/cpuid.h b/libutils/include/utils/cpuid.h similarity index 100% rename from libtcg/include/tcg/utils/cpuid.h rename to libutils/include/utils/cpuid.h diff --git a/libtcg/include/tcg/utils/cutils.h b/libutils/include/utils/cutils.h similarity index 100% rename from libtcg/include/tcg/utils/cutils.h rename to libutils/include/utils/cutils.h diff --git a/libtcg/include/tcg/utils/debug-assert.h b/libutils/include/utils/debug-assert.h similarity index 100% rename from libtcg/include/tcg/utils/debug-assert.h rename to libutils/include/utils/debug-assert.h diff --git a/libtcg/include/tcg/utils/host-utils.h b/libutils/include/utils/host-utils.h similarity index 100% rename from libtcg/include/tcg/utils/host-utils.h rename to libutils/include/utils/host-utils.h diff --git a/libtcg/include/tcg/utils/host/generic/atomic128-cas.h b/libutils/include/utils/host/generic/atomic128-cas.h similarity index 100% rename from libtcg/include/tcg/utils/host/generic/atomic128-cas.h rename to libutils/include/utils/host/generic/atomic128-cas.h diff --git a/libtcg/include/tcg/utils/host/generic/atomic128-ldst.h b/libutils/include/utils/host/generic/atomic128-ldst.h similarity index 100% rename from libtcg/include/tcg/utils/host/generic/atomic128-ldst.h rename to libutils/include/utils/host/generic/atomic128-ldst.h diff --git a/libtcg/include/tcg/utils/host/generic/load-extract-al16-al8.h b/libutils/include/utils/host/generic/load-extract-al16-al8.h similarity index 100% rename from libtcg/include/tcg/utils/host/generic/load-extract-al16-al8.h rename to libutils/include/utils/host/generic/load-extract-al16-al8.h diff --git a/libtcg/include/tcg/utils/host/generic/store-insert-al16.h b/libutils/include/utils/host/generic/store-insert-al16.h similarity index 100% rename from libtcg/include/tcg/utils/host/generic/store-insert-al16.h rename to libutils/include/utils/host/generic/store-insert-al16.h diff --git a/libtcg/include/tcg/utils/host/x86_64/atomic128-ldst.h b/libutils/include/utils/host/x86_64/atomic128-ldst.h similarity index 97% rename from libtcg/include/tcg/utils/host/x86_64/atomic128-ldst.h rename to libutils/include/utils/host/x86_64/atomic128-ldst.h index 46a056780..4545781ab 100644 --- a/libtcg/include/tcg/utils/host/x86_64/atomic128-ldst.h +++ b/libutils/include/utils/host/x86_64/atomic128-ldst.h @@ -66,7 +66,7 @@ static inline void atomic16_set(Int128 *ptr, Int128 val) { } #else /* Provide QEMU_ERROR stubs. */ -#include "tcg/utils/host/generic/atomic128-ldst.h" +#include "utils/host/generic/atomic128-ldst.h" #endif #endif /* X86_64_ATOMIC128_LDST_H */ diff --git a/libtcg/include/tcg/utils/host/x86_64/cpuinfo.h b/libutils/include/utils/host/x86_64/cpuinfo.h similarity index 100% rename from libtcg/include/tcg/utils/host/x86_64/cpuinfo.h rename to libutils/include/utils/host/x86_64/cpuinfo.h diff --git a/libtcg/include/tcg/utils/int128.h b/libutils/include/utils/int128.h similarity index 100% rename from libtcg/include/tcg/utils/int128.h rename to libutils/include/utils/int128.h diff --git a/libtcg/include/tcg/utils/interval-tree.h b/libutils/include/utils/interval-tree.h similarity index 100% rename from libtcg/include/tcg/utils/interval-tree.h rename to libutils/include/utils/interval-tree.h diff --git a/libtcg/include/tcg/utils/memalign.h b/libutils/include/utils/memalign.h similarity index 100% rename from libtcg/include/tcg/utils/memalign.h rename to libutils/include/utils/memalign.h diff --git a/libtcg/include/tcg/utils/mutex.h b/libutils/include/utils/mutex.h similarity index 100% rename from libtcg/include/tcg/utils/mutex.h rename to libutils/include/utils/mutex.h diff --git a/libtcg/include/tcg/utils/osdep.h b/libutils/include/utils/osdep.h similarity index 100% rename from libtcg/include/tcg/utils/osdep.h rename to libutils/include/utils/osdep.h diff --git a/libtcg/include/tcg/utils/qtree.h b/libutils/include/utils/qtree.h similarity index 100% rename from libtcg/include/tcg/utils/qtree.h rename to libutils/include/utils/qtree.h diff --git a/libtcg/include/tcg/utils/registerfields.h b/libutils/include/utils/registerfields.h similarity index 99% rename from libtcg/include/tcg/utils/registerfields.h rename to libutils/include/utils/registerfields.h index 5ef2261b7..4ee575f76 100644 --- a/libtcg/include/tcg/utils/registerfields.h +++ b/libutils/include/utils/registerfields.h @@ -11,7 +11,7 @@ #ifndef REGISTERFIELDS_H #define REGISTERFIELDS_H -#include +#include /* Define constants for a 32 bit register */ diff --git a/libtcg/include/tcg/utils/rounding.h b/libutils/include/utils/rounding.h similarity index 100% rename from libtcg/include/tcg/utils/rounding.h rename to libutils/include/utils/rounding.h diff --git a/libtcg/include/tcg/utils/spinlock.h b/libutils/include/utils/spinlock.h similarity index 100% rename from libtcg/include/tcg/utils/spinlock.h rename to libutils/include/utils/spinlock.h diff --git a/libtcg/include/tcg/utils/units.h b/libutils/include/utils/units.h similarity index 100% rename from libtcg/include/tcg/utils/units.h rename to libutils/include/utils/units.h diff --git a/libutils/scripts/upgrade/.gitignore b/libutils/scripts/upgrade/.gitignore new file mode 100644 index 000000000..89f9ac04a --- /dev/null +++ b/libutils/scripts/upgrade/.gitignore @@ -0,0 +1 @@ +out/ diff --git a/libutils/scripts/upgrade/BASELINE b/libutils/scripts/upgrade/BASELINE new file mode 100644 index 000000000..a933a5dd7 --- /dev/null +++ b/libutils/scripts/upgrade/BASELINE @@ -0,0 +1 @@ +v11.1.0 diff --git a/libutils/scripts/upgrade/README.md b/libutils/scripts/upgrade/README.md new file mode 100644 index 000000000..2d51be717 --- /dev/null +++ b/libutils/scripts/upgrade/README.md @@ -0,0 +1,75 @@ +# Upgrading libutils' vendored QEMU utilities to a new QEMU release + +`include/utils/` and `src/utils/` hold a subset of QEMU's `util/`, +`include/qemu/` and `host/include/` that was de-QEMU-ified (headers moved out +of `qemu/` into `utils/`) and reformatted with the S2E `.clang-format` style. +They used to live in libtcg under `tcg/utils/`; they moved here because they +depend on no target macro and libtcg is configured once per target, so keeping +them in libtcg compiled every object six times per build type. + +A plain `git cherry-pick` or `patch` against upstream never applies: every line +differs because of reformatting alone. The trick that makes upgrades tractable +is to *normalize the formatting first*. Running an upstream file through +`clang-format` with the S2E style reduces the difference against its libutils +counterpart to the genuine S2E delta. + +The upgrade is then an ordinary three-way merge: + + base = clang-formatted upstream file at the OLD tag + theirs = clang-formatted upstream file at the NEW tag + ours = the current libutils file + + git merge-file ours base theirs + +The rest of libutils (QAPI, QObject, the visitors, coroutines, fsigc++) is not +covered here; it diverged from QEMU long ago and is maintained by hand. + +## Files + +- `mapping.tsv` — libutils path -> upstream QEMU path, one pair per line, tab + separated. Only files that track upstream are listed; S2E-original files + (`utils/cache.h`, `utils/mutex.h`, `utils/spinlock.h`, `utils/rounding.h`) + are deliberately absent. +- `BASELINE` — the QEMU tag `mapping.tsv` paths and the current tree correspond + to. Update it (and any renamed paths in `mapping.tsv`) once an upgrade lands. +- `normalize.sh` — extract one file from a QEMU tag and clang-format it. +- `merge.sh` — normalize every mapped file at both tags and three-way merge. + +libtcg has its own copy of the same tooling under `libtcg/scripts/upgrade/`, +covering the TCG core, the x86_64 backend, the fpu and the three utility files +that stay behind (`utils/bswap.h`, `utils/cpu-float.h`, `utils/log.*`). Both +should be re-run when a QEMU tag is bumped. + +## Running an upgrade + + export QEMU_SRC=~/qemu + ./merge.sh v10.2.0 v11.1.0 # writes into ./out, reports conflicts + ./merge.sh v10.2.0 v11.1.0 --apply # same, but writes back into the tree + +`merge.sh` follows upstream renames automatically (via `git diff -M`) and +reports files that were deleted upstream or added since the old tag, both of +which need a human decision. + +Not every file tracks upstream closely. The ones below the "hand written" +marker in `mapping.tsv` (`utils/osdep.h`, `utils/cutils.*`, `utils/bitmap.h`) +are heavily reduced S2E-specific subsets rather than vendored copies, and are +still v8.1.0-era. They are listed for reference but want a manual look rather +than a mechanical merge. + +Two S2E deviations in the merged code are deliberate and must survive future +merges: + +- `host/generic/atomic128-cas.h` renames the `new` parameter to `_new`, since + these headers are included from C++. +- `utils/osdep.h` carries what upstream keeps in `include/qemu/compiler.h`. + +`utils/qtree.h`, `utils/int128.h` and `utils/host-utils.h` read +`HAVE_GLIB_WITH_SLICE_ALLOCATOR`, `CONFIG_INT128` and `HOST_BIG_ENDIAN`. +`libutils/src/CMakeLists.txt` defines them, and every component that includes +these headers has to define them the same way, or the struct layouts disagree +across translation units. + +## After merging + +Re-run `run-clang-format.sh` from the S2E source root so the tree stays +normalized for the next upgrade. diff --git a/libutils/scripts/upgrade/mapping.tsv b/libutils/scripts/upgrade/mapping.tsv new file mode 100644 index 000000000..456540095 --- /dev/null +++ b/libutils/scripts/upgrade/mapping.tsv @@ -0,0 +1,42 @@ +# libutils path upstream QEMU path, as of the tag recorded in BASELINE. +# +# Only the vendored QEMU utilities below include/utils/ and src/utils/ appear +# here. The rest of libutils (QAPI, QObject, the visitors, coroutines, +# fsigc++) is S2E-original or diverged far enough that it is not merged +# mechanically, and the S2E-original utilities (utils/cache.h, utils/mutex.h, +# utils/spinlock.h, utils/rounding.h) have no upstream counterpart at all. +# +# --- host support ------------------------------------------------------- +include/utils/host/x86_64/cpuinfo.h host/include/x86_64/host/cpuinfo.h +include/utils/host/x86_64/atomic128-ldst.h host/include/x86_64/host/atomic128-ldst.h.inc +include/utils/host/generic/atomic128-cas.h host/include/generic/host/atomic128-cas.h.inc +include/utils/host/generic/atomic128-ldst.h host/include/generic/host/atomic128-ldst.h.inc +include/utils/host/generic/load-extract-al16-al8.h host/include/generic/host/load-extract-al16-al8.h.inc +include/utils/host/generic/store-insert-al16.h host/include/generic/host/store-insert-al16.h.inc +src/utils/cpuinfo-i386.c util/cpuinfo-i386.c +# --- utilities ---------------------------------------------------------- +# These track BASELINE. Files not listed as changing upstream since v8.1.0 +# were simply never touched there, so they are current by definition. +include/utils/atomic.h include/qemu/atomic.h +include/utils/atomic128.h include/qemu/atomic128.h +include/utils/bitops.h include/qemu/bitops.h +include/utils/cpuid.h include/qemu/cpuid.h +include/utils/debug-assert.h include/tcg/debug-assert.h +include/utils/host-utils.h include/qemu/host-utils.h +include/utils/int128.h include/qemu/int128.h +include/utils/interval-tree.h include/qemu/interval-tree.h +include/utils/qtree.h include/qemu/qtree.h +include/utils/units.h include/qemu/units.h +include/utils/registerfields.h include/hw/core/registerfields.h +src/utils/host-utils.c util/host-utils.c +src/utils/interval-tree.c util/interval-tree.c +src/utils/memalign.c util/memalign.c +src/utils/qtree.c util/qtree.c +# Heavily reduced S2E-specific subsets, still v8.1.0-era: these are hand +# written rather than vendored, so merge by hand, not mechanically. +include/utils/memalign.h include/qemu/memalign.h +include/utils/bitmap.h include/qemu/bitmap.h +include/utils/cutils.h include/qemu/cutils.h +include/utils/osdep.h include/qemu/osdep.h +src/utils/cutils.c util/cutils.c +src/utils/osdep.c util/osdep.c diff --git a/libutils/scripts/upgrade/merge.sh b/libutils/scripts/upgrade/merge.sh new file mode 100755 index 000000000..67bc61040 --- /dev/null +++ b/libutils/scripts/upgrade/merge.sh @@ -0,0 +1,113 @@ +#!/bin/bash +# +# Three-way merge every vendored QEMU utility in libutils from one QEMU tag to +# another. See README.md for the rationale. +# +# Usage: QEMU_SRC=~/qemu ./merge.sh [--apply] +# +set -e + +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +LIBUTILS=$(cd "${HERE}/../.." && pwd) +QEMU_SRC=${QEMU_SRC:-${HOME}/qemu} +OUT=${OUT:-${HERE}/out} + +OLD=$1 +NEW=$2 +APPLY=$3 + +if [ -z "${OLD}" ] || [ -z "${NEW}" ]; then + echo "Usage: QEMU_SRC=/path/to/qemu $0 [--apply]" >&2 + exit 1 +fi + +rm -rf "${OUT}" +mkdir -p "${OUT}/base" "${OUT}/new" "${OUT}/merged" + +clean=0 +conflicted=0 + +# mapping.tsv records upstream paths as of the newest release libutils tracks, so +# a path may need resolving in either direction depending on which end of the +# upgrade we are looking at. +resolve_new_path() { + local path=$1 + if git -C "${QEMU_SRC}" cat-file -e "${NEW}:${path}" 2>/dev/null; then + echo "${path}" + return 0 + fi + git -C "${QEMU_SRC}" diff --diff-filter=R -M --name-status "${OLD}" "${NEW}" | + awk -v old="${path}" -F'\t' '$2 == old { print $3; exit }' +} + +resolve_old_path() { + local path=$1 + if git -C "${QEMU_SRC}" cat-file -e "${OLD}:${path}" 2>/dev/null; then + echo "${path}" + return 0 + fi + git -C "${QEMU_SRC}" diff --diff-filter=R -M --name-status "${OLD}" "${NEW}" | + awk -v new="${path}" -F'\t' '$3 == new { print $2; exit }' +} + +printf '%-56s %9s %9s %s\n' FILE S2E UPSTREAM STATUS + +while IFS=$'\t' read -r lf qf; do + case "${lf}" in '' | '#'*) continue ;; esac + + name=$(basename "${lf}") + mkdir -p "${OUT}/base/$(dirname "${lf}")" "${OUT}/new/$(dirname "${lf}")" \ + "${OUT}/merged/$(dirname "${lf}")" + + oqf=$(resolve_old_path "${qf}") + if [ -z "${oqf}" ]; then + printf '%-56s %9s %9s %s\n' "${lf}" - - "ABSENT-AT-${OLD} (${qf})" + continue + fi + QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${OLD}" "${oqf}" "${name}" > "${OUT}/base/${lf}" + + nqf=$(resolve_new_path "${oqf}") + if [ -z "${nqf}" ]; then + printf '%-56s %9s %9s %s\n' "${lf}" - - "REMOVED-IN-${NEW} (${qf})" + continue + fi + QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${NEW}" "${nqf}" "${name}" > "${OUT}/new/${lf}" + + s2e=$(diff "${OUT}/base/${lf}" "${LIBUTILS}/${lf}" | grep -c '^[<>]' || true) + up=$(diff "${OUT}/base/${lf}" "${OUT}/new/${lf}" | grep -c '^[<>]' || true) + + status=ok + [ "${oqf}" != "${nqf}" ] && status="renamed ${oqf} -> ${nqf}" + + cp "${LIBUTILS}/${lf}" "${OUT}/merged/${lf}" + if git merge-file -L libutils -L "qemu ${OLD}" -L "qemu ${NEW}" \ + "${OUT}/merged/${lf}" "${OUT}/base/${lf}" "${OUT}/new/${lf}" > /dev/null 2>&1; then + clean=$((clean + 1)) + else + n=$(grep -c '^<<<<<<<' "${OUT}/merged/${lf}" || true) + status="CONFLICT (${n})" + conflicted=$((conflicted + 1)) + fi + + [ "${up}" = "0" ] && continue + printf '%-56s %9s %9s %s\n' "${lf}" "${s2e}" "${up}" "${status}" +done < "${HERE}/mapping.tsv" + +echo +echo "clean: ${clean} conflicted: ${conflicted} output: ${OUT}/merged" + +# Files that appeared upstream since the old tag may need to be imported by +# hand; there is no way to guess their libutils name. +echo +echo "Added upstream between ${OLD} and ${NEW} (review for import):" +git -C "${QEMU_SRC}" diff --diff-filter=A --name-only "${OLD}" "${NEW}" -- \ + util/ include/qemu/ host/include/ | sed 's/^/ /' + +if [ "${APPLY}" = "--apply" ]; then + echo + echo "Applying merged files into ${LIBUTILS}" + (cd "${OUT}/merged" && find . -type f -print0) | + while IFS= read -r -d '' f; do + cp "${OUT}/merged/${f#./}" "${LIBUTILS}/${f#./}" + done +fi diff --git a/libutils/scripts/upgrade/normalize.sh b/libutils/scripts/upgrade/normalize.sh new file mode 100755 index 000000000..e85f89454 --- /dev/null +++ b/libutils/scripts/upgrade/normalize.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# +# Extract one file from a QEMU tag and reformat it with the S2E style, so that +# it can be compared or merged against its libutils counterpart. +# +# Usage: QEMU_SRC=~/qemu ./normalize.sh v11.1.0 tcg/tcg.c [assumed-filename] +# +set -e + +QEMU_SRC=${QEMU_SRC:-${HOME}/qemu} +CLANG_FORMAT=${CLANG_FORMAT:-clang-format-19} +STYLE_FILE=${STYLE_FILE:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)/.clang-format} + +TAG=$1 +FILE=$2 +NAME=${3:-$(basename "${FILE}")} + +if [ -z "${TAG}" ] || [ -z "${FILE}" ]; then + echo "Usage: QEMU_SRC=/path/to/qemu $0 [assumed-filename]" >&2 + exit 1 +fi + +if [ ! -f "${STYLE_FILE}" ]; then + echo "Cannot find .clang-format at ${STYLE_FILE}" >&2 + exit 1 +fi + +git -C "${QEMU_SRC}" show "${TAG}:${FILE}" | + "${CLANG_FORMAT}" -style="file:${STYLE_FILE}" --assume-filename="${NAME}" diff --git a/libutils/src/CMakeLists.txt b/libutils/src/CMakeLists.txt index 416cc7ac3..74020f58d 100644 --- a/libutils/src/CMakeLists.txt +++ b/libutils/src/CMakeLists.txt @@ -21,6 +21,10 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror -Wno-initializer-overrides -fPIC") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -fPIC -std=c++20") +# The vendored QEMU utilities in utils/ read these. Consumers that include the +# headers must define them identically, so keep them in sync with libtcg. +add_definitions(-DCONFIG_INT128 -DHOST_BIG_ENDIAN=0 -DHAVE_GLIB_WITH_SLICE_ALLOCATOR) + add_library ( utils @@ -51,6 +55,15 @@ add_library ( q/error.c q/unicode.c q/cutils.c + + utils/cache.c + utils/cpuinfo-i386.c + utils/cutils.c + utils/host-utils.c + utils/interval-tree.c + utils/memalign.c + utils/osdep.c + utils/qtree.c ) ########## diff --git a/libtcg/src/utils/cache.c b/libutils/src/utils/cache.c similarity index 98% rename from libtcg/src/utils/cache.c rename to libutils/src/utils/cache.c index e811187da..01c5f8a79 100644 --- a/libtcg/src/utils/cache.c +++ b/libutils/src/utils/cache.c @@ -20,7 +20,7 @@ #include -#include +#include int g_icache_linesize = 0; int g_dcache_linesize = 0; diff --git a/libtcg/src/utils/cpuinfo-i386.c b/libutils/src/utils/cpuinfo-i386.c similarity index 98% rename from libtcg/src/utils/cpuinfo-i386.c rename to libutils/src/utils/cpuinfo-i386.c index d0658346e..a6d68be1b 100644 --- a/libtcg/src/utils/cpuinfo-i386.c +++ b/libutils/src/utils/cpuinfo-i386.c @@ -3,8 +3,8 @@ * Host specific cpu identification for x86. */ -#include -#include +#include +#include #ifdef CONFIG_CPUID_H #include "qemu/cpuid.h" diff --git a/libtcg/src/utils/cutils.c b/libutils/src/utils/cutils.c similarity index 99% rename from libtcg/src/utils/cutils.c rename to libutils/src/utils/cutils.c index cf42360f5..be2054b4f 100644 --- a/libtcg/src/utils/cutils.c +++ b/libutils/src/utils/cutils.c @@ -30,7 +30,7 @@ #include #include -#include +#include static int64_t suffix_mul(char suffix, int64_t unit) { switch (toupper(suffix)) { diff --git a/libtcg/src/utils/host-utils.c b/libutils/src/utils/host-utils.c similarity index 99% rename from libtcg/src/utils/host-utils.c rename to libutils/src/utils/host-utils.c index 9424e5be5..348e5b73e 100644 --- a/libtcg/src/utils/host-utils.c +++ b/libutils/src/utils/host-utils.c @@ -23,8 +23,8 @@ * THE SOFTWARE. */ -#include -#include +#include +#include #ifndef CONFIG_INT128 /* Long integer helpers */ diff --git a/libtcg/src/utils/interval-tree.c b/libutils/src/utils/interval-tree.c similarity index 99% rename from libtcg/src/utils/interval-tree.c rename to libutils/src/utils/interval-tree.c index b76c288ef..4bfd5060b 100644 --- a/libtcg/src/utils/interval-tree.c +++ b/libutils/src/utils/interval-tree.c @@ -1,8 +1,8 @@ /* SPDX-License-Identifier: GPL-2.0-or-later */ -#include "tcg/utils/interval-tree.h" -#include "tcg/utils/atomic.h" -#include "tcg/utils/osdep.h" +#include "utils/interval-tree.h" +#include "utils/atomic.h" +#include "utils/osdep.h" /* * Red Black Trees. diff --git a/libtcg/src/utils/memalign.c b/libutils/src/utils/memalign.c similarity index 97% rename from libtcg/src/utils/memalign.c rename to libutils/src/utils/memalign.c index bd9d338db..db081eb3c 100644 --- a/libtcg/src/utils/memalign.c +++ b/libutils/src/utils/memalign.c @@ -29,8 +29,8 @@ #include #include -#include -#include +#include +#include #define CONFIG_POSIX_MEMALIGN diff --git a/libtcg/src/utils/osdep.c b/libutils/src/utils/osdep.c similarity index 99% rename from libtcg/src/utils/osdep.c rename to libutils/src/utils/osdep.c index e5cda1b32..136ea75a6 100644 --- a/libtcg/src/utils/osdep.c +++ b/libutils/src/utils/osdep.c @@ -27,8 +27,8 @@ #include #include #include -#include #include +#include #define CONFIG_MADVISE diff --git a/libtcg/src/utils/qtree.c b/libutils/src/utils/qtree.c similarity index 99% rename from libtcg/src/utils/qtree.c rename to libutils/src/utils/qtree.c index 5d9544249..b3feee5df 100644 --- a/libtcg/src/utils/qtree.c +++ b/libutils/src/utils/qtree.c @@ -29,8 +29,8 @@ * MT safe */ -#include -#include +#include +#include /** * SECTION:trees-binary From 21540f04a771986f82f2f4ec86eb80f5b5648041 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Fri, 21 Aug 2026 16:23:20 +0000 Subject: [PATCH 17/52] libutils: derived the host config macros from one header CONFIG_INT128, HOST_BIG_ENDIAN and HAVE_GLIB_WITH_SLICE_ALLOCATOR were defined three times on the command line: in libutils, in libtcg and (for CONFIG_INT128) in libcpu's generated config-target.h. The bitcode rule for softfloat.c got none of them, because it passes CARGS_LIST, which libtcg never sets, so softfloat.bc declared mulu64() extern and carried an unresolvable reference that op_helper.bc inherited. utils/config-host.h now derives CONFIG_INT128 and HOST_BIG_ENDIAN from compiler builtins and fixes HAVE_GLIB_WITH_SLICE_ALLOCATOR, and int128.h and osdep.h include it, so every translation unit that uses a utils header sees the same values regardless of how it is compiled. The command-line copies are gone. CONFIG_CPUID_H stays undefined on purpose: the TCG backend would start advertising andc, ctz, clz, ctpop and vector ops that tcg-llvm.cpp does not translate. cpuinfo-i386.c and host/x86_64/atomic128-ldst.h still pointed at upstream include paths that exist nowhere in the tree; they now use . Co-Authored-By: Claude Fable 5 Signed-off-by: Vitaly Chipounov --- libcpu/CMakeLists.txt | 1 - libtcg/src/CMakeLists.txt | 2 +- libutils/include/utils/config-host.h | 51 +++++++++++++++++++ .../utils/host/x86_64/atomic128-ldst.h | 4 +- libutils/include/utils/int128.h | 2 + libutils/include/utils/osdep.h | 2 + libutils/src/CMakeLists.txt | 4 -- libutils/src/utils/cpuinfo-i386.c | 2 +- 8 files changed, 59 insertions(+), 9 deletions(-) create mode 100644 libutils/include/utils/config-host.h diff --git a/libcpu/CMakeLists.txt b/libcpu/CMakeLists.txt index 83d49ed36..90f0501fc 100644 --- a/libcpu/CMakeLists.txt +++ b/libcpu/CMakeLists.txt @@ -59,7 +59,6 @@ file(WRITE ${CONFIG_TARGET_H} #define TARGET_PHYS_ADDR_BITS 64 #define CONFIG_SOFTMMU 1 #define CONFIG_I386_DIS 1 -#define CONFIG_INT128 1 " ) diff --git a/libtcg/src/CMakeLists.txt b/libtcg/src/CMakeLists.txt index 9b3e1d9b5..e20806a60 100644 --- a/libtcg/src/CMakeLists.txt +++ b/libtcg/src/CMakeLists.txt @@ -34,7 +34,7 @@ endif (WITH_SYMBEX) add_library(tcg ${TCG_SOURCES}) set (COMMON_FLAGS "-Wall -fPIC -Werror -Wno-zero-length-array -Wno-mismatched-tags -Wno-initializer-overrides") -set (COMMON_FLAGS "${COMMON_FLAGS} -DCOMPILING_PER_TARGET -DCONFIG_SOFTMMU -DCONFIG_INT128 -DCPU_TEMP_BUF_NLONGS=128 -DHOST_BIG_ENDIAN=0 -DHAVE_GLIB_WITH_SLICE_ALLOCATOR") +set (COMMON_FLAGS "${COMMON_FLAGS} -DCOMPILING_PER_TARGET -DCONFIG_SOFTMMU -DCPU_TEMP_BUF_NLONGS=128") if (WITH_SYMBEX) set (COMMON_FLAGS "${COMMON_FLAGS} -DCONFIG_SYMBEX -DTCG_ENABLE_MEM_TRACING") diff --git a/libutils/include/utils/config-host.h b/libutils/include/utils/config-host.h new file mode 100644 index 000000000..dd4d420c0 --- /dev/null +++ b/libutils/include/utils/config-host.h @@ -0,0 +1,51 @@ +/// Copyright (c) 2026 Vitaly Chipounov +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy +/// of this software and associated documentation files (the "Software"), to deal +/// in the Software without restriction, including without limitation the rights +/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +/// copies of the Software, and to permit persons to whom the Software is +/// furnished to do so, subject to the following conditions: +/// +/// The above copyright notice and this permission notice shall be included in +/// all copies or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +/// SOFTWARE. + +#ifndef S2E_UTILS_CONFIG_HOST_H +#define S2E_UTILS_CONFIG_HOST_H + +// Host configuration for the vendored QEMU utilities. Upstream gets these from +// meson through qemu/osdep.h; here they derive from compiler builtins so that +// every translation unit that includes a utils header, in any component and +// under any build rule (including the clang -emit-llvm bitcode rules), sees the +// same definitions. Struct layouts in int128.h and qtree.h depend on them. + +// Upstream CONFIG_INT128: the compiler has __int128. +#ifdef __SIZEOF_INT128__ +#define CONFIG_INT128 1 +#endif + +#if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define HOST_BIG_ENDIAN 1 +#else +#define HOST_BIG_ENDIAN 0 +#endif + +// Always use QEMU's own QTree rather than aliasing it to GTree. Upstream +// switches on the glib version; keeping one implementation avoids a behavior +// change when the host glib is upgraded. +#define HAVE_GLIB_WITH_SLICE_ALLOCATOR 1 + +// CONFIG_CPUID_H is deliberately left undefined. With it, cpuinfo-i386.c +// detects BMI/POPCNT/LZCNT/AVX and the TCG backend then advertises andc, ctz, +// clz, ctpop and vector ops, which tcg-llvm.cpp does not translate. The TCG op +// set has to stay at the baseline until the LLVM translator covers them. + +#endif diff --git a/libutils/include/utils/host/x86_64/atomic128-ldst.h b/libutils/include/utils/host/x86_64/atomic128-ldst.h index 4545781ab..9a11d6fb4 100644 --- a/libutils/include/utils/host/x86_64/atomic128-ldst.h +++ b/libutils/include/utils/host/x86_64/atomic128-ldst.h @@ -13,8 +13,8 @@ #ifdef CONFIG_INT128_TYPE #include -#include "host/cpuinfo.h" -#include "tcg/debug-assert.h" +#include +#include typedef union { __m128i v; diff --git a/libutils/include/utils/int128.h b/libutils/include/utils/int128.h index fb21ffbb9..75eb7518f 100644 --- a/libutils/include/utils/int128.h +++ b/libutils/include/utils/int128.h @@ -5,6 +5,8 @@ #include #include +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/libutils/include/utils/osdep.h b/libutils/include/utils/osdep.h index d2225b747..fab4c0ad2 100644 --- a/libutils/include/utils/osdep.h +++ b/libutils/include/utils/osdep.h @@ -31,6 +31,8 @@ #include #include +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/libutils/src/CMakeLists.txt b/libutils/src/CMakeLists.txt index 74020f58d..443e544d5 100644 --- a/libutils/src/CMakeLists.txt +++ b/libutils/src/CMakeLists.txt @@ -21,10 +21,6 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror -Wno-initializer-overrides -fPIC") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -fPIC -std=c++20") -# The vendored QEMU utilities in utils/ read these. Consumers that include the -# headers must define them identically, so keep them in sync with libtcg. -add_definitions(-DCONFIG_INT128 -DHOST_BIG_ENDIAN=0 -DHAVE_GLIB_WITH_SLICE_ALLOCATOR) - add_library ( utils diff --git a/libutils/src/utils/cpuinfo-i386.c b/libutils/src/utils/cpuinfo-i386.c index a6d68be1b..3a09fa987 100644 --- a/libutils/src/utils/cpuinfo-i386.c +++ b/libutils/src/utils/cpuinfo-i386.c @@ -7,7 +7,7 @@ #include #ifdef CONFIG_CPUID_H -#include "qemu/cpuid.h" +#include #endif unsigned cpuinfo; From b3f127f7075794ce9aad1f14cf0720798ba20542 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Fri, 21 Aug 2026 16:23:20 +0000 Subject: [PATCH 18/52] build: stopped libutils edits from reconfiguring libs2e and tools stamps/libs2e-*-configure and stamps/tools-*-configure depended on stamps/libutils-*-make, and libs2e/configure removes every per-target tree before running cmake. Since the utilities moved into libutils, touching any of them wiped and rebuilt all six libs2e targets per build type. The configure stamps now depend on libutils' configure stamp only, and the make stamps depend on its make stamp, so a libutils change relinks incrementally. Co-Authored-By: Claude Fable 5 Signed-off-by: Vitaly Chipounov --- Makefile | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index b656a8f33..c198dfd4a 100644 --- a/Makefile +++ b/Makefile @@ -397,7 +397,7 @@ LIBS2E_RELEASE_FLAGS = --with-llvm=$(LLVM_PREFIX) stamps/libs2e-debug-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libs2e) stamps/libs2e-debug-configure: stamps/lua-make stamps/libvmi-debug-install \ - stamps/klee-debug-make stamps/libutils-debug-make \ + stamps/klee-debug-make stamps/libutils-debug-configure \ stamps/klee-coverage-make stamps/libs2e-debug-configure: CONFIGURE_COMMAND = $(S2E_SRC)/libs2e/configure \ $(LIBS2E_CONFIGURE_FLAGS) \ @@ -405,20 +405,22 @@ stamps/libs2e-debug-configure: CONFIGURE_COMMAND = $(S2E_SRC)/libs2e/configure stamps/libs2e-release-configure: $(call FIND_CONFIG_SOURCE,$(S2E_SRC)/libs2e) stamps/libs2e-release-configure: stamps/lua-make stamps/libvmi-release-install \ - stamps/klee-release-make stamps/libutils-release-make + stamps/klee-release-make stamps/libutils-release-configure stamps/libs2e-release-configure: CONFIGURE_COMMAND = $(S2E_SRC)/libs2e/configure \ $(LIBS2E_CONFIGURE_FLAGS) \ $(LIBS2E_RELEASE_FLAGS) -stamps/libs2e-debug-make: stamps/libs2e-debug-configure \ +# libutils changes must not reconfigure libs2e: configure wipes every per-target +# tree. Depend on its make stamp here so they only trigger an incremental build. +stamps/libs2e-debug-make: stamps/libs2e-debug-configure stamps/libutils-debug-make \ $(call FIND_SOURCE,$(S2E_SRC)/libs2e) \ $(call FIND_SOURCE,$(S2E_SRC)/libcpu) \ $(call FIND_SOURCE,$(S2E_SRC)/libtcg) \ $(call FIND_SOURCE,$(S2E_SRC)/libs2ecore) \ $(call FIND_SOURCE,$(S2E_SRC)/libs2eplugins) -stamps/libs2e-release-make: stamps/libs2e-release-configure \ +stamps/libs2e-release-make: stamps/libs2e-release-configure stamps/libutils-release-make \ $(call FIND_SOURCE,$(S2E_SRC)/libs2e) \ $(call FIND_SOURCE,$(S2E_SRC)/libcpu) \ $(call FIND_SOURCE,$(S2E_SRC)/libtcg) \ @@ -486,7 +488,7 @@ TOOLS_CONFIGURE_FLAGS = -DCMAKE_INSTALL_PREFIX=$(S2E_PREFIX) \ -DS2EPLUGINS_SRC_DIR=$(S2E_SRC)/libs2eplugins/src \ -G "Unix Makefiles" -stamps/tools-debug-configure: stamps/libvmi-debug-make stamps/libutils-debug-make +stamps/tools-debug-configure: stamps/libvmi-debug-make stamps/libutils-debug-configure stamps/tools-debug-configure: CONFIGURE_COMMAND = cmake $(TOOLS_CONFIGURE_FLAGS) \ -DVMI_DIR=$(S2E_BUILD)/libvmi-debug \ -DLIBUTILS_DIR=$(S2E_BUILD)/libutils-debug \ @@ -494,7 +496,7 @@ stamps/tools-debug-configure: CONFIGURE_COMMAND = cmake $(TOOLS_CONFIGURE_FLAGS) -DCMAKE_CXX_FLAGS="$(CXXFLAGS_DEBUG)" \ $(S2E_SRC)/tools -stamps/tools-release-configure: stamps/libvmi-release-make stamps/libutils-release-make +stamps/tools-release-configure: stamps/libvmi-release-make stamps/libutils-release-configure stamps/tools-release-configure: CONFIGURE_COMMAND = cmake $(TOOLS_CONFIGURE_FLAGS) \ -DVMI_DIR=$(S2E_BUILD)/libvmi-release \ -DLIBUTILS_DIR=$(S2E_BUILD)/libutils-release \ @@ -502,9 +504,9 @@ stamps/tools-release-configure: CONFIGURE_COMMAND = cmake $(TOOLS_CONFIGURE_FLAG -DCMAKE_CXX_FLAGS="$(CXXFLAGS_RELEASE)" \ $(S2E_SRC)/tools -stamps/tools-debug-make: stamps/tools-debug-configure +stamps/tools-debug-make: stamps/tools-debug-configure stamps/libutils-debug-make -stamps/tools-release-make: stamps/tools-release-configure +stamps/tools-release-make: stamps/tools-release-configure stamps/libutils-release-make stamps/tools-release-install: stamps/tools-release-make $(MAKE) -C tools-release install From 98a96bd692d47d537b385a9fc14473ae5894d2e9 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Fri, 21 Aug 2026 16:23:20 +0000 Subject: [PATCH 19/52] scripts: shared the qemu upgrade driver between libtcg and libutils libtcg and libutils carried byte-identical copies of merge.sh and normalize.sh. Both now live in scripts/upgrade/ at the source root; merge.sh takes the component name and reads /scripts/upgrade/mapping.tsv, whose new "# upstream-dirs:" header names the upstream directories to scan for added files. The components keep only BASELINE and mapping.tsv. merge.sh also computes the rename table once with the rename limit lifted (-l0), which used to skip inexact renames over a large range and report atomic128-ldst.h as absent at v8.1.0; reports pure renames, since their mapping row still has to change; reports a mapping row whose S2E file is missing instead of aborting; lists files written with conflict markers under --apply; and drops foreign-architecture host headers from the added-upstream list. The README, the upgrade skill and PORTING.md follow: both components are merged on every tag bump, libutils first, and the hand-written and S2E-original file lists now match mapping.tsv. Co-Authored-By: Claude Fable 5 Signed-off-by: Vitaly Chipounov --- .claude/skills/upgrade-libtcg/SKILL.md | 165 +++++++++++------- libcpu/PORTING.md | 57 +++--- libtcg/scripts/upgrade/README.md | 70 -------- libtcg/scripts/upgrade/mapping.tsv | 5 +- libtcg/scripts/upgrade/merge.sh | 113 ------------ libutils/scripts/upgrade/.gitignore | 1 - libutils/scripts/upgrade/README.md | 75 -------- libutils/scripts/upgrade/mapping.tsv | 8 +- libutils/scripts/upgrade/merge.sh | 113 ------------ libutils/scripts/upgrade/normalize.sh | 29 --- .../scripts => scripts}/upgrade/.gitignore | 0 scripts/upgrade/README.md | 119 +++++++++++++ scripts/upgrade/merge.sh | 161 +++++++++++++++++ .../scripts => scripts}/upgrade/normalize.sh | 4 +- 14 files changed, 424 insertions(+), 496 deletions(-) delete mode 100644 libtcg/scripts/upgrade/README.md delete mode 100755 libtcg/scripts/upgrade/merge.sh delete mode 100644 libutils/scripts/upgrade/.gitignore delete mode 100644 libutils/scripts/upgrade/README.md delete mode 100755 libutils/scripts/upgrade/merge.sh delete mode 100755 libutils/scripts/upgrade/normalize.sh rename {libtcg/scripts => scripts}/upgrade/.gitignore (100%) create mode 100644 scripts/upgrade/README.md create mode 100755 scripts/upgrade/merge.sh rename {libtcg/scripts => scripts}/upgrade/normalize.sh (88%) diff --git a/.claude/skills/upgrade-libtcg/SKILL.md b/.claude/skills/upgrade-libtcg/SKILL.md index 7f5a9d4f9..4ee51feed 100644 --- a/.claude/skills/upgrade-libtcg/SKILL.md +++ b/.claude/skills/upgrade-libtcg/SKILL.md @@ -1,27 +1,35 @@ --- name: upgrade-libtcg -description: Upgrade libtcg (and its softfloat/utils subsets) to a newer QEMU release. Use when asked to move libtcg to a new QEMU version, pull in upstream TCG changes, rebase the TCG fork, or when a QEMU tag is named alongside libtcg/tcg/softfloat. Covers the normalize-then-merge workflow, the S2E deviations that must survive, and the libcpu fallout. +description: Upgrade libtcg and libutils' vendored QEMU code (TCG core, softfloat, host utilities) to a newer QEMU release. Use when asked to move libtcg to a new QEMU version, pull in upstream TCG changes, rebase the TCG fork, or when a QEMU tag is named alongside libtcg/tcg/softfloat/libutils. Covers the normalize-then-merge workflow, the S2E deviations that must survive, and the libcpu fallout. --- -# Upgrading libtcg to a new QEMU release +# Upgrading libtcg and libutils to a new QEMU release -libtcg is a de-QEMU-ified fork of QEMU's TCG: headers are moved out of `qemu/`, -`exec/` and `accel/tcg/` into `tcg/utils/`, `tcg/exec/` and `tcg/accel/`, and the -whole tree is reformatted with the S2E `.clang-format`. **`git cherry-pick` and -`patch` never apply** — every line differs because of reformatting alone. +Two components carry vendored QEMU code and are upgraded together: -The tooling lives in `libtcg/scripts/upgrade/`. Read its `README.md` first. +- **libtcg**: a de-QEMU-ified fork of QEMU's TCG (headers moved out of `qemu/`, + `exec/` and `accel/tcg/` into `tcg/utils/`, `tcg/exec/` and `tcg/accel/`), + plus `fpu/` and the target-dependent `utils/{bswap.h,cpu-float.h,log.*}`. +- **libutils**: QEMU's platform-independent utilities under `include/utils/` + and `src/utils/` (upstream `util/`, `include/qemu/`, `host/include/`). + +Both trees are reformatted with the S2E `.clang-format`. **`git cherry-pick` +and `patch` never apply**: every line differs because of reformatting alone. + +The shared driver lives in `scripts/upgrade/` at the S2E source root; each +component keeps `scripts/upgrade/{BASELINE,mapping.tsv}`. Read +`scripts/upgrade/README.md` first. ## The core idea Run the upstream file through clang-format with the S2E style *before* -comparing. That collapses the diff to the genuine S2E delta — `src/tcg.c` goes -from ~6800 differing lines to ~79 — which makes the upgrade an ordinary +comparing. That collapses the diff to the genuine S2E delta (`libtcg/src/tcg.c` +goes from ~6800 differing lines to ~79), which makes the upgrade an ordinary three-way merge: base = clang-formatted upstream at the OLD tag theirs = clang-formatted upstream at the NEW tag - ours = the current libtcg file + ours = the current S2E file Expect most files to merge clean, including the big ones (`tcg.c`, `tcg-op.c`, `optimize.c`, `tcg-target.c.inc`). Conflicts are almost always one hunk in an @@ -31,56 +39,73 @@ include block or where S2E's `extern "C"` guard meets appended upstream code. ### 1. Scope it - cat libtcg/scripts/upgrade/BASELINE # the tag libtcg currently tracks - git -C ~/qemu log --oneline .. -- tcg/ include/tcg/ + cat libtcg/scripts/upgrade/BASELINE libutils/scripts/upgrade/BASELINE + git -C ~/qemu log --oneline .. -- tcg/ include/tcg/ util/ include/qemu/ host/include/ -**libtcg is not uniformly at one version.** The TCG core, `fpu/` and most of -`utils/` track `BASELINE`, but the hand-written subsets flagged in `mapping.tsv` -(`osdep.h`, `cutils.*`, `log.*`, `bitmap.h`, `bswap.h`) are still v8.1.0-era and -are not vendored. Before assuming a file's baseline, check -it: format the file at several candidate tags and pick the smallest diff. A file -that is stale relative to its neighbours is a bug waiting to happen — the 11.1 +**Neither component is uniformly at one version.** The TCG core, `fpu/` and the +vendored utilities track `BASELINE`, but the hand-written subsets flagged below +the "hand written" marker in each `mapping.tsv` (libutils: `osdep.*`, +`cutils.*`, `bitmap.h`, `memalign.h`; libtcg: `log.*`, `bswap.h`) are still +v8.1.0-era and are not vendored. Before assuming a file's baseline, check it: +format the file at several candidate tags and pick the smallest diff. A file +that is stale relative to its neighbors is a bug waiting to happen: the 11.1 upgrade found `tcg-gvec-desc.h` stranded at an old descriptor encoding while `simd_desc()` already wrote the new one. Note deleted, added and renamed files in the upstream range; `merge.sh` reports them but cannot decide what to do about them. -### 2. Merge +### 2. Merge, libutils first - cd libtcg/scripts/upgrade - QEMU_SRC=~/qemu ./merge.sh # dry run, reports conflicts - QEMU_SRC=~/qemu ./merge.sh --apply # write back + cd scripts/upgrade + QEMU_SRC=~/qemu ./merge.sh libutils # dry run + QEMU_SRC=~/qemu ./merge.sh libutils --apply # write back + QEMU_SRC=~/qemu ./merge.sh libtcg + QEMU_SRC=~/qemu ./merge.sh libtcg --apply -Prefer applying a chosen subset by hand over `--apply` when the upgrade is -scoped to part of the tree (e.g. TCG core but not `fpu/`). Merged output sits in -`scripts/upgrade/out/merged/`. +libutils goes first because libtcg's merged code may call utility APIs that +only arrive with the libutils merge. Prefer applying a chosen subset by hand +over `--apply` when the upgrade is scoped to part of the tree (e.g. TCG core +but not `fpu/`). Merged output sits in `scripts/upgrade/out//merged/`. +`--apply` writes conflicted files with markers and lists them; resolve them +before building. -Resolve conflicts by keeping the libtcg side of include blocks (the `` -paths and `// clang-format off` markers), and keeping the upstream side of -everything else, with the `extern "C"` guard moved to wrap the new code. +Resolve conflicts by keeping the S2E side of include blocks (the `` and +`` paths and `// clang-format off` markers), and keeping the upstream +side of everything else, with the `extern "C"` guard moved to wrap the new code. ### 3. Import new files by hand -Files upstream added have no libtcg name to merge into. Normalize, then rewrite -the includes to libtcg paths and add `extern "C"` guards: +Files upstream added have no S2E name to merge into. Normalize, then rewrite the +includes to S2E paths and add `extern "C"` guards: + + QEMU_SRC=~/qemu ./normalize.sh include/tcg/foo.h > ../../libtcg/include/tcg/foo.h + QEMU_SRC=~/qemu ./normalize.sh include/qemu/bar.h > ../../libutils/include/utils/bar.h - QEMU_SRC=~/qemu ./normalize.sh include/tcg/foo.h > ../../include/tcg/foo.h +Place by dependency, not by origin: anything that reads no `TARGET_*` or +`CONFIG_SYMBEX` macro belongs in libutils (libtcg is built six times per build +type, libutils once). Add the new row to that component's `mapping.tsv`. **Make imported headers self-contained.** Upstream relies on `qemu/osdep.h` -being included first everywhere; libtcg has no such prelude, and the S2E +being included first everywhere; S2E has no such prelude, and the S2E clang-format sets `SortIncludes: true`, so it will reorder an include block and -break any header that depends on its position. +break any header that depends on its position. Host configuration macros +(`CONFIG_INT128`, `HOST_BIG_ENDIAN`, `HAVE_GLIB_WITH_SLICE_ALLOCATOR`) come from +`utils/config-host.h`, pulled in by `utils/int128.h` and `utils/osdep.h`; never +add `-D` copies to a CMakeLists. ### 4. Build - cd ~/s2e/build/libs2e-release && make -j16 - cd ~/s2e/build/libs2e-debug && make -j16 + cd ~/s2e/build/libutils-release && make -j16 + cd ~/s2e/build/libs2e-release && make -j16 + cd ~/s2e/build/libutils-debug && make -j16 + cd ~/s2e/build/libs2e-debug && make -j16 -Both trees, six configurations each: `{i386,x86_64}-{,s2e-,s2e_sp-}softmmu`. -Iterate on `libs2e-release/x86_64-s2e-softmmu/libtcg` alone for a fast loop, but -finish on the full build — the i386 (`TARGET_LONG_BITS=32`) configurations -exercise different paths. +libutils before libs2e, since libs2e links `libutils.a`. Both libs2e trees have +six configurations each: `{i386,x86_64}-{,s2e-,s2e_sp-}softmmu`. Iterate on +`libs2e-release/x86_64-s2e-softmmu/libtcg` alone for a fast loop, but finish on +the full build: the i386 (`TARGET_LONG_BITS=32`) configurations exercise +different paths. ### 5. Verify the S2E patches survived @@ -88,13 +113,14 @@ A clean merge is not a correct merge. Diff each changed file against normalized upstream at the new tag and confirm the residual is *only* the expected S2E delta: - diff scripts/upgrade/out/new/src/x86_64/tcg-target.c.inc src/x86_64/tcg-target.c.inc + diff out/libtcg/new/src/x86_64/tcg-target.c.inc ../../libtcg/src/x86_64/tcg-target.c.inc + diff out/libutils/new/include/utils/bitops.h ../../libutils/include/utils/bitops.h Patches that must still be there, and that upstream refactors can silently relocate: - `s->qemu_ld_helpers` / `s->qemu_st_helpers` (per-context, not the static table) -- the `CONFIG_SYMBEX && CONFIG_SYMBEX_MP` `se_addend` load on the TLB hit path — +- the `CONFIG_SYMBEX && CONFIG_SYMBEX_MP` `se_addend` load on the TLB hit path; check it is anchored to the right `tcg_out_ld`, not merely present - `tcg_target_force_tb_exit` - `tcg_prologue_init(TCGContext *s)` taking the context explicitly @@ -105,51 +131,63 @@ relocate: ./run-clang-format.sh # from the S2E source root make -j16 # formatting can reorder includes; rebuild -Then update `BASELINE` and any renamed paths in `mapping.tsv`, add newly tracked -files, and confirm the tree is normalized by merging the new tag onto itself: +Then update both `BASELINE` files and any renamed paths in both `mapping.tsv`, +add newly tracked files, and confirm the trees are normalized by merging the +new tag onto itself: - QEMU_SRC=~/qemu ./merge.sh # must be 0 conflicts + QEMU_SRC=~/qemu ./merge.sh libutils # must be 0 conflicts + QEMU_SRC=~/qemu ./merge.sh libtcg # must be 0 conflicts ### 7. Commit -Per `CLAUDE.md`: `component: short description`, lowercase. Split by phase — -tooling, rename, the merge itself, then each consumer. Explain *why* in the -body, especially for anything that deviates from upstream. +Per `CLAUDE.md`: `component: short description`, lowercase. Split by phase: +tooling, rename, the libutils merge, the libtcg merge, then each consumer. +Explain *why* in the body, especially for anything that deviates from upstream. ## Deviations that must survive every merge +libutils: + +- **`host/generic/atomic128-cas.h`** renames the `new` parameter to `_new`. + These headers are included from C++, where `new` is a keyword. +- **`utils/bitops.h`** wraps `#define BIT(nr)` in `#ifndef BIT`, because + `libcpu/include/cpu/kvm.h` also defines it. +- **`utils/osdep.h`** carries what upstream keeps in `include/qemu/compiler.h` + (`QEMU_FLATTEN`, `QEMU_ALWAYS_INLINE`, `typeof_strip_qual`, ...). When a merge + pulls in code that needs a new compiler macro, add it here. +- **`utils/int128.h` and `utils/osdep.h`** include ``. +- **`src/utils/cpuinfo-i386.c`** includes ``; `CONFIG_CPUID_H` + stays undefined on purpose (see `utils/config-host.h`: the TCG op set must + not grow past what `tcg-llvm.cpp` translates). + +libtcg: + - **`float_status.float_rounding_mode` is a plain field, not a bitfield.** S2E addresses the CPU state by `(offset, size)`; `RR_cpu`/`WR_cpu` need `offsetof`/`sizeof`, which no bitfield supports. - **`tcg/utils/cpu-float.h`** holds the float/integer reinterpretation unions that upstream keeps in `include/qemu/cpu-float.h`. Leaving them in `bswap.h` - creates a cycle: `softfloat-types.h` → `registerfields.h` → `bitops.h` → - `host-utils.h` → `bswap.h`. + creates a cycle: `softfloat-types.h` -> `registerfields.h` -> `bitops.h` -> + `host-utils.h` -> `bswap.h`. - **`accel/getpc.h`** drops upstream's `#ifndef CONFIG_TCG #error` guard. - **`exec/helper-head.h.inc`** keeps its `#ifdef TARGET_LONG_BITS` guard instead of including `exec/target_long.h`. -- **`host/generic/atomic128-cas.h`** renames the `new` parameter to `_new`. - These headers are included from C++, where `new` is a keyword. -- **`utils/bitops.h`** wraps `#define BIT(nr)` in `#ifndef BIT`, because - `libcpu/include/cpu/kvm.h` also defines it. -- **`utils/osdep.h`** carries what upstream keeps in `include/qemu/compiler.h` - (`QEMU_FLATTEN`, `QEMU_ALWAYS_INLINE`, `typeof_strip_qual`, ...). When a merge - pulls in code that needs a new compiler macro, add it here. ## The libcpu fallout -libcpu consumes libtcg and breaks in ways libtcg's own build will not catch. +libcpu consumes libtcg and libutils and breaks in ways their own builds will +not catch. **Never replace `RR_cpu`/`WR_cpu` with direct struct access to silence a compiler error.** Under `CONFIG_SYMBEX` these route through -`g_sqi.regs.read_concrete()` when `fast_concrete_invocation` is false — that is, +`g_sqi.regs.read_concrete()` when `fast_concrete_invocation` is false, that is, when the helper runs as bitcode inside KLEE. Direct access reads the native copy of the CPU state instead of KLEE's, silently, on exactly the symbolic paths that matter. If upstream makes a field unaddressable, change the field in libtcg. **Check for newly required initialization.** Softfloat asserts at runtime when a NaN propagation rule or default NaN pattern was never set. `cpu_state_reset()` -memsets the CPU state, so anything of that kind must be reapplied there — see +memsets the CPU state, so anything of that kind must be reapplied there; see `cpu_init_fp_statuses()` in `libcpu/src/target-i386/helper.c`, mirroring QEMU's `target/i386/tcg/fpu_helper.c`. This class of bug builds clean and aborts later, so grep upstream's target code for setters the fork does not call. @@ -157,15 +195,16 @@ so grep upstream's target code for setters the fork does not call. **Watch for removed macros and renamed flags**, e.g. the removal of `TARGET_INSN_START_EXTRA_WORDS` (which made `tcg_gen_insn_start` take a fixed `INSN_START_WORDS` arguments, callers padding with zeroes), and -`float_flag_input_denormal` → `float_flag_input_denormal_flushed`. +`float_flag_input_denormal` -> `float_flag_input_denormal_flushed`. -## Things that change behaviour, not just code +## Things that change behavior, not just code Say so explicitly when reporting the upgrade: - Softfloat changes are guest-visible, and `softfloat.c` is compiled to `softfloat.bc` and interpreted by KLEE, so symbolic paths see them too. -- `float_status` layout changes do not break compatibility with existing S2E snapshots. Snapshots are handled by vanilla QEMU. +- `float_status` layout changes do not break compatibility with existing S2E + snapshots. Snapshots are handled by vanilla QEMU. - `tcg-llvm.cpp` switches over TCG opcodes; if the upstream range removes or renames any, the LLVM translator needs updating. Check the opcode list diff: `diff <(git show :include/tcg/tcg-opc.h | grep -oE '^DEF\([a-z0-9_]+') ...` @@ -175,4 +214,4 @@ Say so explicitly when reporting the upgrade: `testsuite/` drives real guest images through `~/s2e/projects/testsuite/*`. The launch scripts use `BUILD=debug`, so build `libs2e-debug` before running. `basic4-xmm` is the one most likely to notice softfloat changes. Ask before -running the suite — it is slow, and the user often has it covered. +running the suite; it is slow, and the user often has it covered. diff --git a/libcpu/PORTING.md b/libcpu/PORTING.md index be58ca113..4f1713761 100644 --- a/libcpu/PORTING.md +++ b/libcpu/PORTING.md @@ -29,7 +29,7 @@ makes upstream QEMU hard to extract. Second, libtcg has already been through this exercise. It is a de-QEMU-ified fork at `v11.1.0` with a normalize-then-three-way-merge upgrade path -(`libtcg/scripts/upgrade/`), and it is *almost* free-standing: the only symbol it +(`scripts/upgrade/` at the source root), and it is *almost* free-standing: the only symbol it needs from libcpu today is `helper_lookup_tb_ptr`. The boundary is already clean. ### Fate of the current tree @@ -70,12 +70,13 @@ ones. Take the same route libtcg took, so that the second upgrade (11.1 to 3. Record the pairing in `libcpu/scripts/upgrade/mapping.tsv`, with `BASELINE` = `v11.1.0`. 4. Confirm normalization by merging the tag onto itself: - `./merge.sh v11.1.0 v11.1.0` must report zero conflicts. + `./merge.sh libcpu v11.1.0 v11.1.0` must report zero conflicts. -`libtcg/scripts/upgrade/{normalize.sh,merge.sh}` already do steps 1 and 4; they -need a tree-root parameter so they can serve both components. Every S2E -deviation introduced from here on gets a comment saying *why*, because the merge -tool cannot preserve intent it cannot see. +`scripts/upgrade/{normalize.sh,merge.sh}` at the S2E source root already do +steps 1 and 4 for any component that carries `scripts/upgrade/mapping.tsv`, so +libcpu only needs the data files. Every S2E deviation introduced from here on +gets a comment saying *why*, because the merge tool cannot preserve intent it +cannot see. libcpu's current state is exactly what happens without this discipline: fourteen years of drift that can no longer be merged. The tooling is cheap, a day or two @@ -269,9 +270,10 @@ relocation is done: libtcg's `utils/` subset moved to `libutils/include/utils/` and `libutils/src/utils/`, and the include prefix is now ``, matching libutils' existing flat `` / `` shape. -Three files stayed behind in `libtcg/include/tcg/utils/`. `utils/log.c` has -three `#ifdef TARGET_I386` / `#ifdef CONFIG_SYMBEX` blocks that populate the -`CPU_LOG_*` mask table (`log.h` itself is clean); `utils/bswap.h` tests +Four files stayed behind: `utils/{log.h,bswap.h,cpu-float.h}` in +`libtcg/include/tcg/utils/` and `utils/log.c` in `libtcg/src/utils/`. +`utils/log.c` has three `#ifdef TARGET_I386` / `#ifdef CONFIG_SYMBEX` blocks +that populate the `CPU_LOG_*` mask table (`log.h` itself is clean); `utils/bswap.h` tests `TARGET_WORDS_BIGENDIAN` and `TARGET_LONG_SIZE` in live code and is mapped to upstream `include/qemu/bswap.h`, so it cannot be edited to drop the dependency without creating a merge deviation; `utils/cpu-float.h` needs the softfloat @@ -280,15 +282,17 @@ splitting bswap's target-dependent tail into a libcpu header would let the first two follow, but neither is on the critical path. `utils/qtree.h`, `utils/int128.h` and `utils/host-utils.h` read -`HAVE_GLIB_WITH_SLICE_ALLOCATOR`, `CONFIG_INT128` and `HOST_BIG_ENDIAN`. -`libutils/src/CMakeLists.txt` defines them for its own objects; every component -that includes these headers has to define them identically, or struct layouts -disagree across translation units. - -The upgrade tooling followed the files: libutils now has its own -`scripts/upgrade/{BASELINE,mapping.tsv,merge.sh,normalize.sh}`, and the 28 -corresponding rows moved out of libtcg's mapping. Both components report zero -conflicts under `merge.sh v11.1.0 v11.1.0`. +`HAVE_GLIB_WITH_SLICE_ALLOCATOR`, `CONFIG_INT128` and `HOST_BIG_ENDIAN`. They +come from `utils/config-host.h`, included by `int128.h` and `osdep.h` and +derived from compiler builtins, so every translation unit in every component +(including the bitcode rules) sees the same definitions without any `-D` flag. +Do not reintroduce command-line copies in libtcg or libcpu. + +The upgrade tooling followed the files: the shared driver now lives in +`scripts/upgrade/` at the source root, and libutils has its own +`scripts/upgrade/{BASELINE,mapping.tsv}` holding the 28 rows that moved out of +libtcg's mapping. Both components report zero conflicts under +`merge.sh v11.1.0 v11.1.0`. ### 4.2 What 11.1 needs that we do not have @@ -307,7 +311,7 @@ vendored utils gives a short list. Placement follows the rule above. | `exec/icount.h`, `exec/replay-core.h`, `system/tcg.h`, `qemu/plugin.h`, `qemu/target-info.h` | n/a | missing | **Stub** in libcpu; these are configuration-dependent. icount off, replay off, `tcg_enabled()` is true, plugins compiled out. | | `qemu/queue.h` | n/a | have | libutils `qqueue.h`, already in the right place. | | glib allocation shims (`g_new`, `g_try_new`, `g_free`, `GArray`) | n/a | verify | Used by `qht.c`, `cputlb.c`, `tb-maint.c`; confirm libtcg's existing glib-compat covers the import closure, extend in **libutils** if not. | -| osdep, cutils, bitops, bitmap, int128, host-utils, atomic, atomic128, interval-tree, qtree, memalign, cacheinfo, units, cpuid | ~7,140 | have | Moved to `libutils/include/utils/` and `libutils/src/utils/` per 4.1. | +| osdep, cutils, bitops, bitmap, int128, host-utils, atomic, atomic128, interval-tree, qtree, memalign, units, cpuid | ~7,140 | have | Moved to `libutils/include/utils/` and `libutils/src/utils/` per 4.1. `utils/cache.{h,c}` is S2E-original, not upstream `cacheinfo.c`. | | bswap | 308 | have, target-dependent | Tests `TARGET_WORDS_BIGENDIAN` / `TARGET_LONG_SIZE`; stayed in libtcg with log unless its target tail is split out (see 4.1). | | log | 238 | have, target-dependent | Stayed in libtcg unless the `CPU_LOG_*` mask table is made registrable. | @@ -339,11 +343,10 @@ codebase. ### Phase 0: Tooling and scaffolding (~1 week) -- Generalize `libtcg/scripts/upgrade/{normalize.sh,merge.sh}` to take a component - root, so libcpu can drive them; or fork them into `libcpu/scripts/upgrade/` if - that turns out cleaner. -- Create `libcpu/scripts/upgrade/{BASELINE,mapping.tsv,README.md}`. `BASELINE` is - `v11.1.0` from the start; `mapping.tsv` grows as files land. +- `scripts/upgrade/{normalize.sh,merge.sh}` already take a component name, so + nothing needs generalizing. Create `libcpu/scripts/upgrade/{BASELINE,mapping.tsv}` + with an `# upstream-dirs:` header. `BASELINE` is `v11.1.0` from the start; + `mapping.tsv` grows as files land. - Settle the target directory layout. Proposal, mirroring libtcg: `src/accel/` for accel/tcg files, `src/target-i386/` for the frontend and helpers, `src/s2e/` for S2E originals (exec-ram, exec-phys, memory, ioport, cpus, timer, @@ -351,14 +354,14 @@ codebase. - Create a scratch branch that builds the *current* tree with `CONFIG_SYMBEX` off, so the concrete-only configuration is known-good before anything moves. -**Exit:** `./merge.sh v11.1.0 v11.1.0` runs clean over an empty mapping; +**Exit:** `./merge.sh libcpu v11.1.0 v11.1.0` runs clean over an empty mapping; `normalize.sh` can emit any 11.1 file into its intended libcpu path; `x86_64-softmmu` builds and boots on the old code. ### Phase 1: Substrate, utilities, CPUState, memory shim (2-3 weeks) -- **Relocate libtcg's platform-independent utils to libutils** (section 4.1) - — done. 33 files moved, 77 include lines across 46 files rewritten to +- **Relocate libtcg's platform-independent utils to libutils** (section 4.1). + Done: 33 files moved, 77 include lines across 46 files rewritten to ``, `utils/{log.h,log.c,bswap.h,cpu-float.h}` left behind, and 28 mapping rows moved into libutils' new `scripts/upgrade/`. - Import qht, rcu, thread, xxhash, seqlock into **libutils** per section 4.2; add diff --git a/libtcg/scripts/upgrade/README.md b/libtcg/scripts/upgrade/README.md deleted file mode 100644 index 7ee29aba7..000000000 --- a/libtcg/scripts/upgrade/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# Upgrading libtcg to a new QEMU release - -libtcg is a fork of QEMU's TCG that has been de-QEMU-ified (headers moved out of -`qemu/`, `exec/` and `accel/tcg/` into `tcg/utils/`, `tcg/exec/` and -`tcg/accel/`) and reformatted with the S2E `.clang-format` style. A plain -`git cherry-pick` or `patch` against upstream therefore never applies: every -line differs because of reformatting alone. - -Most of what used to sit in `tcg/utils/` now lives in libutils under -`utils/`, with its own copy of this tooling in `libutils/scripts/upgrade/`. -Only `utils/bswap.h`, `utils/cpu-float.h` and `utils/log.*` stayed here: the -first two depend on the target and on the softfloat types, and `log.c` tests -`TARGET_I386` and `CONFIG_SYMBEX` to build its mask table. Bumping a QEMU tag -means running both components' `merge.sh`. - -The trick that makes upgrades tractable is to *normalize the formatting first*. -Running an upstream file through `clang-format` with the S2E style reduces the -difference against its libtcg counterpart to the genuine S2E delta. For -`src/tcg.c` that is the difference between a 6800-line diff and a 79-line one. - -The upgrade is then an ordinary three-way merge: - - base = clang-formatted upstream file at the OLD tag - theirs = clang-formatted upstream file at the NEW tag - ours = the current libtcg file - - git merge-file ours base theirs - -## Files - -- `mapping.tsv` — libtcg path -> upstream QEMU path, one pair per line, tab - separated. Only files that track upstream are listed; S2E-original files - (`tcg-s2e.c`, `tcg-llvm.cpp`, `tb.h`, `tlb.h`, ...) are deliberately absent. -- `BASELINE` — the QEMU tag `mapping.tsv` paths and the current tree correspond - to. Update it (and any renamed paths in `mapping.tsv`) once an upgrade lands. -- `normalize.sh` — extract one file from a QEMU tag and clang-format it. -- `merge.sh` — normalize every mapped file at both tags and three-way merge. - -## Running an upgrade - - export QEMU_SRC=~/qemu - ./merge.sh v10.2.0 v11.1.0 # writes into ./out, reports conflicts - ./merge.sh v10.2.0 v11.1.0 --apply # same, but writes back into the tree - -`merge.sh` follows upstream renames automatically (via `git diff -M`) and -reports files that were deleted upstream or added since the old tag, both of -which need a human decision. - -Not every libtcg file tracks upstream closely. The utility files below the -"hand written" marker in `mapping.tsv` (`utils/log.*`, `utils/bswap.h`) are -heavily reduced S2E-specific subsets rather than vendored copies, and are still -v8.1.0-era. They are listed for reference but want a manual look rather than a -mechanical merge. - -Several S2E deviations in the merged code are deliberate and must survive future -merges: - -- `float_status.float_rounding_mode` is a plain field rather than a bitfield. - S2E addresses the CPU state by (offset, size) so helpers running as bitcode - inside KLEE can read it back, which `offsetof`/`sizeof` on a bitfield cannot - express. -- `utils/cpu-float.h` holds the float/integer reinterpretation unions that - upstream keeps in `include/qemu/cpu-float.h`. Leaving them in `bswap.h`, as - older libtcg did, creates an include cycle through `softfloat-types.h` -> - `registerfields.h` -> `bitops.h` -> `host-utils.h` -> `bswap.h`. - -## After merging - -Re-run `run-clang-format.sh` from the S2E source root so the tree stays -normalized for the next upgrade. diff --git a/libtcg/scripts/upgrade/mapping.tsv b/libtcg/scripts/upgrade/mapping.tsv index 9d919346b..7db5ba164 100644 --- a/libtcg/scripts/upgrade/mapping.tsv +++ b/libtcg/scripts/upgrade/mapping.tsv @@ -6,7 +6,10 @@ # absent: they have no upstream counterpart to merge from. # # The platform-independent utilities live in libutils; see -# libutils/scripts/upgrade/mapping.tsv for their rows. +# libutils/scripts/upgrade/mapping.tsv for their rows. The merge driver is +# scripts/upgrade/merge.sh at the S2E source root. +# +# upstream-dirs: tcg/ include/tcg/ accel/tcg/ include/accel/ # --- TCG core ----------------------------------------------------------- include/tcg/tcg.h include/tcg/tcg.h include/tcg/tcg-op.h include/tcg/tcg-op.h diff --git a/libtcg/scripts/upgrade/merge.sh b/libtcg/scripts/upgrade/merge.sh deleted file mode 100755 index 9a9f9c041..000000000 --- a/libtcg/scripts/upgrade/merge.sh +++ /dev/null @@ -1,113 +0,0 @@ -#!/bin/bash -# -# Three-way merge every upstream-tracking libtcg file from one QEMU tag to -# another. See README.md for the rationale. -# -# Usage: QEMU_SRC=~/qemu ./merge.sh [--apply] -# -set -e - -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -LIBTCG=$(cd "${HERE}/../.." && pwd) -QEMU_SRC=${QEMU_SRC:-${HOME}/qemu} -OUT=${OUT:-${HERE}/out} - -OLD=$1 -NEW=$2 -APPLY=$3 - -if [ -z "${OLD}" ] || [ -z "${NEW}" ]; then - echo "Usage: QEMU_SRC=/path/to/qemu $0 [--apply]" >&2 - exit 1 -fi - -rm -rf "${OUT}" -mkdir -p "${OUT}/base" "${OUT}/new" "${OUT}/merged" - -clean=0 -conflicted=0 - -# mapping.tsv records upstream paths as of the newest release libtcg tracks, so -# a path may need resolving in either direction depending on which end of the -# upgrade we are looking at. -resolve_new_path() { - local path=$1 - if git -C "${QEMU_SRC}" cat-file -e "${NEW}:${path}" 2>/dev/null; then - echo "${path}" - return 0 - fi - git -C "${QEMU_SRC}" diff --diff-filter=R -M --name-status "${OLD}" "${NEW}" | - awk -v old="${path}" -F'\t' '$2 == old { print $3; exit }' -} - -resolve_old_path() { - local path=$1 - if git -C "${QEMU_SRC}" cat-file -e "${OLD}:${path}" 2>/dev/null; then - echo "${path}" - return 0 - fi - git -C "${QEMU_SRC}" diff --diff-filter=R -M --name-status "${OLD}" "${NEW}" | - awk -v new="${path}" -F'\t' '$3 == new { print $2; exit }' -} - -printf '%-56s %9s %9s %s\n' FILE S2E UPSTREAM STATUS - -while IFS=$'\t' read -r lf qf; do - case "${lf}" in '' | '#'*) continue ;; esac - - name=$(basename "${lf}") - mkdir -p "${OUT}/base/$(dirname "${lf}")" "${OUT}/new/$(dirname "${lf}")" \ - "${OUT}/merged/$(dirname "${lf}")" - - oqf=$(resolve_old_path "${qf}") - if [ -z "${oqf}" ]; then - printf '%-56s %9s %9s %s\n' "${lf}" - - "ABSENT-AT-${OLD} (${qf})" - continue - fi - QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${OLD}" "${oqf}" "${name}" > "${OUT}/base/${lf}" - - nqf=$(resolve_new_path "${oqf}") - if [ -z "${nqf}" ]; then - printf '%-56s %9s %9s %s\n' "${lf}" - - "REMOVED-IN-${NEW} (${qf})" - continue - fi - QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${NEW}" "${nqf}" "${name}" > "${OUT}/new/${lf}" - - s2e=$(diff "${OUT}/base/${lf}" "${LIBTCG}/${lf}" | grep -c '^[<>]' || true) - up=$(diff "${OUT}/base/${lf}" "${OUT}/new/${lf}" | grep -c '^[<>]' || true) - - status=ok - [ "${oqf}" != "${nqf}" ] && status="renamed ${oqf} -> ${nqf}" - - cp "${LIBTCG}/${lf}" "${OUT}/merged/${lf}" - if git merge-file -L libtcg -L "qemu ${OLD}" -L "qemu ${NEW}" \ - "${OUT}/merged/${lf}" "${OUT}/base/${lf}" "${OUT}/new/${lf}" > /dev/null 2>&1; then - clean=$((clean + 1)) - else - n=$(grep -c '^<<<<<<<' "${OUT}/merged/${lf}" || true) - status="CONFLICT (${n})" - conflicted=$((conflicted + 1)) - fi - - [ "${up}" = "0" ] && continue - printf '%-56s %9s %9s %s\n' "${lf}" "${s2e}" "${up}" "${status}" -done < "${HERE}/mapping.tsv" - -echo -echo "clean: ${clean} conflicted: ${conflicted} output: ${OUT}/merged" - -# Files that appeared upstream since the old tag may need to be imported by -# hand; there is no way to guess their libtcg name. -echo -echo "Added upstream between ${OLD} and ${NEW} (review for import):" -git -C "${QEMU_SRC}" diff --diff-filter=A --name-only "${OLD}" "${NEW}" -- \ - tcg/ include/tcg/ accel/tcg/ include/accel/ | sed 's/^/ /' - -if [ "${APPLY}" = "--apply" ]; then - echo - echo "Applying merged files into ${LIBTCG}" - (cd "${OUT}/merged" && find . -type f -print0) | - while IFS= read -r -d '' f; do - cp "${OUT}/merged/${f#./}" "${LIBTCG}/${f#./}" - done -fi diff --git a/libutils/scripts/upgrade/.gitignore b/libutils/scripts/upgrade/.gitignore deleted file mode 100644 index 89f9ac04a..000000000 --- a/libutils/scripts/upgrade/.gitignore +++ /dev/null @@ -1 +0,0 @@ -out/ diff --git a/libutils/scripts/upgrade/README.md b/libutils/scripts/upgrade/README.md deleted file mode 100644 index 2d51be717..000000000 --- a/libutils/scripts/upgrade/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# Upgrading libutils' vendored QEMU utilities to a new QEMU release - -`include/utils/` and `src/utils/` hold a subset of QEMU's `util/`, -`include/qemu/` and `host/include/` that was de-QEMU-ified (headers moved out -of `qemu/` into `utils/`) and reformatted with the S2E `.clang-format` style. -They used to live in libtcg under `tcg/utils/`; they moved here because they -depend on no target macro and libtcg is configured once per target, so keeping -them in libtcg compiled every object six times per build type. - -A plain `git cherry-pick` or `patch` against upstream never applies: every line -differs because of reformatting alone. The trick that makes upgrades tractable -is to *normalize the formatting first*. Running an upstream file through -`clang-format` with the S2E style reduces the difference against its libutils -counterpart to the genuine S2E delta. - -The upgrade is then an ordinary three-way merge: - - base = clang-formatted upstream file at the OLD tag - theirs = clang-formatted upstream file at the NEW tag - ours = the current libutils file - - git merge-file ours base theirs - -The rest of libutils (QAPI, QObject, the visitors, coroutines, fsigc++) is not -covered here; it diverged from QEMU long ago and is maintained by hand. - -## Files - -- `mapping.tsv` — libutils path -> upstream QEMU path, one pair per line, tab - separated. Only files that track upstream are listed; S2E-original files - (`utils/cache.h`, `utils/mutex.h`, `utils/spinlock.h`, `utils/rounding.h`) - are deliberately absent. -- `BASELINE` — the QEMU tag `mapping.tsv` paths and the current tree correspond - to. Update it (and any renamed paths in `mapping.tsv`) once an upgrade lands. -- `normalize.sh` — extract one file from a QEMU tag and clang-format it. -- `merge.sh` — normalize every mapped file at both tags and three-way merge. - -libtcg has its own copy of the same tooling under `libtcg/scripts/upgrade/`, -covering the TCG core, the x86_64 backend, the fpu and the three utility files -that stay behind (`utils/bswap.h`, `utils/cpu-float.h`, `utils/log.*`). Both -should be re-run when a QEMU tag is bumped. - -## Running an upgrade - - export QEMU_SRC=~/qemu - ./merge.sh v10.2.0 v11.1.0 # writes into ./out, reports conflicts - ./merge.sh v10.2.0 v11.1.0 --apply # same, but writes back into the tree - -`merge.sh` follows upstream renames automatically (via `git diff -M`) and -reports files that were deleted upstream or added since the old tag, both of -which need a human decision. - -Not every file tracks upstream closely. The ones below the "hand written" -marker in `mapping.tsv` (`utils/osdep.h`, `utils/cutils.*`, `utils/bitmap.h`) -are heavily reduced S2E-specific subsets rather than vendored copies, and are -still v8.1.0-era. They are listed for reference but want a manual look rather -than a mechanical merge. - -Two S2E deviations in the merged code are deliberate and must survive future -merges: - -- `host/generic/atomic128-cas.h` renames the `new` parameter to `_new`, since - these headers are included from C++. -- `utils/osdep.h` carries what upstream keeps in `include/qemu/compiler.h`. - -`utils/qtree.h`, `utils/int128.h` and `utils/host-utils.h` read -`HAVE_GLIB_WITH_SLICE_ALLOCATOR`, `CONFIG_INT128` and `HOST_BIG_ENDIAN`. -`libutils/src/CMakeLists.txt` defines them, and every component that includes -these headers has to define them the same way, or the struct layouts disagree -across translation units. - -## After merging - -Re-run `run-clang-format.sh` from the S2E source root so the tree stays -normalized for the next upgrade. diff --git a/libutils/scripts/upgrade/mapping.tsv b/libutils/scripts/upgrade/mapping.tsv index 456540095..7f28b9dd4 100644 --- a/libutils/scripts/upgrade/mapping.tsv +++ b/libutils/scripts/upgrade/mapping.tsv @@ -3,8 +3,12 @@ # Only the vendored QEMU utilities below include/utils/ and src/utils/ appear # here. The rest of libutils (QAPI, QObject, the visitors, coroutines, # fsigc++) is S2E-original or diverged far enough that it is not merged -# mechanically, and the S2E-original utilities (utils/cache.h, utils/mutex.h, -# utils/spinlock.h, utils/rounding.h) have no upstream counterpart at all. +# mechanically, and the S2E-original utilities (utils/cache.h, utils/cache.c, +# utils/config-host.h, utils/mutex.h, utils/spinlock.h, utils/rounding.h) have +# no upstream counterpart at all. The merge driver is scripts/upgrade/merge.sh +# at the S2E source root. +# +# upstream-dirs: util/ include/qemu/ host/include/ # # --- host support ------------------------------------------------------- include/utils/host/x86_64/cpuinfo.h host/include/x86_64/host/cpuinfo.h diff --git a/libutils/scripts/upgrade/merge.sh b/libutils/scripts/upgrade/merge.sh deleted file mode 100755 index 67bc61040..000000000 --- a/libutils/scripts/upgrade/merge.sh +++ /dev/null @@ -1,113 +0,0 @@ -#!/bin/bash -# -# Three-way merge every vendored QEMU utility in libutils from one QEMU tag to -# another. See README.md for the rationale. -# -# Usage: QEMU_SRC=~/qemu ./merge.sh [--apply] -# -set -e - -HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -LIBUTILS=$(cd "${HERE}/../.." && pwd) -QEMU_SRC=${QEMU_SRC:-${HOME}/qemu} -OUT=${OUT:-${HERE}/out} - -OLD=$1 -NEW=$2 -APPLY=$3 - -if [ -z "${OLD}" ] || [ -z "${NEW}" ]; then - echo "Usage: QEMU_SRC=/path/to/qemu $0 [--apply]" >&2 - exit 1 -fi - -rm -rf "${OUT}" -mkdir -p "${OUT}/base" "${OUT}/new" "${OUT}/merged" - -clean=0 -conflicted=0 - -# mapping.tsv records upstream paths as of the newest release libutils tracks, so -# a path may need resolving in either direction depending on which end of the -# upgrade we are looking at. -resolve_new_path() { - local path=$1 - if git -C "${QEMU_SRC}" cat-file -e "${NEW}:${path}" 2>/dev/null; then - echo "${path}" - return 0 - fi - git -C "${QEMU_SRC}" diff --diff-filter=R -M --name-status "${OLD}" "${NEW}" | - awk -v old="${path}" -F'\t' '$2 == old { print $3; exit }' -} - -resolve_old_path() { - local path=$1 - if git -C "${QEMU_SRC}" cat-file -e "${OLD}:${path}" 2>/dev/null; then - echo "${path}" - return 0 - fi - git -C "${QEMU_SRC}" diff --diff-filter=R -M --name-status "${OLD}" "${NEW}" | - awk -v new="${path}" -F'\t' '$3 == new { print $2; exit }' -} - -printf '%-56s %9s %9s %s\n' FILE S2E UPSTREAM STATUS - -while IFS=$'\t' read -r lf qf; do - case "${lf}" in '' | '#'*) continue ;; esac - - name=$(basename "${lf}") - mkdir -p "${OUT}/base/$(dirname "${lf}")" "${OUT}/new/$(dirname "${lf}")" \ - "${OUT}/merged/$(dirname "${lf}")" - - oqf=$(resolve_old_path "${qf}") - if [ -z "${oqf}" ]; then - printf '%-56s %9s %9s %s\n' "${lf}" - - "ABSENT-AT-${OLD} (${qf})" - continue - fi - QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${OLD}" "${oqf}" "${name}" > "${OUT}/base/${lf}" - - nqf=$(resolve_new_path "${oqf}") - if [ -z "${nqf}" ]; then - printf '%-56s %9s %9s %s\n' "${lf}" - - "REMOVED-IN-${NEW} (${qf})" - continue - fi - QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${NEW}" "${nqf}" "${name}" > "${OUT}/new/${lf}" - - s2e=$(diff "${OUT}/base/${lf}" "${LIBUTILS}/${lf}" | grep -c '^[<>]' || true) - up=$(diff "${OUT}/base/${lf}" "${OUT}/new/${lf}" | grep -c '^[<>]' || true) - - status=ok - [ "${oqf}" != "${nqf}" ] && status="renamed ${oqf} -> ${nqf}" - - cp "${LIBUTILS}/${lf}" "${OUT}/merged/${lf}" - if git merge-file -L libutils -L "qemu ${OLD}" -L "qemu ${NEW}" \ - "${OUT}/merged/${lf}" "${OUT}/base/${lf}" "${OUT}/new/${lf}" > /dev/null 2>&1; then - clean=$((clean + 1)) - else - n=$(grep -c '^<<<<<<<' "${OUT}/merged/${lf}" || true) - status="CONFLICT (${n})" - conflicted=$((conflicted + 1)) - fi - - [ "${up}" = "0" ] && continue - printf '%-56s %9s %9s %s\n' "${lf}" "${s2e}" "${up}" "${status}" -done < "${HERE}/mapping.tsv" - -echo -echo "clean: ${clean} conflicted: ${conflicted} output: ${OUT}/merged" - -# Files that appeared upstream since the old tag may need to be imported by -# hand; there is no way to guess their libutils name. -echo -echo "Added upstream between ${OLD} and ${NEW} (review for import):" -git -C "${QEMU_SRC}" diff --diff-filter=A --name-only "${OLD}" "${NEW}" -- \ - util/ include/qemu/ host/include/ | sed 's/^/ /' - -if [ "${APPLY}" = "--apply" ]; then - echo - echo "Applying merged files into ${LIBUTILS}" - (cd "${OUT}/merged" && find . -type f -print0) | - while IFS= read -r -d '' f; do - cp "${OUT}/merged/${f#./}" "${LIBUTILS}/${f#./}" - done -fi diff --git a/libutils/scripts/upgrade/normalize.sh b/libutils/scripts/upgrade/normalize.sh deleted file mode 100755 index e85f89454..000000000 --- a/libutils/scripts/upgrade/normalize.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash -# -# Extract one file from a QEMU tag and reformat it with the S2E style, so that -# it can be compared or merged against its libutils counterpart. -# -# Usage: QEMU_SRC=~/qemu ./normalize.sh v11.1.0 tcg/tcg.c [assumed-filename] -# -set -e - -QEMU_SRC=${QEMU_SRC:-${HOME}/qemu} -CLANG_FORMAT=${CLANG_FORMAT:-clang-format-19} -STYLE_FILE=${STYLE_FILE:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)/.clang-format} - -TAG=$1 -FILE=$2 -NAME=${3:-$(basename "${FILE}")} - -if [ -z "${TAG}" ] || [ -z "${FILE}" ]; then - echo "Usage: QEMU_SRC=/path/to/qemu $0 [assumed-filename]" >&2 - exit 1 -fi - -if [ ! -f "${STYLE_FILE}" ]; then - echo "Cannot find .clang-format at ${STYLE_FILE}" >&2 - exit 1 -fi - -git -C "${QEMU_SRC}" show "${TAG}:${FILE}" | - "${CLANG_FORMAT}" -style="file:${STYLE_FILE}" --assume-filename="${NAME}" diff --git a/libtcg/scripts/upgrade/.gitignore b/scripts/upgrade/.gitignore similarity index 100% rename from libtcg/scripts/upgrade/.gitignore rename to scripts/upgrade/.gitignore diff --git a/scripts/upgrade/README.md b/scripts/upgrade/README.md new file mode 100644 index 000000000..ddf85cd86 --- /dev/null +++ b/scripts/upgrade/README.md @@ -0,0 +1,119 @@ +# Upgrading vendored QEMU code to a new QEMU release + +Two S2E components carry code vendored from QEMU: + +- **libtcg** is a fork of QEMU's TCG, de-QEMU-ified (headers moved out of + `qemu/`, `exec/` and `accel/tcg/` into `tcg/utils/`, `tcg/exec/` and + `tcg/accel/`) and reformatted with the S2E `.clang-format` style. It also + carries `fpu/` (softfloat) and the three target-dependent utilities + `utils/bswap.h`, `utils/cpu-float.h` and `utils/log.*`. +- **libutils** carries QEMU's platform-independent utilities under + `include/utils/` and `src/utils/` (`util/`, `include/qemu/` and + `host/include/` upstream). They moved out of libtcg because they depend on no + target macro, and libtcg is configured once per target, so keeping them there + compiled every object six times per build type. + +A plain `git cherry-pick` or `patch` against upstream never applies to either: +every line differs because of reformatting alone. The trick that makes upgrades +tractable is to *normalize the formatting first*. Running an upstream file +through `clang-format` with the S2E style reduces the difference against its +S2E counterpart to the genuine S2E delta. For `libtcg/src/tcg.c` that is the +difference between a 6800-line diff and a 79-line one. + +The upgrade is then an ordinary three-way merge: + + base = clang-formatted upstream file at the OLD tag + theirs = clang-formatted upstream file at the NEW tag + ours = the current S2E file + + git merge-file ours base theirs + +## Files + +The driver lives here and is shared. Each component keeps its own data under +`/scripts/upgrade/`: + +- `normalize.sh` (here): extract one file from a QEMU tag and clang-format it. +- `merge.sh` (here): normalize every mapped file of one component at both tags + and three-way merge. Output goes to `scripts/upgrade/out//`. +- `/scripts/upgrade/mapping.tsv`: component path -> upstream QEMU + path, one pair per line, tab separated. Only files that track upstream are + listed; S2E-original files are deliberately absent. A `# upstream-dirs:` + header names the upstream directories the component draws from, which + `merge.sh` scans for files added since the old tag. +- `/scripts/upgrade/BASELINE`: the QEMU tag `mapping.tsv` paths and + the current tree correspond to. Update it (and any renamed paths in + `mapping.tsv`) once an upgrade lands. + +## Running an upgrade + + export QEMU_SRC=~/qemu + ./merge.sh libutils v10.2.0 v11.1.0 # dry run, reports conflicts + ./merge.sh libtcg v10.2.0 v11.1.0 + ./merge.sh libtcg v10.2.0 v11.1.0 --apply # same, but writes back into the tree + +A QEMU tag bump always covers both components: libtcg's merged code may call +utility APIs that only arrive with the libutils merge. Run libutils first. + +`merge.sh` resolves upstream renames with the rename limit lifted (`git diff +-M -l0`), and reports every row that changed upstream or was renamed. A pure +rename is reported even when the content did not change, because its +`mapping.tsv` row has to be updated. Files deleted upstream, files added since +the old tag, and mapping rows whose S2E file is missing are reported too; all +of those need a human decision. `--apply` writes conflicted files with their +conflict markers and lists them at the end, so the tree does not build until +they are resolved. + +## Hand-written subsets + +Not every file tracks upstream closely. The rows below the "hand written" +marker in each `mapping.tsv` are heavily reduced S2E-specific subsets rather +than vendored copies, and are still v8.1.0-era. They are listed for reference +but want a manual look rather than a mechanical merge: + +- libutils: `utils/memalign.h`, `utils/bitmap.h`, `utils/cutils.{h,c}`, + `utils/osdep.{h,c}`. +- libtcg: `utils/bswap.h`, `utils/log.{h,c}`. + +## Deviations that must survive every merge + +### libutils + +- `host/generic/atomic128-cas.h` renames the `new` parameter to `_new`, since + these headers are included from C++. +- `utils/bitops.h` wraps `#define BIT(nr)` in `#ifndef BIT`, because + `libcpu/include/cpu/kvm.h` also defines it. +- `utils/osdep.h` carries what upstream keeps in `include/qemu/compiler.h` + (`QEMU_FLATTEN`, `QEMU_ALWAYS_INLINE`, `typeof_strip_qual`, ...). When a merge + pulls in code that needs a new compiler macro, add it here. +- `utils/int128.h` and `utils/osdep.h` include ``, the + S2E-original header that defines `CONFIG_INT128`, `HOST_BIG_ENDIAN` and + `HAVE_GLIB_WITH_SLICE_ALLOCATOR` from compiler builtins. Upstream gets them + from meson through `qemu/osdep.h`; here the header is what keeps every + translation unit, in every component, on the same definitions. +- `src/utils/cpuinfo-i386.c` includes `` where upstream + includes `qemu/cpuid.h`, and `CONFIG_CPUID_H` stays undefined on purpose; see + `utils/config-host.h`. + +### libtcg + +- `float_status.float_rounding_mode` is a plain field rather than a bitfield. + S2E addresses the CPU state by (offset, size) so helpers running as bitcode + inside KLEE can read it back, which `offsetof`/`sizeof` on a bitfield cannot + express. +- `utils/cpu-float.h` holds the float/integer reinterpretation unions that + upstream keeps in `include/qemu/cpu-float.h`. Leaving them in `bswap.h`, as + older libtcg did, creates an include cycle through `softfloat-types.h` -> + `registerfields.h` -> `bitops.h` -> `host-utils.h` -> `bswap.h`. +- `accel/getpc.h` drops upstream's `#ifndef CONFIG_TCG #error` guard. +- `exec/helper-head.h.inc` keeps its `#ifdef TARGET_LONG_BITS` guard instead of + including `exec/target_long.h`. + +## After merging + +Re-run `run-clang-format.sh` from the S2E source root so the tree stays +normalized for the next upgrade, update each component's `BASELINE`, and +confirm normalization by merging the new tag onto itself: + + ./merge.sh libutils # must be 0 conflicts + ./merge.sh libtcg # must be 0 conflicts diff --git a/scripts/upgrade/merge.sh b/scripts/upgrade/merge.sh new file mode 100755 index 000000000..54086454a --- /dev/null +++ b/scripts/upgrade/merge.sh @@ -0,0 +1,161 @@ +#!/bin/bash +# +# Three-way merge every upstream-tracking file of one S2E component from one +# QEMU tag to another. See README.md for the rationale. +# +# Usage: QEMU_SRC=~/qemu ./merge.sh [--apply] +# +# is a directory under the S2E source root (libtcg, libutils, ...) +# that carries scripts/upgrade/{BASELINE,mapping.tsv}. +# +set -e + +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +ROOT=$(cd "${HERE}/../.." && pwd) +QEMU_SRC=${QEMU_SRC:-${HOME}/qemu} + +COMPONENT=$1 +OLD=$2 +NEW=$3 +APPLY=$4 + +if [ -z "${COMPONENT}" ] || [ -z "${OLD}" ] || [ -z "${NEW}" ]; then + echo "Usage: QEMU_SRC=/path/to/qemu $0 [--apply]" >&2 + exit 1 +fi + +COMP_DIR="${ROOT}/${COMPONENT}" +MAPPING="${COMP_DIR}/scripts/upgrade/mapping.tsv" +if [ ! -f "${MAPPING}" ]; then + echo "No mapping file at ${MAPPING}" >&2 + exit 1 +fi +OUT=${OUT:-${HERE}/out/${COMPONENT}} + +# The upstream directories this component's files come from, used to list files +# added between the two tags. Declared in mapping.tsv as "# upstream-dirs: a/ b/". +UPSTREAM_DIRS=$(sed -n 's/^# upstream-dirs:[[:space:]]*//p' "${MAPPING}") + +rm -rf "${OUT}" +mkdir -p "${OUT}/base" "${OUT}/new" "${OUT}/merged" + +# One rename table for the whole run. -l0 lifts git's rename limit, which +# otherwise silently skips inexact renames over a large range. +RENAMES="${OUT}/renames.tsv" +git -C "${QEMU_SRC}" diff --diff-filter=R -M -l0 --name-status "${OLD}" "${NEW}" > "${RENAMES}" + +# mapping.tsv records upstream paths as of the newest release the component +# tracks, so a path may need resolving in either direction depending on which +# end of the upgrade we are looking at. +resolve_new_path() { + local path=$1 + if git -C "${QEMU_SRC}" cat-file -e "${NEW}:${path}" 2>/dev/null; then + echo "${path}" + return 0 + fi + awk -v old="${path}" -F'\t' '$2 == old { print $3; exit }' "${RENAMES}" +} + +resolve_old_path() { + local path=$1 + if git -C "${QEMU_SRC}" cat-file -e "${OLD}:${path}" 2>/dev/null; then + echo "${path}" + return 0 + fi + awk -v new="${path}" -F'\t' '$3 == new { print $2; exit }' "${RENAMES}" +} + +clean=0 +conflicted=0 +conflicted_files=() + +printf '%-56s %9s %9s %s\n' FILE S2E UPSTREAM STATUS + +while IFS=$'\t' read -r lf qf; do + case "${lf}" in '' | '#'*) continue ;; esac + + if [ ! -f "${COMP_DIR}/${lf}" ]; then + printf '%-56s %9s %9s %s\n' "${lf}" - - "MISSING-IN-TREE" + continue + fi + + name=$(basename "${lf}") + mkdir -p "${OUT}/base/$(dirname "${lf}")" "${OUT}/new/$(dirname "${lf}")" \ + "${OUT}/merged/$(dirname "${lf}")" + + oqf=$(resolve_old_path "${qf}") + if [ -z "${oqf}" ]; then + printf '%-56s %9s %9s %s\n' "${lf}" - - "ABSENT-AT-${OLD} (${qf})" + continue + fi + QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${OLD}" "${oqf}" "${name}" > "${OUT}/base/${lf}" + + nqf=$(resolve_new_path "${oqf}") + if [ -z "${nqf}" ]; then + printf '%-56s %9s %9s %s\n' "${lf}" - - "REMOVED-IN-${NEW} (${qf})" + continue + fi + QEMU_SRC="${QEMU_SRC}" "${HERE}/normalize.sh" "${NEW}" "${nqf}" "${name}" > "${OUT}/new/${lf}" + + s2e=$(diff "${OUT}/base/${lf}" "${COMP_DIR}/${lf}" | grep -c '^[<>]' || true) + up=$(diff "${OUT}/base/${lf}" "${OUT}/new/${lf}" | grep -c '^[<>]' || true) + + status=ok + renamed= + if [ "${oqf}" != "${nqf}" ]; then + renamed="renamed ${oqf} -> ${nqf}" + status="${renamed}" + fi + + cp "${COMP_DIR}/${lf}" "${OUT}/merged/${lf}" + if git merge-file -L "${COMPONENT}" -L "qemu ${OLD}" -L "qemu ${NEW}" \ + "${OUT}/merged/${lf}" "${OUT}/base/${lf}" "${OUT}/new/${lf}" > /dev/null 2>&1; then + clean=$((clean + 1)) + else + n=$(grep -c '^<<<<<<<' "${OUT}/merged/${lf}" || true) + status="CONFLICT (${n})" + if [ -n "${renamed}" ]; then + status="${status}, ${renamed}" + fi + conflicted=$((conflicted + 1)) + conflicted_files+=("${lf}") + fi + + # Only rows with nothing to act on are hidden: unchanged upstream and not + # renamed. A pure rename still needs its mapping.tsv row updated. + if [ "${up}" = "0" ] && [ -z "${renamed}" ]; then + continue + fi + printf '%-56s %9s %9s %s\n' "${lf}" "${s2e}" "${up}" "${status}" +done < "${MAPPING}" + +echo +echo "clean: ${clean} conflicted: ${conflicted} output: ${OUT}/merged" + +# Files that appeared upstream since the old tag may need to be imported by +# hand; there is no way to guess their component-side name. Host-specific +# headers for other architectures are never candidates. +if [ -n "${UPSTREAM_DIRS}" ]; then + # shellcheck disable=SC2086 + added=$(git -C "${QEMU_SRC}" diff --diff-filter=A --name-only "${OLD}" "${NEW}" -- ${UPSTREAM_DIRS} | + awk '!/^host\/include\// || /^host\/include\/(generic|x86_64)\//') + if [ -n "${added}" ]; then + echo + echo "Added upstream between ${OLD} and ${NEW} under ${UPSTREAM_DIRS} (review for import):" + echo "${added}" | sed 's/^/ /' + fi +fi + +if [ "${APPLY}" = "--apply" ]; then + echo + echo "Applying merged files into ${COMP_DIR}" + (cd "${OUT}/merged" && find . -type f -print0) | + while IFS= read -r -d '' f; do + cp "${OUT}/merged/${f#./}" "${COMP_DIR}/${f#./}" + done + if [ "${conflicted}" -gt 0 ]; then + echo + echo "WARNING: ${conflicted} file(s) were written with conflict markers, resolve before building:" + printf ' %s\n' "${conflicted_files[@]}" + fi +fi diff --git a/libtcg/scripts/upgrade/normalize.sh b/scripts/upgrade/normalize.sh similarity index 88% rename from libtcg/scripts/upgrade/normalize.sh rename to scripts/upgrade/normalize.sh index ad51d5248..5c8f46a14 100755 --- a/libtcg/scripts/upgrade/normalize.sh +++ b/scripts/upgrade/normalize.sh @@ -1,7 +1,7 @@ #!/bin/bash # # Extract one file from a QEMU tag and reformat it with the S2E style, so that -# it can be compared or merged against its libtcg counterpart. +# it can be compared or merged against its S2E counterpart. # # Usage: QEMU_SRC=~/qemu ./normalize.sh v11.1.0 tcg/tcg.c [assumed-filename] # @@ -9,7 +9,7 @@ set -e QEMU_SRC=${QEMU_SRC:-${HOME}/qemu} CLANG_FORMAT=${CLANG_FORMAT:-clang-format-19} -STYLE_FILE=${STYLE_FILE:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)/.clang-format} +STYLE_FILE=${STYLE_FILE:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/.clang-format} TAG=$1 FILE=$2 From 6135a76fa76ee5ded6c609d8b845e30d4c63711b Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Fri, 21 Aug 2026 17:27:50 +0000 Subject: [PATCH 20/52] libutils: vendored the remaining hand-written utilities from QEMU v11.1.0 The rows below the "hand written" marker in mapping.tsv (memalign.h, bitmap.h, cutils.{h,c}, osdep.{h,c}) were v8.1.0-era subsets that had to be merged by hand on every upgrade, and cache.{h,c} and rounding.h were S2E-original stand-ins for upstream code. They are now upstream files: - compiler.h, memalign.h, ctype.h, madvise.h, mprotect.h, cacheflush.{h,c}, cacheinfo.h and hexdump.c are vendored verbatim, with the include paths, extern "C" guards and the includes each header needs to stand alone, since S2E has no qemu/osdep.h prelude. - cutils.h, osdep.h, cutils.c, osdep.c and oslib-posix.c are pruned copies: upstream text with the sections that need meson configuration, os-posix.h, the Error API, error_report() or sockets deleted. cutils.h drops the prototypes (qemu_init_exec_dir, get_relocated_path, parse_debug_env) whose bodies cutils.c prunes, so every declaration it keeps has a definition. The kept sections are verbatim, so merge.sh handles them like any other row. - cache.{h,c} is replaced by cacheflush.c (qemu_icache_linesize and friends, initialized from a constructor), rounding.h by the QEMU_ALIGN_* and ROUND_* macros in osdep.h, and bitmap.h is dropped: nothing used it and upstream bitmap.c needs bswap.h, which libtcg still owns. - src/q/cutils.{c,h}, a renamed copy of the same upstream file, is gone; the QAPI code calls qemu_strto*() directly. config-host.h gains CONFIG_MADVISE and CONFIG_POSIX_MEMALIGN and loses HOST_BIG_ENDIAN, which compiler.h defines as upstream does. The remaining deviations are small and documented in scripts/upgrade/README.md: compiler.h spells typeof as __typeof__ for C++, cutils.h spells restrict as __restrict and casts the buffer_is_zero() argument so it compiles as C++ behind its extern "C" guard, osdep.h keeps the plain MIN/MAX/ARRAY_SIZE for C++ and drops the #error on NDEBUG (libtcg and libcpu build with it in release), and osdep.c reports mprotect failures with fprintf. The consumers follow upstream naming: region.c uses qemu_dcache_linesize, QEMU_MADV_HUGEPAGE and QEMU_ALIGN_DOWN; tcg.c uses qemu_icache_linesize and ; tcg.h uses QEMU_ALIGN_UP; translate-all.c no longer calls init_cache_info(); exec-ram.c uses qemu_strtosz_MiB() and rejects sizes above INT64_MAX, which its int64_t return would otherwise turn into the default. libcpu's libcpu-compiler.h had the same COMPILER_H guard as upstream compiler.h and types.h redefined HOST_LONG_BITS; libs2e.cpp includes before it undefines __REDIRECT_NTH, since osdep.h now pulls in glib; coroutine.h and coroutine-ucontext.c drop their private coroutine_fn and container_of. mutex.h and spinlock.h stay S2E-original: qemu/thread.h drags in qsp, notify, the generated trace.h and main-loop.h, far more than the two wrappers replace. Co-Authored-By: Claude Fable 5 Signed-off-by: Vitaly Chipounov --- .claude/skills/upgrade-libtcg/SKILL.md | 27 +- libcpu/include/cpu/types.h | 10 +- libcpu/include/libcpu-compiler.h | 6 +- libcpu/src/exec-ram.c | 10 +- libcpu/src/translate-all.c | 6 - libs2e/src/libs2e.cpp | 4 + libtcg/include/tcg/tcg.h | 2 +- libtcg/src/region.c | 18 +- libtcg/src/tcg-op-gvec.c | 1 - libtcg/src/tcg.c | 7 +- libutils/include/coroutine.h | 18 +- libutils/include/utils/bitmap.h | 41 - libutils/include/utils/bitops.h | 2 +- libutils/include/utils/cache.h | 38 - libutils/include/utils/cacheflush.h | 51 + libutils/include/utils/cacheinfo.h | 29 + libutils/include/utils/compiler.h | 390 ++++++++ libutils/include/utils/config-host.h | 9 +- libutils/include/utils/ctype.h | 29 + libutils/include/utils/cutils.h | 288 +++++- libutils/include/utils/int128.h | 1 + libutils/include/utils/madvise.h | 105 ++ libutils/include/utils/memalign.h | 77 +- libutils/include/utils/mprotect.h | 24 + libutils/include/utils/osdep.h | 557 +++++++---- libutils/include/utils/rounding.h | 61 -- libutils/scripts/upgrade/mapping.tsv | 26 +- libutils/src/CMakeLists.txt | 5 +- libutils/src/coroutine/coroutine-ucontext.c | 4 - libutils/src/q/cutils.c | 543 ----------- libutils/src/q/qapi/qapi-forward-visitor.c | 2 +- libutils/src/q/qapi/qobject-input-visitor.c | 10 +- libutils/src/q/qobject/json-parser.c | 10 +- libutils/src/utils/cache.c | 48 - libutils/src/utils/cacheflush.c | 351 +++++++ libutils/src/utils/cutils.c | 923 ++++++++++++++++-- libutils/src/utils/hexdump.c | 112 +++ libutils/src/utils/memalign.c | 3 +- libutils/src/utils/osdep.c | 36 +- .../src/{q/cutils.h => utils/oslib-posix.c} | 36 +- scripts/upgrade/README.md | 59 +- 41 files changed, 2789 insertions(+), 1190 deletions(-) delete mode 100644 libutils/include/utils/bitmap.h delete mode 100644 libutils/include/utils/cache.h create mode 100644 libutils/include/utils/cacheflush.h create mode 100644 libutils/include/utils/cacheinfo.h create mode 100644 libutils/include/utils/compiler.h create mode 100644 libutils/include/utils/ctype.h create mode 100644 libutils/include/utils/madvise.h create mode 100644 libutils/include/utils/mprotect.h delete mode 100644 libutils/include/utils/rounding.h delete mode 100644 libutils/src/q/cutils.c delete mode 100644 libutils/src/utils/cache.c create mode 100644 libutils/src/utils/cacheflush.c create mode 100644 libutils/src/utils/hexdump.c rename libutils/src/{q/cutils.h => utils/oslib-posix.c} (55%) diff --git a/.claude/skills/upgrade-libtcg/SKILL.md b/.claude/skills/upgrade-libtcg/SKILL.md index 4ee51feed..e525edcd2 100644 --- a/.claude/skills/upgrade-libtcg/SKILL.md +++ b/.claude/skills/upgrade-libtcg/SKILL.md @@ -43,10 +43,12 @@ include block or where S2E's `extern "C"` guard meets appended upstream code. git -C ~/qemu log --oneline .. -- tcg/ include/tcg/ util/ include/qemu/ host/include/ **Neither component is uniformly at one version.** The TCG core, `fpu/` and the -vendored utilities track `BASELINE`, but the hand-written subsets flagged below -the "hand written" marker in each `mapping.tsv` (libutils: `osdep.*`, -`cutils.*`, `bitmap.h`, `memalign.h`; libtcg: `log.*`, `bswap.h`) are still -v8.1.0-era and are not vendored. Before assuming a file's baseline, check it: +vendored utilities track `BASELINE`, but libtcg's hand-written subsets +(`log.*`, `bswap.h`, flagged below the "hand written" marker in its +`mapping.tsv`) are still v8.1.0-era and are not vendored. libutils has no +hand-written subsets left, only pruned copies (`cutils.h`, `osdep.h`, +`cutils.c`, `osdep.c`, `oslib-posix.c`: upstream text with sections deleted), +which merge like any other row. Before assuming a file's baseline, check it: format the file at several candidate tags and pick the smallest diff. A file that is stale relative to its neighbors is a bug waiting to happen: the 11.1 upgrade found `tcg-gvec-desc.h` stranded at an old descriptor encoding while @@ -90,7 +92,7 @@ type, libutils once). Add the new row to that component's `mapping.tsv`. being included first everywhere; S2E has no such prelude, and the S2E clang-format sets `SortIncludes: true`, so it will reorder an include block and break any header that depends on its position. Host configuration macros -(`CONFIG_INT128`, `HOST_BIG_ENDIAN`, `HAVE_GLIB_WITH_SLICE_ALLOCATOR`) come from +(`CONFIG_INT128`, `CONFIG_MADVISE` and the rest) come from `utils/config-host.h`, pulled in by `utils/int128.h` and `utils/osdep.h`; never add `-D` copies to a CMakeLists. @@ -124,7 +126,8 @@ relocate: check it is anchored to the right `tcg_out_ld`, not merely present - `tcg_target_force_tb_exit` - `tcg_prologue_init(TCGContext *s)` taking the context explicitly -- `mutex_t` / `spin_*` / `g_*cache_linesize` in `region.c` +- `mutex_t` / `spin_*` in `region.c` and `tb.h` (libutils keeps its own + `mutex.h`/`spinlock.h` instead of `qemu/thread.h`) ### 6. Re-normalize and record @@ -152,10 +155,14 @@ libutils: These headers are included from C++, where `new` is a keyword. - **`utils/bitops.h`** wraps `#define BIT(nr)` in `#ifndef BIT`, because `libcpu/include/cpu/kvm.h` also defines it. -- **`utils/osdep.h`** carries what upstream keeps in `include/qemu/compiler.h` - (`QEMU_FLATTEN`, `QEMU_ALWAYS_INLINE`, `typeof_strip_qual`, ...). When a merge - pulls in code that needs a new compiler macro, add it here. -- **`utils/int128.h` and `utils/osdep.h`** include ``. +- **`utils/compiler.h`** is vendored; it adds ``/`` and + `#define typeof __typeof__` for C++. **`utils/osdep.h`** is a pruned copy of + upstream's: it redefines `MIN`/`MAX`/`ARRAY_SIZE` for C++ and drops the + `NDEBUG` `#error`. +- **`utils/int128.h` and `utils/osdep.h`** include ``; + `int128.h` also includes ``. +- **`src/utils/osdep.c`** uses `fprintf(stderr)` where upstream calls + `error_report()`. - **`src/utils/cpuinfo-i386.c`** includes ``; `CONFIG_CPUID_H` stays undefined on purpose (see `utils/config-host.h`: the TCG op set must not grow past what `tcg-llvm.cpp` translates). diff --git a/libcpu/include/cpu/types.h b/libcpu/include/cpu/types.h index 67c0e06e5..c148294e0 100644 --- a/libcpu/include/cpu/types.h +++ b/libcpu/include/cpu/types.h @@ -23,6 +23,7 @@ #include #include +#include #ifdef __cplusplus extern "C" { @@ -34,15 +35,6 @@ extern "C" { #define TARGET_LONG_BITS 32 #endif -/* HOST_LONG_BITS is the size of a native pointer in bits. */ -#if UINTPTR_MAX == UINT32_MAX -#define HOST_LONG_BITS 32 -#elif UINTPTR_MAX == UINT64_MAX -#define HOST_LONG_BITS 64 -#else -#error Unknown pointer size -#endif - #define TARGET_LONG_SIZE (TARGET_LONG_BITS / 8) typedef int16_t target_short __attribute__((aligned(TARGET_SHORT_ALIGNMENT))); diff --git a/libcpu/include/libcpu-compiler.h b/libcpu/include/libcpu-compiler.h index 986ebb861..ca8edd018 100644 --- a/libcpu/include/libcpu-compiler.h +++ b/libcpu/include/libcpu-compiler.h @@ -1,7 +1,7 @@ /* public domain */ -#ifndef COMPILER_H -#define COMPILER_H +#ifndef LIBCPU_COMPILER_H +#define LIBCPU_COMPILER_H #include @@ -54,4 +54,4 @@ extern "C" { } #endif -#endif /* COMPILER_H */ +#endif /* LIBCPU_COMPILER_H */ diff --git a/libcpu/src/exec-ram.c b/libcpu/src/exec-ram.c index 11ab91144..71ab82316 100644 --- a/libcpu/src/exec-ram.c +++ b/libcpu/src/exec-ram.c @@ -17,6 +17,7 @@ /// License along with this library; if not, see . #include +#include #include #include @@ -44,16 +45,15 @@ static int64_t parse_ram_size(int argc, char **argv) { } if (found == 1) { - int64_t value; - char *end_str; + uint64_t value; + const char *end_str; - value = strtosz(argv[id], &end_str); - if (value < 0 || *end_str) { + if (qemu_strtosz_MiB(argv[id], &end_str, &value) < 0 || *end_str) { fprintf(stderr, "libcpu: invalid ram size: %s\n", optarg); goto end; } - if (value != (uint64_t) (ram_addr_t) value) { + if (value > INT64_MAX || value != (uint64_t) (ram_addr_t) value) { fprintf(stderr, "libcpu: ram size too large\n"); goto end; } diff --git a/libcpu/src/translate-all.c b/libcpu/src/translate-all.c index 19b4a8324..b44449d44 100644 --- a/libcpu/src/translate-all.c +++ b/libcpu/src/translate-all.c @@ -33,7 +33,6 @@ #define NO_CPU_IO_DEFS #include #include -#include #include #include "cpu.h" #include "timer.h" @@ -124,11 +123,6 @@ static void cpu_gen_init(TCGContext *ctx) { (in bytes) allocated to the translation buffer. Zero means default size. */ void tcg_exec_init(unsigned long tb_size) { - if (init_cache_info() < 0) { - fprintf(stderr, "Could not init cache size"); - exit(-1); - } - tcg_init(MIN_CODE_GEN_BUFFER_SIZE, 0, 1); cpu_gen_init(&tcg_init_ctx); diff --git a/libs2e/src/libs2e.cpp b/libs2e/src/libs2e.cpp index 8c0c4d523..c5f290161 100644 --- a/libs2e/src/libs2e.cpp +++ b/libs2e/src/libs2e.cpp @@ -32,6 +32,10 @@ #include #include +// glib pulls in dirent.h later, and that header has no fallback when +// __REDIRECT_NTH is undefined, so include it before undefining the macro. +#include + #undef __REDIRECT_NTH #include #include diff --git a/libtcg/include/tcg/tcg.h b/libtcg/include/tcg/tcg.h index 29a044e82..1fadb1915 100644 --- a/libtcg/include/tcg/tcg.h +++ b/libtcg/include/tcg/tcg.h @@ -801,7 +801,7 @@ static inline void *tcg_malloc(int size) { uintptr_t ptr, ptr_end; /* ??? This is a weak placeholder for minimum malloc alignment. */ - size = ALIGN_UP(size, 8); + size = QEMU_ALIGN_UP(size, 8); ptr = s->pool_cur; ptr_end = ptr + size; diff --git a/libtcg/src/region.c b/libtcg/src/region.c index 60552e64e..f970c6805 100644 --- a/libtcg/src/region.c +++ b/libtcg/src/region.c @@ -36,9 +36,11 @@ #include #include -#include +#include #include +#include #include +#include #include #include #include @@ -190,8 +192,8 @@ static void tb_destroy(gpointer value) { static void tcg_region_trees_init(void) { size_t i; - tree_size = ROUND_UP(sizeof(struct tcg_region_tree), g_dcache_linesize); - region_trees = qemu_memalign(g_dcache_linesize, region.n * tree_size); + tree_size = ROUND_UP(sizeof(struct tcg_region_tree), qemu_dcache_linesize); + region_trees = qemu_memalign(qemu_dcache_linesize, region.n * tree_size); for (i = 0; i < region.n; i++) { struct tcg_region_tree *rt = region_trees + i * tree_size; @@ -498,7 +500,7 @@ static int alloc_code_gen_buffer(size_t tb_size, int splitwx, Error **errp) { /* Honor a command-line option limiting the size of the buffer. */ if (size > tb_size) { - size = ALIGN_DOWN(tb_size, qemu_real_host_page_size()); + size = QEMU_ALIGN_DOWN(tb_size, qemu_real_host_page_size()); } region.start_aligned = buf; @@ -707,7 +709,7 @@ void tcg_region_init(size_t tb_size, int splitwx, unsigned max_threads) { if (phys_mem == 0) { tb_size = DEFAULT_CODE_GEN_BUFFER_SIZE; } else { - tb_size = ALIGN_DOWN(phys_mem / 8, page_size); + tb_size = QEMU_ALIGN_DOWN(phys_mem / 8, page_size); tb_size = MIN(DEFAULT_CODE_GEN_BUFFER_SIZE, tb_size); } } @@ -722,9 +724,9 @@ void tcg_region_init(size_t tb_size, int splitwx, unsigned max_threads) { assert(have_prot >= 0); /* Request large pages for the buffer and the splitwx. */ - qemu_madvise(region.start_aligned, region.total_size, MADV_HUGEPAGE); + qemu_madvise(region.start_aligned, region.total_size, QEMU_MADV_HUGEPAGE); if (tcg_splitwx_diff) { - qemu_madvise(region.start_aligned + tcg_splitwx_diff, region.total_size, MADV_HUGEPAGE); + qemu_madvise(region.start_aligned + tcg_splitwx_diff, region.total_size, QEMU_MADV_HUGEPAGE); } /* @@ -734,7 +736,7 @@ void tcg_region_init(size_t tb_size, int splitwx, unsigned max_threads) { */ region.n = tcg_n_regions(tb_size, max_threads); region_size = tb_size / region.n; - region_size = ALIGN_DOWN(region_size, page_size); + region_size = QEMU_ALIGN_DOWN(region_size, page_size); /* A region must have at least 2 pages; one code, one guard */ g_assert(region_size >= 2 * page_size); diff --git a/libtcg/src/tcg-op-gvec.c b/libtcg/src/tcg-op-gvec.c index 836b3be98..950c21658 100644 --- a/libtcg/src/tcg-op-gvec.c +++ b/libtcg/src/tcg-op-gvec.c @@ -19,7 +19,6 @@ // Order of includes is important // clang-format off -#include #include #include #include diff --git a/libtcg/src/tcg.c b/libtcg/src/tcg.c index 0da6257b9..1174a4846 100644 --- a/libtcg/src/tcg.c +++ b/libtcg/src/tcg.c @@ -41,7 +41,8 @@ #include #include -#include +#include +#include #include #include #include @@ -719,7 +720,7 @@ static int tcg_out_pool_finalize(TCGContext *s) { } /* - * ??? Round up to g_icache_linesize, but then do not round + * ??? Round up to qemu_icache_linesize, but then do not round * again when allocating the next TranslationBlock structure. */ a = (void *) ROUND_UP((uintptr_t) s->code_ptr, sizeof(tcg_target_ulong) * p->nlong); @@ -1686,7 +1687,7 @@ void tcg_init(size_t tb_size, int splitwx, unsigned max_threads) { * sure that TBs and code are on different cache lines. */ TranslationBlock *tcg_tb_alloc(TCGContext *s) { - uintptr_t align = g_icache_linesize; + uintptr_t align = qemu_icache_linesize; TranslationBlock *tb; void *next; diff --git a/libutils/include/coroutine.h b/libutils/include/coroutine.h index ae86aae1d..b4e31af6b 100644 --- a/libutils/include/coroutine.h +++ b/libutils/include/coroutine.h @@ -20,6 +20,8 @@ #include #include +#include + #ifdef __cplusplus extern "C" { #endif @@ -34,22 +36,6 @@ extern "C" { * These functions are re-entrant and may be used outside the global mutex. */ -/** - * Mark a function that executes in coroutine context - * - * Functions that execute in coroutine context cannot be called directly from - * normal functions. In the future it would be nice to enable compiler or - * static checker support for catching such errors. This annotation might make - * it possible and in the meantime it serves as documentation. - * - * For example: - * - * static void coroutine_fn foo(void) { - * .... - * } - */ -#define coroutine_fn - typedef struct Coroutine Coroutine; /** diff --git a/libutils/include/utils/bitmap.h b/libutils/include/utils/bitmap.h deleted file mode 100644 index 32b49577b..000000000 --- a/libutils/include/utils/bitmap.h +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2019 Cyberhaven -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef TCG_BITMAP_H - -#define TCG_BITMAP_H - -#include -#include "bitops.h" - -#ifdef __cplusplus -extern "C" { -#endif - -static inline void bitmap_zero(unsigned long *bitmap, long bits) { - long length = BITS_TO_LONGS(bits) * sizeof(unsigned long); - memset(bitmap, 0, length); -} - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libutils/include/utils/bitops.h b/libutils/include/utils/bitops.h index decb18d5e..dbc21b51c 100644 --- a/libutils/include/utils/bitops.h +++ b/libutils/include/utils/bitops.h @@ -17,7 +17,7 @@ #include "atomic.h" #include "host-utils.h" -#include "rounding.h" +#include "osdep.h" #ifdef __cplusplus extern "C" { diff --git a/libutils/include/utils/cache.h b/libutils/include/utils/cache.h deleted file mode 100644 index 68a0163cb..000000000 --- a/libutils/include/utils/cache.h +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2023 Vitaly Chipounov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef TCG_CACHE_H - -#define TCG_CACHE_H - -#ifdef __cplusplus -extern "C" { -#endif - -extern int g_icache_linesize; -extern int g_dcache_linesize; - -int init_cache_info(); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libutils/include/utils/cacheflush.h b/libutils/include/utils/cacheflush.h new file mode 100644 index 000000000..7aa595aad --- /dev/null +++ b/libutils/include/utils/cacheflush.h @@ -0,0 +1,51 @@ +/* + * Flush the host cpu caches. + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#ifndef QEMU_CACHEFLUSH_H +#define QEMU_CACHEFLUSH_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * flush_idcache_range: + * @rx: instruction address + * @rw: data address + * @len: length to flush + * + * Flush @len bytes of the data cache at @rw and the icache at @rx + * to bring them in sync. The two addresses may be different virtual + * mappings of the same physical page(s). + */ + +#if defined(__x86_64__) || defined(__s390x__) + +static inline void flush_idcache_range(uintptr_t rx, uintptr_t rw, size_t len) { + /* icache is coherent and does not require flushing. */ +} + +#elif defined(EMSCRIPTEN) + +static inline void flush_idcache_range(uintptr_t rx, uintptr_t rw, size_t len) { + /* Wasm doesn't have executable region of memory. */ +} + +#else + +void flush_idcache_range(uintptr_t rx, uintptr_t rw, size_t len); + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* QEMU_CACHEFLUSH_H */ diff --git a/libutils/include/utils/cacheinfo.h b/libutils/include/utils/cacheinfo.h new file mode 100644 index 000000000..8c8fca530 --- /dev/null +++ b/libutils/include/utils/cacheinfo.h @@ -0,0 +1,29 @@ +/* + * QEMU host cacheinfo information + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ +#ifndef QEMU_CACHEINFO_H +#define QEMU_CACHEINFO_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * These variables represent our best guess at the host icache and + * dcache sizes, expressed both as the size in bytes and as the + * base-2 log of the size in bytes. They are initialized at startup + * (via an attribute 'constructor' function). + */ +extern int qemu_icache_linesize; +extern int qemu_icache_linesize_log; +extern int qemu_dcache_linesize; +extern int qemu_dcache_linesize_log; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libutils/include/utils/compiler.h b/libutils/include/utils/compiler.h new file mode 100644 index 000000000..c87a8cf1f --- /dev/null +++ b/libutils/include/utils/compiler.h @@ -0,0 +1,390 @@ +/* compiler.h: macros to abstract away compiler specifics + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#ifndef COMPILER_H +#define COMPILER_H + +#include +#include + +#ifdef __cplusplus +/* The macros below use GNU C typeof; strict C++ only spells it __typeof__. */ +#define typeof __typeof__ +#endif + +#define HOST_BIG_ENDIAN (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) + +/* HOST_LONG_BITS is the size of a native pointer in bits. */ +#define HOST_LONG_BITS (__SIZEOF_POINTER__ * 8) + +#if defined __clang_analyzer__ || defined __COVERITY__ +#define QEMU_STATIC_ANALYSIS 1 +#endif + +#ifdef __cplusplus +#define QEMU_EXTERN_C extern "C" +#else +#define QEMU_EXTERN_C extern +#endif + +#define QEMU_PACKED __attribute__((packed)) +#define QEMU_ALIGNED(X) __attribute__((aligned(X))) + +#ifndef glue +#define xglue(x, y) x##y +#define glue(x, y) xglue(x, y) +#define stringify(s) tostring(s) +#define tostring(s) #s +#endif + +/* Expands into an identifier stemN, where N is another number each time */ +#define MAKE_IDENTIFIER(stem) glue(stem, __COUNTER__) + +#ifndef likely +#define likely(x) __builtin_expect(!!(x), 1) +#define unlikely(x) __builtin_expect(!!(x), 0) +#endif + +#ifndef container_of +#define container_of(ptr, type, member) \ + ({ \ + const typeof(((type *) 0)->member) *__mptr = (ptr); \ + (type *) ((char *) __mptr - offsetof(type, member)); \ + }) +#endif + +#define sizeof_field(type, field) sizeof(((type *) 0)->field) + +/* + * Calculate the number of bytes up to and including the given 'field' of + * 'container'. + */ +#define endof(container, field) (offsetof(container, field) + sizeof_field(container, field)) + +/* Convert from a base type to a parent type, with compile time checking. */ +#define DO_UPCAST(type, field, dev) \ + (__extension__({ \ + char __attribute__((unused)) offset_must_be_zero[-offsetof(type, field)]; \ + container_of(dev, type, field); \ + })) + +#define typeof_field(type, field) typeof(((type *) 0)->field) +#define type_check(t1, t2) ((t1 *) 0 - (t2 *) 0) + +#define QEMU_BUILD_BUG_ON_STRUCT(x) \ + struct { \ + int : (x) ? -1 : 1; \ + } + +#define QEMU_BUILD_BUG_MSG(x, msg) _Static_assert(!(x), msg) + +#define QEMU_BUILD_BUG_ON(x) QEMU_BUILD_BUG_MSG(x, "not expecting: " #x) + +#define QEMU_BUILD_BUG_ON_ZERO(x) (sizeof(QEMU_BUILD_BUG_ON_STRUCT(x)) - sizeof(QEMU_BUILD_BUG_ON_STRUCT(x))) + +#if !defined(__clang__) && defined(_WIN32) +/* + * Map __printf__ to __gnu_printf__ because we want standard format strings even + * when MinGW or GLib include files use __printf__. + */ +#define __printf__ __gnu_printf__ +#endif + +#ifndef __has_warning +#define __has_warning(x) 0 /* compatibility with non-clang compilers */ +#endif + +#ifndef __has_feature +#define __has_feature(x) 0 /* compatibility with non-clang compilers */ +#endif + +#ifndef __has_builtin +#define __has_builtin(x) 0 /* compatibility with non-clang compilers */ +#endif + +#if __has_builtin(__builtin_assume_aligned) || !defined(__clang__) +#define HAS_ASSUME_ALIGNED +#endif + +#ifndef __has_attribute +#define __has_attribute(x) 0 /* compatibility with older GCC */ +#endif + +#if defined(__SANITIZE_ADDRESS__) || __has_feature(address_sanitizer) +#define QEMU_SANITIZE_ADDRESS 1 +#endif + +#if defined(__SANITIZE_THREAD__) || __has_feature(thread_sanitizer) +#define QEMU_SANITIZE_THREAD 1 +#endif + +/* + * GCC doesn't provide __has_attribute() until GCC 5, but we know all the GCC + * versions we support have the "flatten" attribute. Clang may not have the + * "flatten" attribute but always has __has_attribute() to check for it. + */ +#if __has_attribute(flatten) || !defined(__clang__) +#define QEMU_FLATTEN __attribute__((flatten)) +#else +#define QEMU_FLATTEN +#endif + +/* + * If __attribute__((error)) is present, use it to produce an error at + * compile time. Otherwise, one must wait for the linker to diagnose + * the missing symbol. + */ +#if __has_attribute(error) +#define QEMU_ERROR(X) __attribute__((error(X))) +#else +#define QEMU_ERROR(X) +#endif + +/* + * The nonstring variable attribute specifies that an object or member + * declaration with type array of char or pointer to char is intended + * to store character arrays that do not necessarily contain a terminating + * NUL character. This is useful in detecting uses of such arrays or pointers + * with functions that expect NUL-terminated strings, and to avoid warnings + * when such an array or pointer is used as an argument to a bounded string + * manipulation function such as strncpy. + */ +#if __has_attribute(nonstring) +#define QEMU_NONSTRING __attribute__((nonstring)) +#else +#define QEMU_NONSTRING +#endif + +/* + * Forced inlining may be desired to encourage constant propagation + * of function parameters. However, it can also make debugging harder, + * so disable it for a non-optimizing build. + */ +#if defined(__OPTIMIZE__) +#define QEMU_ALWAYS_INLINE __attribute__((always_inline)) +#else +#define QEMU_ALWAYS_INLINE +#endif + +/** + * In most cases, normal "fallthrough" comments are good enough for + * switch-case statements, but sometimes the compiler has problems + * with those. In that case you can use QEMU_FALLTHROUGH instead. + */ +#if __has_attribute(fallthrough) +#define QEMU_FALLTHROUGH __attribute__((fallthrough)) +#else +#define QEMU_FALLTHROUGH \ + do { \ + } while (0) /* fallthrough */ +#endif + +#ifdef CONFIG_CFI +/* + * If CFI is enabled, use an attribute to disable cfi-icall on the following + * function + */ +#define QEMU_DISABLE_CFI __attribute__((no_sanitize("cfi-icall"))) +#else +/* If CFI is not enabled, use an empty define to not change the behavior */ +#define QEMU_DISABLE_CFI +#endif + +#if __has_attribute(annotate) +#define QEMU_ANNOTATE(x) __attribute__((annotate(x))) +#else +#define QEMU_ANNOTATE(x) +#endif + +#if __has_attribute(used) +#define QEMU_USED __attribute__((used)) +#else +#define QEMU_USED +#endif + +/* + * A priority for __attribute__((constructor(...))) that + * will run earlier than the default constructors. Must + * only be used for functions that have no dependency + * on global initialization of other QEMU subsystems. + */ +#define QEMU_CONSTRUCTOR_EARLY 101 + +/* + * Disable -ftrivial-auto-var-init on a local variable. + * + * Use this in cases where there a method in the device I/O path (or other + * important hot paths), that has large variables on the stack. A rule of + * thumb is that "large" means a method with 4kb data in the local stack + * frame. Any variables which are KB in size, should be annotated with this + * attribute, to pre-emptively eliminate any potential overhead from the + * compiler's implicit zero'ing of memory. + * + * Given that this turns off a security hardening feature, when using this + * to flag variables, it is important that the code is double-checked to + * ensure there is no possible use of uninitialized data in the method. + */ +#if __has_attribute(uninitialized) +#define QEMU_UNINITIALIZED __attribute__((uninitialized)) +#else +#define QEMU_UNINITIALIZED +#endif + +/* + * http://clang.llvm.org/docs/ThreadSafetyAnalysis.html + * + * TSA is available since clang 3.6-ish. + */ +#ifdef __clang__ +#define TSA(x) __attribute__((x)) +#else +#define TSA(x) /* No TSA, make TSA attributes no-ops. */ +#endif + +/* + * TSA_CAPABILITY() is used to annotate typedefs: + * + * typedef pthread_mutex_t TSA_CAPABILITY("mutex") tsa_mutex; + */ +#define TSA_CAPABILITY(x) TSA(capability(x)) + +/* + * TSA_GUARDED_BY() is used to annotate global variables, + * the data is guarded: + * + * Foo foo TSA_GUARDED_BY(mutex); + */ +#define TSA_GUARDED_BY(x) TSA(guarded_by(x)) + +/* + * TSA_PT_GUARDED_BY() is used to annotate global pointers, the data + * behind the pointer is guarded. + * + * Foo* ptr TSA_PT_GUARDED_BY(mutex); + */ +#define TSA_PT_GUARDED_BY(x) TSA(pt_guarded_by(x)) + +/* + * The TSA_REQUIRES() is used to annotate functions: the caller of the + * function MUST hold the resource, the function will NOT release it. + * + * More than one mutex may be specified, comma-separated. + * + * void Foo(void) TSA_REQUIRES(mutex); + */ +#define TSA_REQUIRES(...) TSA(requires_capability(__VA_ARGS__)) +#define TSA_REQUIRES_SHARED(...) TSA(requires_shared_capability(__VA_ARGS__)) + +/* + * TSA_EXCLUDES() is used to annotate functions: the caller of the + * function MUST NOT hold resource, the function first acquires the + * resource, and then releases it. + * + * More than one mutex may be specified, comma-separated. + * + * void Foo(void) TSA_EXCLUDES(mutex); + */ +#define TSA_EXCLUDES(...) TSA(locks_excluded(__VA_ARGS__)) + +/* + * TSA_ACQUIRE() is used to annotate functions: the caller of the + * function MUST NOT hold the resource, the function will acquire the + * resource, but NOT release it. + * + * More than one mutex may be specified, comma-separated. + * + * void Foo(void) TSA_ACQUIRE(mutex); + */ +#define TSA_ACQUIRE(...) TSA(acquire_capability(__VA_ARGS__)) +#define TSA_ACQUIRE_SHARED(...) TSA(acquire_shared_capability(__VA_ARGS__)) + +/* + * TSA_RELEASE() is used to annotate functions: the caller of the + * function MUST hold the resource, but the function will then release it. + * + * More than one mutex may be specified, comma-separated. + * + * void Foo(void) TSA_RELEASE(mutex); + */ +#define TSA_RELEASE(...) TSA(release_capability(__VA_ARGS__)) +#define TSA_RELEASE_SHARED(...) TSA(release_shared_capability(__VA_ARGS__)) + +/* + * TSA_NO_TSA is used to annotate functions. Use only when you need to. + * + * void Foo(void) TSA_NO_TSA; + */ +#define TSA_NO_TSA TSA(no_thread_safety_analysis) + +/* + * TSA_ASSERT() is used to annotate functions: This function will assert that + * the lock is held. When it returns, the caller of the function is assumed to + * already hold the resource. + * + * More than one mutex may be specified, comma-separated. + */ +#define TSA_ASSERT(...) TSA(assert_capability(__VA_ARGS__)) +#define TSA_ASSERT_SHARED(...) TSA(assert_shared_capability(__VA_ARGS__)) + +/* + * Ugly CPP trick that is like "defined FOO", but also works in C + * code. Useful to replace #ifdef with "if" statements; assumes + * the symbol was defined with Meson's "config.set()", so it is empty + * if defined. + */ +#define IS_ENABLED(x) IS_EMPTY(x) + +#define IS_EMPTY_JUNK_ junk, +#define IS_EMPTY(value) IS_EMPTY_(IS_EMPTY_JUNK_##value) + +/* Expands to either SECOND_ARG(junk, 1, 0) or SECOND_ARG(IS_EMPTY_JUNK_CONFIG_FOO 1, 0) */ +#define SECOND_ARG(first, second, ...) second +#define IS_EMPTY_(junk_maybecomma) SECOND_ARG(junk_maybecomma 1, 0) + +#ifndef __cplusplus +/* + * Useful in macros that need to declare temporary variables. For example, + * the variable that receives the old value of an atomically-accessed + * variable must be non-qualified, because atomic builtins return values + * through a pointer-type argument as in __atomic_load(&var, &old, MODEL). + * + * This macro has to handle types smaller than int manually, because of + * implicit promotion. int and larger types, as well as pointers, can be + * converted to a non-qualified type just by applying a binary operator. + */ +#define typeof_strip_qual(expr) \ + typeof(__builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), bool) || __builtin_types_compatible_p(typeof(expr), const bool) || \ + __builtin_types_compatible_p(typeof(expr), volatile bool) || \ + __builtin_types_compatible_p(typeof(expr), const volatile bool), \ + (bool) 1, \ + __builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), signed char) || \ + __builtin_types_compatible_p(typeof(expr), const signed char) || \ + __builtin_types_compatible_p(typeof(expr), volatile signed char) || \ + __builtin_types_compatible_p(typeof(expr), const volatile signed char), \ + (signed char) 1, \ + __builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), unsigned char) || \ + __builtin_types_compatible_p(typeof(expr), const unsigned char) || \ + __builtin_types_compatible_p(typeof(expr), volatile unsigned char) || \ + __builtin_types_compatible_p(typeof(expr), const volatile unsigned char), \ + (unsigned char) 1, \ + __builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), signed short) || \ + __builtin_types_compatible_p(typeof(expr), const signed short) || \ + __builtin_types_compatible_p(typeof(expr), volatile signed short) || \ + __builtin_types_compatible_p(typeof(expr), const volatile signed short), \ + (signed short) 1, \ + __builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(expr), unsigned short) || \ + __builtin_types_compatible_p(typeof(expr), const unsigned short) || \ + __builtin_types_compatible_p(typeof(expr), volatile unsigned short) || \ + __builtin_types_compatible_p(typeof(expr), const volatile unsigned short), \ + (unsigned short) 1, (expr) + 0)))))) +#endif + +#endif /* COMPILER_H */ diff --git a/libutils/include/utils/config-host.h b/libutils/include/utils/config-host.h index dd4d420c0..93df1af39 100644 --- a/libutils/include/utils/config-host.h +++ b/libutils/include/utils/config-host.h @@ -26,17 +26,16 @@ // every translation unit that includes a utils header, in any component and // under any build rule (including the clang -emit-llvm bitcode rules), sees the // same definitions. Struct layouts in int128.h and qtree.h depend on them. +// HOST_BIG_ENDIAN comes from utils/compiler.h, as upstream. // Upstream CONFIG_INT128: the compiler has __int128. #ifdef __SIZEOF_INT128__ #define CONFIG_INT128 1 #endif -#if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -#define HOST_BIG_ENDIAN 1 -#else -#define HOST_BIG_ENDIAN 0 -#endif +// Upstream detects these at configure time; every supported host has them. +#define CONFIG_MADVISE 1 +#define CONFIG_POSIX_MEMALIGN 1 // Always use QEMU's own QTree rather than aliasing it to GTree. Upstream // switches on the glib version; keeping one implementation avoids a behavior diff --git a/libutils/include/utils/ctype.h b/libutils/include/utils/ctype.h new file mode 100644 index 000000000..ea70cea33 --- /dev/null +++ b/libutils/include/utils/ctype.h @@ -0,0 +1,29 @@ +/* + * QEMU TCG support + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#ifndef QEMU_CTYPE_H +#define QEMU_CTYPE_H + +#include + +#define qemu_isalnum(c) isalnum((unsigned char) (c)) +#define qemu_isalpha(c) isalpha((unsigned char) (c)) +#define qemu_iscntrl(c) iscntrl((unsigned char) (c)) +#define qemu_isdigit(c) isdigit((unsigned char) (c)) +#define qemu_isgraph(c) isgraph((unsigned char) (c)) +#define qemu_islower(c) islower((unsigned char) (c)) +#define qemu_isprint(c) isprint((unsigned char) (c)) +#define qemu_ispunct(c) ispunct((unsigned char) (c)) +#define qemu_isspace(c) isspace((unsigned char) (c)) +#define qemu_isupper(c) isupper((unsigned char) (c)) +#define qemu_isxdigit(c) isxdigit((unsigned char) (c)) +#define qemu_tolower(c) tolower((unsigned char) (c)) +#define qemu_toupper(c) toupper((unsigned char) (c)) +#define qemu_isascii(c) isascii((unsigned char) (c)) +#define qemu_toascii(c) toascii((unsigned char) (c)) + +#endif diff --git a/libutils/include/utils/cutils.h b/libutils/include/utils/cutils.h index fd5190e4e..7cea828b4 100644 --- a/libutils/include/utils/cutils.h +++ b/libutils/include/utils/cutils.h @@ -1,55 +1,269 @@ +#ifndef QEMU_CUTILS_H +#define QEMU_CUTILS_H + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * si_prefix: + * @exp10: exponent of 10, a multiple of 3 between -18 and 18 inclusive. + * + * Return a SI prefix (n, u, m, K, M, etc.) corresponding + * to the given exponent of 10. + */ +const char *si_prefix(unsigned int exp10); + /* - * Simple C functions to supplement the C library + * iec_binary_prefix: + * @exp2: exponent of 2, a multiple of 10 between 0 and 60 inclusive. + * + * Return an IEC binary prefix (Ki, Mi, etc.) corresponding + * to the given exponent of 2. + */ +const char *iec_binary_prefix(unsigned int exp2); + +/** + * pstrcpy: + * @buf: buffer to copy string into + * @buf_size: size of @buf in bytes + * @str: string to copy + * + * Copy @str into @buf, including the trailing NUL, but do not + * write more than @buf_size bytes. The resulting buffer is + * always NUL terminated (even if the source string was too long). + * If @buf_size is zero or negative then no bytes are copied. + * + * This function is similar to strncpy(), but avoids two of that + * function's problems: + * * if @str fits in the buffer, pstrcpy() does not zero-fill the + * remaining space at the end of @buf + * * if @str is too long, pstrcpy() will copy the first @buf_size-1 + * bytes and then add a NUL + */ +void pstrcpy(char *buf, int buf_size, const char *str); +/** + * strpadcpy: + * @buf: buffer to copy string into + * @buf_size: size of @buf in bytes + * @str: string to copy + * @pad: character to pad the remainder of @buf with + * + * Copy @str into @buf (but *not* its trailing NUL!), and then pad the + * rest of the buffer with the @pad character. If @str is too large + * for the buffer then it is truncated, so that @buf contains the + * first @buf_size characters of @str, with no terminator. + */ +void strpadcpy(char *buf, int buf_size, const char *str, char pad); +/** + * pstrcat: + * @buf: buffer containing existing string + * @buf_size: size of @buf in bytes + * @s: string to concatenate to @buf + * + * Append a copy of @s to the string already in @buf, but do not + * allow the buffer to overflow. If the existing contents of @buf + * plus @str would total more than @buf_size bytes, then write + * as much of @str as will fit followed by a NUL terminator. + * + * @buf must already contain a NUL-terminated string, or the + * behaviour is undefined. + * + * Returns: @buf. + */ +char *pstrcat(char *buf, int buf_size, const char *s); +/** + * strstart: + * @str: string to test + * @val: prefix string to look for + * @ptr: NULL, or pointer to be written to indicate start of + * the remainder of the string * - * Copyright (c) 2006 Fabrice Bellard + * Test whether @str starts with the prefix @val. + * If it does (including the degenerate case where @str and @val + * are equal) then return true. If @ptr is not NULL then a + * pointer to the first character following the prefix is written + * to it. If @val is not a prefix of @str then return false (and + * @ptr is not written to). * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: + * Returns: true if @str starts with prefix @val, false otherwise. + */ +int strstart(const char *str, const char *val, const char **ptr); +/** + * stristart: + * @str: string to test + * @val: prefix string to look for + * @ptr: NULL, or pointer to be written to indicate start of + * the remainder of the string * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. + * Test whether @str starts with the case-insensitive prefix @val. + * This function behaves identically to strstart(), except that the + * comparison is made after calling qemu_toupper() on each pair of + * characters. * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. + * Returns: true if @str starts with case-insensitive prefix @val, + * false otherwise. */ +int stristart(const char *str, const char *val, const char **ptr); -#ifndef _LIBTCG_CUTILS_H_ +/** + * qemu_strsep: + * @input: pointer to string to parse + * @delim: string containing delimiter characters to search for + * + * Locate the first occurrence of any character in @delim within + * the string referenced by @input, and replace it with a NUL. + * The location of the next character after the delimiter character + * is stored into @input. + * If the end of the string was reached without finding a delimiter + * character, then NULL is stored into @input. + * If @input points to a NULL pointer on entry, return NULL. + * The return value is always the original value of *@input (and + * so now points to a NUL-terminated string corresponding to the + * part of the input up to the first delimiter). + * + * This function has the same behaviour as the BSD strsep() function. + * + * Returns: the pointer originally in @input. + */ +char *qemu_strsep(char **input, const char *delim); +#ifdef HAVE_STRCHRNUL +static inline const char *qemu_strchrnul(const char *s, int c) { + return strchrnul(s, c); +} +#else +const char *qemu_strchrnul(const char *s, int c); +#endif +time_t mktimegm(struct tm *tm); +int qemu_parse_fd(const char *param); +int qemu_strtoi(const char *nptr, const char **endptr, int base, int *result); +int qemu_strtoui(const char *nptr, const char **endptr, int base, unsigned int *result); +int qemu_strtol(const char *nptr, const char **endptr, int base, long *result); +int qemu_strtoul(const char *nptr, const char **endptr, int base, unsigned long *result); +int qemu_strtoi64(const char *nptr, const char **endptr, int base, int64_t *result); +int qemu_strtou64(const char *nptr, const char **endptr, int base, uint64_t *result); +int qemu_strtod(const char *nptr, const char **endptr, double *result); +int qemu_strtod_finite(const char *nptr, const char **endptr, double *result); -#define _LIBTCG_CUTILS_H_ +int parse_uint(const char *s, const char **endptr, int base, uint64_t *value); +int parse_uint_full(const char *s, int base, uint64_t *value); -#include +int qemu_strtosz(const char *nptr, const char **end, uint64_t *result); +int qemu_strtosz_MiB(const char *nptr, const char **end, uint64_t *result); +int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result); -#ifdef __cplusplus -extern "C" { +char *size_to_str(uint64_t val); + +/** + * freq_to_str: + * @freq_hz: frequency to stringify + * + * Return human readable string for frequency @freq_hz. + * Use SI units like KHz, MHz, and so forth. + * + * The caller is responsible for releasing the value returned + * with g_free() after use. + */ +char *freq_to_str(uint64_t freq_hz); + +/* used to print char* safely */ +#define STR_OR_NULL(str) ((str) ? (str) : "null") + +/* + * Check if a buffer is all zeroes. + */ + +bool buffer_is_zero_ool(const void *vbuf, size_t len); +bool buffer_is_zero_ge256(const void *vbuf, size_t len); +bool test_buffer_is_zero_next_accel(void); + +static inline bool buffer_is_zero_sample3(const char *buf, size_t len) { + /* + * For any reasonably sized buffer, these three samples come from + * three different cachelines. In qemu-img usage, we find that + * each byte eliminates more than half of all buffer testing. + * It is therefore critical to performance that the byte tests + * short-circuit, so that we do not pull in additional cache lines. + * Do not "optimize" this to !(a | b | c). + */ + return !buf[0] && !buf[len - 1] && !buf[len / 2]; +} + +#ifdef __OPTIMIZE__ +static inline bool buffer_is_zero(const void *buf, size_t len) { + return (__builtin_constant_p(len) && len >= 256 + ? buffer_is_zero_sample3((const char *) buf, len) && buffer_is_zero_ge256(buf, len) + : buffer_is_zero_ool(buf, len)); +} +#else +#define buffer_is_zero buffer_is_zero_ool #endif -// strtosz() suffixes used to specify the default treatment of an -// argument passed to strtosz() without an explicit suffix. -// These should be defined using upper case characters in the range -// A-Z, as strtosz() will use qemu_toupper() on the given argument -// prior to comparison. -#define STRTOSZ_DEFSUFFIX_TB 'T' -#define STRTOSZ_DEFSUFFIX_GB 'G' -#define STRTOSZ_DEFSUFFIX_MB 'M' -#define STRTOSZ_DEFSUFFIX_KB 'K' -#define STRTOSZ_DEFSUFFIX_B 'B' +/* + * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128) + * Input is limited to 14-bit numbers + */ + +int uleb128_encode_small(uint8_t *out, uint32_t n); +int uleb128_decode_small(const uint8_t *in, uint32_t *n); -int64_t strtosz_suffix_unit(const char *nptr, char **end, const char default_suffix, int64_t unit); +/** + * qemu_pstrcmp0: + * @str1: a non-NULL pointer to a C string (*str1 can be NULL) + * @str2: a non-NULL pointer to a C string (*str2 can be NULL) + * + * Compares *str1 and *str2 with g_strcmp0(). + * + * Returns: an integer less than, equal to, or greater than zero, if + * *str1 is <, == or > than *str2. + */ +int qemu_pstrcmp0(const char **str1, const char **str2); -int64_t strtosz_suffix(const char *nptr, char **end, const char default_suffix); -int64_t strtosz(const char *nptr, char **end); +static inline const char *yes_no(bool b) { + return b ? "yes" : "no"; +} -void pstrcpy(char *buf, int buf_size, const char *str); -char *pstrcat(char *buf, int buf_size, const char *s); +/** + * qemu_hexdump_line: + * @str: GString into which to append + * @buf: buffer to dump + * @len: number of bytes to dump + * @unit_len: add a space between every @unit_len bytes + * @block_len: add an extra space between every @block_len bytes + * + * Append @len bytes of @buf as hexadecimal into @str. + * Add spaces between every @unit_len and @block_len bytes. + * If @str is NULL, allocate a new string and return it; + * otherwise return @str. + */ +GString *qemu_hexdump_line(GString *str, const void *buf, size_t len, size_t unit_len, size_t block_len); + +/* + * Hexdump a buffer to a file. An optional string prefix is added to every line + */ + +void qemu_hexdump(FILE *fp, const char *prefix, const void *bufptr, size_t size); + +/** + * qemu_hexdump_to_buffer: + * @buffer: output string buffer + * @buffer_size: amount of available space in buffer. Must be at least + * data_size*2+1. + * @data: input bytes + * @data_size: number of bytes in data + * + * Converts the @data_size bytes in @data into hex digit pairs, writing them to + * @buffer. Finally, a nul terminating character is written; @buffer therefore + * needs space for (data_size*2+1) chars. + */ +void qemu_hexdump_to_buffer(char *__restrict buffer, size_t buffer_size, const uint8_t *__restrict data, + size_t data_size); #ifdef __cplusplus } diff --git a/libutils/include/utils/int128.h b/libutils/include/utils/int128.h index 75eb7518f..3ce9fdf5b 100644 --- a/libutils/include/utils/int128.h +++ b/libutils/include/utils/int128.h @@ -5,6 +5,7 @@ #include #include +#include #include #ifdef __cplusplus diff --git a/libutils/include/utils/madvise.h b/libutils/include/utils/madvise.h new file mode 100644 index 000000000..62f84dd24 --- /dev/null +++ b/libutils/include/utils/madvise.h @@ -0,0 +1,105 @@ +/* + * QEMU madvise wrapper functions + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#ifndef QEMU_MADVISE_H +#define QEMU_MADVISE_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define QEMU_MADV_INVALID -1 + +#if defined(CONFIG_MADVISE) + +#define QEMU_MADV_WILLNEED MADV_WILLNEED +#define QEMU_MADV_DONTNEED MADV_DONTNEED +#ifdef MADV_DONTFORK +#define QEMU_MADV_DONTFORK MADV_DONTFORK +#else +#define QEMU_MADV_DONTFORK QEMU_MADV_INVALID +#endif +#ifdef MADV_MERGEABLE +#define QEMU_MADV_MERGEABLE MADV_MERGEABLE +#else +#define QEMU_MADV_MERGEABLE QEMU_MADV_INVALID +#endif +#ifdef MADV_UNMERGEABLE +#define QEMU_MADV_UNMERGEABLE MADV_UNMERGEABLE +#else +#define QEMU_MADV_UNMERGEABLE QEMU_MADV_INVALID +#endif +#ifdef MADV_DODUMP +#define QEMU_MADV_DODUMP MADV_DODUMP +#else +#define QEMU_MADV_DODUMP QEMU_MADV_INVALID +#endif +#ifdef MADV_DONTDUMP +#define QEMU_MADV_DONTDUMP MADV_DONTDUMP +#else +#define QEMU_MADV_DONTDUMP QEMU_MADV_INVALID +#endif +#ifdef MADV_HUGEPAGE +#define QEMU_MADV_HUGEPAGE MADV_HUGEPAGE +#else +#define QEMU_MADV_HUGEPAGE QEMU_MADV_INVALID +#endif +#ifdef MADV_NOHUGEPAGE +#define QEMU_MADV_NOHUGEPAGE MADV_NOHUGEPAGE +#else +#define QEMU_MADV_NOHUGEPAGE QEMU_MADV_INVALID +#endif +#ifdef MADV_REMOVE +#define QEMU_MADV_REMOVE MADV_REMOVE +#else +#define QEMU_MADV_REMOVE QEMU_MADV_DONTNEED +#endif +#ifdef MADV_POPULATE_WRITE +#define QEMU_MADV_POPULATE_WRITE MADV_POPULATE_WRITE +#else +#define QEMU_MADV_POPULATE_WRITE QEMU_MADV_INVALID +#endif + +#elif defined(CONFIG_POSIX_MADVISE) + +#define QEMU_MADV_WILLNEED POSIX_MADV_WILLNEED +#define QEMU_MADV_DONTNEED POSIX_MADV_DONTNEED +#define QEMU_MADV_DONTFORK QEMU_MADV_INVALID +#define QEMU_MADV_MERGEABLE QEMU_MADV_INVALID +#define QEMU_MADV_UNMERGEABLE QEMU_MADV_INVALID +#define QEMU_MADV_DODUMP QEMU_MADV_INVALID +#define QEMU_MADV_DONTDUMP QEMU_MADV_INVALID +#define QEMU_MADV_HUGEPAGE QEMU_MADV_INVALID +#define QEMU_MADV_NOHUGEPAGE QEMU_MADV_INVALID +#define QEMU_MADV_REMOVE QEMU_MADV_DONTNEED +#define QEMU_MADV_POPULATE_WRITE QEMU_MADV_INVALID + +#else /* no-op */ + +#define QEMU_MADV_WILLNEED QEMU_MADV_INVALID +#define QEMU_MADV_DONTNEED QEMU_MADV_INVALID +#define QEMU_MADV_DONTFORK QEMU_MADV_INVALID +#define QEMU_MADV_MERGEABLE QEMU_MADV_INVALID +#define QEMU_MADV_UNMERGEABLE QEMU_MADV_INVALID +#define QEMU_MADV_DODUMP QEMU_MADV_INVALID +#define QEMU_MADV_DONTDUMP QEMU_MADV_INVALID +#define QEMU_MADV_HUGEPAGE QEMU_MADV_INVALID +#define QEMU_MADV_NOHUGEPAGE QEMU_MADV_INVALID +#define QEMU_MADV_REMOVE QEMU_MADV_INVALID +#define QEMU_MADV_POPULATE_WRITE QEMU_MADV_INVALID + +#endif + +int qemu_madvise(void *addr, size_t len, int advice); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libutils/include/utils/memalign.h b/libutils/include/utils/memalign.h index 8660e3d8b..3d5f3e22f 100644 --- a/libutils/include/utils/memalign.h +++ b/libutils/include/utils/memalign.h @@ -1,32 +1,12 @@ /* - * memalign.c: Allocate an aligned memory region + * Allocation and free functions for aligned memory * - * Copyright (c) 2003-2008 Fabrice Bellard - * Copyright (c) 2010-2016 Red Hat, Inc. - * Copyright (c) 2022 Linaro Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. */ -#ifndef LIBTCG_MEMALIGN - -#define LIBTCG_MEMALIGN +#ifndef QEMU_MEMALIGN_H +#define QEMU_MEMALIGN_H #include @@ -34,12 +14,57 @@ extern "C" { #endif +/** + * qemu_try_memalign: Allocate aligned memory + * @alignment: required alignment, in bytes + * @size: size of allocation, in bytes + * + * Allocate memory on an aligned boundary (i.e. the returned + * address will be an exact multiple of @alignment). + * @alignment must be a power of 2, or the function will assert(). + * On success, returns allocated memory; on failure, returns NULL. + * + * The memory allocated through this function must be freed via + * qemu_vfree() (and not via free()). + */ void *qemu_try_memalign(size_t alignment, size_t size); +/** + * qemu_memalign: Allocate aligned memory, without failing + * @alignment: required alignment, in bytes + * @size: size of allocation, in bytes + * + * Allocate memory in the same way as qemu_try_memalign(), but + * abort() with an error message if the memory allocation fails. + * + * The memory allocated through this function must be freed via + * qemu_vfree() (and not via free()). + */ void *qemu_memalign(size_t alignment, size_t size); +/** + * qemu_vfree: Free memory allocated through qemu_memalign + * @ptr: memory to free + * + * This function must be used to free memory allocated via qemu_memalign() + * or qemu_try_memalign(). (Using the wrong free function will cause + * subtle bugs on Windows hosts.) + */ void qemu_vfree(void *ptr); +/* + * It's an analog of GLIB's g_autoptr_cleanup_generic_gfree(), used to define + * g_autofree macro. + */ +static inline void qemu_cleanup_generic_vfree(void *p) { + void **pp = (void **) p; + qemu_vfree(*pp); +} + +/* + * Analog of g_autofree, but qemu_vfree is called on cleanup instead of g_free. + */ +#define QEMU_AUTO_VFREE __attribute__((cleanup(qemu_cleanup_generic_vfree))) #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/libutils/include/utils/mprotect.h b/libutils/include/utils/mprotect.h new file mode 100644 index 000000000..a8f6711f5 --- /dev/null +++ b/libutils/include/utils/mprotect.h @@ -0,0 +1,24 @@ +/* + * QEMU mprotect functions + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ +#ifndef QEMU_MPROTECT_H +#define QEMU_MPROTECT_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int qemu_mprotect_rw(void *addr, size_t size); +int qemu_mprotect_rwx(void *addr, size_t size); +int qemu_mprotect_none(void *addr, size_t size); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libutils/include/utils/osdep.h b/libutils/include/utils/osdep.h index fab4c0ad2..6b624263d 100644 --- a/libutils/include/utils/osdep.h +++ b/libutils/include/utils/osdep.h @@ -1,167 +1,148 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -#ifndef TCG_OSDEP_H -#define TCG_OSDEP_H +/* + * OS includes and handling of OS dependencies + * + * This header exists to pull in some common system headers that + * most code in QEMU will want, and to fix up some possible issues with + * it (missing defines, Windows weirdness, and so on). + * + * To avoid getting into possible circular include dependencies, this + * file should not include any other QEMU headers, with the exceptions + * of config-host.h, config-target.h, qemu/compiler.h, + * system/os-posix.h, system/os-win32.h, system/os-wasm.h, glib-compat.h and + * qemu/typedefs.h, all of which are doing a similar job to this file + * and are under similar constraints. + * + * This header also contains prototypes for functions defined in + * os-*.c and util/oslib-*.c; those would probably be better split + * out into separate header files. + * + * In an ideal world this header would contain only: + * (1) things which everybody needs + * (2) things without which code would work on most platforms but + * fail to compile or misbehave on a minority of host OSes + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ +#ifndef QEMU_OSDEP_H +#define QEMU_OSDEP_H + +#include +#include + +/* Older versions of C++ don't get definitions of various macros from + * stdlib.h unless we define these macros before first inclusion of + * that system header. + */ +#ifndef __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS +#endif +#ifndef __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS +#endif +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include #include +#include #include #include -#ifdef __OpenBSD__ -#include -#include -#endif - -#include +#include +#include +#include #include +#include +#include +#include #include -#include +#include #ifdef __cplusplus extern "C" { #endif -#ifndef glue -#define xglue(x, y) x##y -#define glue(x, y) xglue(x, y) -#define stringify(s) tostring(s) -#define tostring(s) #s -#endif - -#define QEMU_ALIGNED(X) __attribute__((aligned(X))) - -#ifndef container_of -#define container_of(ptr, type, member) \ - ({ \ - const typeof(((type *) 0)->member) *__mptr = (ptr); \ - (type *) ((char *) __mptr - offsetof(type, member)); \ - }) -#endif - -/* Convert from a base type to a parent type, with compile time checking. */ -#ifdef __GNUC__ -#define DO_UPCAST(type, field, dev) \ - (__extension__({ \ - char __attribute__((unused)) offset_must_be_zero[-offsetof(type, field)]; \ - container_of(dev, type, field); \ - })) +/** + * Mark a function that executes in coroutine context + * + * Functions that execute in coroutine context cannot be called directly from + * normal functions. In the future it would be nice to enable compiler or + * static checker support for catching such errors. This annotation might make + * it possible and in the meantime it serves as documentation. + * + * For example: + * + * static void coroutine_fn foo(void) { + * .... + * } + */ +#ifdef __clang__ +#define coroutine_fn QEMU_ANNOTATE("coroutine_fn") #else -#define DO_UPCAST(type, field, dev) container_of(dev, type, field) -#endif - -#define typeof_field(type, field) typeof(((type *) 0)->field) -#define type_check(t1, t2) ((t1 *) 0 - (t2 *) 0) - -#ifndef MIN -#define MIN(a, b) (((a) < (b)) ? (a) : (b)) -#endif -#ifndef MAX -#define MAX(a, b) (((a) > (b)) ? (a) : (b)) -#endif - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define coroutine_fn #endif -#define likely(x) __builtin_expect(!!(x), 1) -#define unlikely(x) __builtin_expect(!!(x), 0) - -#define QEMU_FALLTHROUGH __attribute__((fallthrough)) -#define QEMU_PACKED __attribute__((packed)) - -/* - * GCC doesn't provide __has_attribute() until GCC 5, but we know all the GCC - * versions we support have the "flatten" attribute. Clang may not have the - * "flatten" attribute but always has __has_attribute() to check for it. +/** + * Mark a function that can suspend when executed in coroutine context, + * but can handle running in non-coroutine context too. */ -#if __has_attribute(flatten) || !defined(__clang__) -#define QEMU_FLATTEN __attribute__((flatten)) +#ifdef __clang__ +#define coroutine_mixed_fn QEMU_ANNOTATE("coroutine_mixed_fn") #else -#define QEMU_FLATTEN +#define coroutine_mixed_fn #endif -/* - * If __attribute__((always_inline)) is available, use it to force inlining - * where softfloat relies on constant folding of its format parameters. +/** + * Mark a function that should not be called from a coroutine context. + * Usually there will be an analogous, coroutine_fn function that should + * be used instead. + * + * When the function is also marked as coroutine_mixed_fn, the function should + * only be called if the caller does not know whether it is in coroutine + * context. + * + * Functions that are only no_coroutine_fn, on the other hand, should not + * be called from within coroutines at all. This for example includes + * functions that block. + * + * In the future it would be nice to enable compiler or static checker + * support for catching such errors. This annotation is the first step + * towards this, and in the meantime it serves as documentation. + * + * For example: + * + * static void no_coroutine_fn foo(void) { + * .... + * } */ -#if __has_attribute(always_inline) || !defined(__clang__) -#define QEMU_ALWAYS_INLINE __attribute__((always_inline)) +#ifdef __clang__ +#define no_coroutine_fn QEMU_ANNOTATE("no_coroutine_fn") #else -#define QEMU_ALWAYS_INLINE +#define no_coroutine_fn #endif -#ifndef __cplusplus /* - * Take the type of an expression, stripped of any const/volatile qualifiers. - * The atomic builtins return values through a pointer-type argument, as in - * __atomic_load(&var, &old, MODEL), so the destination must be non-qualified. - * - * Types smaller than int are handled explicitly because of implicit promotion; - * int and larger types, and pointers, are stripped by applying a binary - * operator. Upstream keeps this in include/qemu/compiler.h, whose contents - * libtcg folds into osdep.h. - */ -#define typeof_strip_qual(expr) \ - typeof(__builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), bool) || __builtin_types_compatible_p(typeof(expr), const bool) || \ - __builtin_types_compatible_p(typeof(expr), volatile bool) || \ - __builtin_types_compatible_p(typeof(expr), const volatile bool), \ - (bool) 1, \ - __builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), signed char) || \ - __builtin_types_compatible_p(typeof(expr), const signed char) || \ - __builtin_types_compatible_p(typeof(expr), volatile signed char) || \ - __builtin_types_compatible_p(typeof(expr), const volatile signed char), \ - (signed char) 1, \ - __builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), unsigned char) || \ - __builtin_types_compatible_p(typeof(expr), const unsigned char) || \ - __builtin_types_compatible_p(typeof(expr), volatile unsigned char) || \ - __builtin_types_compatible_p(typeof(expr), const volatile unsigned char), \ - (unsigned char) 1, \ - __builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), signed short) || \ - __builtin_types_compatible_p(typeof(expr), const signed short) || \ - __builtin_types_compatible_p(typeof(expr), volatile signed short) || \ - __builtin_types_compatible_p(typeof(expr), const volatile signed short), \ - (signed short) 1, \ - __builtin_choose_expr( \ - __builtin_types_compatible_p(typeof(expr), unsigned short) || \ - __builtin_types_compatible_p(typeof(expr), const unsigned short) || \ - __builtin_types_compatible_p(typeof(expr), volatile unsigned short) || \ - __builtin_types_compatible_p(typeof(expr), const volatile unsigned short), \ - (unsigned short) 1, (expr) + 0)))))) -#endif /* !__cplusplus */ - -/* - * If __attribute__((error)) is present, use it to produce an error at - * compile time. Otherwise, one must wait for the linker to diagnose - * the missing symbol. + * For mingw, as of v6.0.0, the function implementing the assert macro is + * not marked as noreturn, so the compiler cannot delete code following an + * assert(false) as unused. We rely on this within the code base to delete + * code that is unreachable when features are disabled. + * All supported versions of Glib's g_assert() satisfy this requirement. */ -#if __has_attribute(error) -#define QEMU_ERROR(X) __attribute__((error(X))) -#else -#define QEMU_ERROR(X) -#endif - -#ifndef NORETURN -#define NORETURN __attribute__((noreturn)) +#ifdef __MINGW32__ +#undef assert +#define assert(x) g_assert(x) #endif /** @@ -172,15 +153,12 @@ extern "C" { * supports QEMU_ERROR, this will be reported at compile time; otherwise * this will be reported at link time due to the missing symbol. */ -NORETURN extern void QEMU_ERROR("code path is reachable") qemu_build_not_reached_always(void); +G_NORETURN +void QEMU_ERROR("code path is reachable") qemu_build_not_reached_always(void); #if defined(__OPTIMIZE__) && !defined(__NO_INLINE__) #define qemu_build_not_reached() qemu_build_not_reached_always() #else -#define qemu_build_not_reached() \ - { \ - fprintf(stderr, "not reached"); \ - abort(); \ - } +#define qemu_build_not_reached() g_assert_not_reached() #endif /** @@ -193,25 +171,237 @@ NORETURN extern void QEMU_ERROR("code path is reachable") qemu_build_not_reached while (!(test)) \ qemu_build_not_reached() -// TODO: move this elsewhere? -static inline void flush_idcache_range(uintptr_t rx, uintptr_t rw, size_t len) { -} +/* + * According to waitpid man page: + * WCOREDUMP + * This macro is not specified in POSIX.1-2001 and is not + * available on some UNIX implementations (e.g., AIX, SunOS). + * Therefore, enclose its use inside #ifdef WCOREDUMP ... #endif. + */ +#ifndef WCOREDUMP +#define WCOREDUMP(status) 0 +#endif +/* + * We have a lot of unaudited code that may fail in strange ways, or + * even be a security risk during migration, if you disable assertions + * at compile-time. You may comment out these safety checks if you + * absolutely want to disable assertion overhead, but it is not + * supported upstream so the risk is all yours. Meanwhile, please + * submit patches to remove any side-effects inside an assertion, or + * fixing error handling that should use Error instead of assert. + */ +/* S2E builds libtcg and libcpu with NDEBUG in release, so upstream's NDEBUG refusal is dropped here. */ +#ifdef G_DISABLE_ASSERT +#error building with G_DISABLE_ASSERT is not supported +#endif -#define LIBTCG_ERROR(X) __attribute__((error(X))) -NORETURN extern void LIBTCG_ERROR("code path is reachable") qemu_build_not_reached_always(void); +#ifndef OFF_MAX +#define OFF_MAX (sizeof(off_t) == 8 ? INT64_MAX : INT32_MAX) +#endif -static inline void qemu_thread_jit_write(void) { -} -static inline void qemu_thread_jit_execute(void) { -} +#ifndef O_LARGEFILE +#define O_LARGEFILE 0 +#endif +#ifndef O_BINARY +#define O_BINARY 0 +#endif +#ifndef MAP_ANONYMOUS +#define MAP_ANONYMOUS MAP_ANON +#endif +#ifndef MAP_NORESERVE +#define MAP_NORESERVE 0 +#endif +#ifndef ENOMEDIUM +#define ENOMEDIUM ENODEV +#endif +#if !defined(ENOTSUP) +#define ENOTSUP 4096 +#endif +#if !defined(ECANCELED) +#define ECANCELED 4097 +#endif +#if !defined(EMEDIUMTYPE) +#define EMEDIUMTYPE 4098 +#endif +#if !defined(ESHUTDOWN) +#define ESHUTDOWN 4099 +#endif -#define QEMU_MADV_INVALID -1 +#define RETRY_ON_EINTR(expr) \ + (__extension__({ \ + typeof(expr) __result; \ + do { \ + __result = (expr); \ + } while (__result == -1 && errno == EINTR); \ + __result; \ + })) -int qemu_madvise(void *addr, size_t len, int advice); -int qemu_mprotect_rw(void *addr, size_t size); -int qemu_mprotect_rwx(void *addr, size_t size); -int qemu_mprotect_none(void *addr, size_t size); +/* time_t may be either 32 or 64 bits depending on the host OS, and + * can be either signed or unsigned, so we can't just hardcode a + * specific maximum value. This is not a C preprocessor constant, + * so you can't use TIME_MAX in an #ifdef, but for our purposes + * this isn't a problem. + */ +/* The macros TYPE_SIGNED, TYPE_WIDTH, and TYPE_MAXIMUM are from + * Gnulib, and are under the LGPL v2.1 or (at your option) any + * later version. + */ + +/* True if the real type T is signed. */ +#define TYPE_SIGNED(t) (!((t) 0 < (t) - 1)) + +/* The width in bits of the integer type or expression T. + * Padding bits are not supported. + */ +#define TYPE_WIDTH(t) (sizeof(t) * CHAR_BIT) + +/* The maximum and minimum values for the integer type T. */ +#define TYPE_MAXIMUM(t) ((t) (!TYPE_SIGNED(t) ? (t) - 1 : ((((t) 1 << (TYPE_WIDTH(t) - 2)) - 1) * 2 + 1))) + +#ifndef TIME_MAX +#define TIME_MAX TYPE_MAXIMUM(time_t) +#endif + +#ifndef PATH_MAX +#define PATH_MAX 1024 +#endif + +/* + * Use the same value as Linux for now. + */ +#ifndef IOV_MAX +#define IOV_MAX 1024 +#endif + +/* Mac OSX has a bug that incorrectly defines SIZE_MAX with + * the wrong type. Our replacement isn't usable in preprocessor + * expressions, but it is sufficient for our needs. */ +#ifdef HAVE_BROKEN_SIZE_MAX +#undef SIZE_MAX +#define SIZE_MAX ((size_t) -1) +#endif + +/* + * Two variations of MIN/MAX macros. The first is for runtime use, and + * evaluates arguments only once (so it is safe even with side + * effects), but will not work in constant contexts (such as array + * size declarations) because of the '{}'. The second is for constant + * expression use, where evaluating arguments twice is safe because + * the result is going to be constant anyway, but will not work in a + * runtime context because of a void expression where a value is + * expected. Thus, both gcc and clang will fail to compile if you use + * the wrong macro (even if the error may seem a bit cryptic). + * + * Note that neither form is usable as an #if condition; if you truly + * need to write conditional code that depends on a minimum or maximum + * determined by the pre-processor instead of the compiler, you'll + * have to open-code it. Sadly, Coverity is severely confused by the + * constant variants, so we have to dumb things down there. + * + * Preprocessor sorcery ahead: use different identifiers for the local + * variables in each expansion, so we can nest macro calls without + * shadowing variables. + */ +#define MIN_INTERNAL(a, b, _a, _b) \ + ({ \ + typeof(1 ? (a) : (b)) _a = (a), _b = (b); \ + _a < _b ? _a : _b; \ + }) +#undef MIN +#define MIN(a, b) MIN_INTERNAL((a), (b), MAKE_IDENTIFIER(_a), MAKE_IDENTIFIER(_b)) + +#define MAX_INTERNAL(a, b, _a, _b) \ + ({ \ + typeof(1 ? (a) : (b)) _a = (a), _b = (b); \ + _a > _b ? _a : _b; \ + }) +#undef MAX +#define MAX(a, b) MAX_INTERNAL((a), (b), MAKE_IDENTIFIER(_a), MAKE_IDENTIFIER(_b)) + +#ifdef __COVERITY__ +#define MIN_CONST(a, b) ((a) < (b) ? (a) : (b)) +#define MAX_CONST(a, b) ((a) > (b) ? (a) : (b)) +#else +#define MIN_CONST(a, b) \ + __builtin_choose_expr(__builtin_constant_p(a) && __builtin_constant_p(b), (a) < (b) ? (a) : (b), ((void) 0)) +#define MAX_CONST(a, b) \ + __builtin_choose_expr(__builtin_constant_p(a) && __builtin_constant_p(b), (a) > (b) ? (a) : (b), ((void) 0)) +#endif + +/* + * Minimum function that returns zero only if both values are zero. + * Intended for use with unsigned values only. + * + * Preprocessor sorcery ahead: use different identifiers for the local + * variables in each expansion, so we can nest macro calls without + * shadowing variables. + */ +#define MIN_NON_ZERO_INTERNAL(a, b, _a, _b) \ + ({ \ + typeof(1 ? (a) : (b)) _a = (a), _b = (b); \ + _a == 0 ? _b : (_b == 0 || _b > _a) ? _a : _b; \ + }) +#define MIN_NON_ZERO(a, b) MIN_NON_ZERO_INTERNAL((a), (b), MAKE_IDENTIFIER(_a), MAKE_IDENTIFIER(_b)) + +/* + * Round number down to multiple. Safe when m is not a power of 2 (see + * ROUND_DOWN for a faster version when a power of 2 is guaranteed). + */ +#define QEMU_ALIGN_DOWN(n, m) ((n) / (m) * (m)) + +/* + * Round number up to multiple. Safe when m is not a power of 2 (see + * ROUND_UP for a faster version when a power of 2 is guaranteed). + */ +#define QEMU_ALIGN_UP(n, m) QEMU_ALIGN_DOWN((n) + (m) - 1, (m)) + +/* Check if n is a multiple of m */ +#define QEMU_IS_ALIGNED(n, m) (((n) % (m)) == 0) + +/* n-byte align pointer down */ +#define QEMU_ALIGN_PTR_DOWN(p, n) ((typeof(p)) QEMU_ALIGN_DOWN((uintptr_t) (p), (n))) + +/* n-byte align pointer up */ +#define QEMU_ALIGN_PTR_UP(p, n) ((typeof(p)) QEMU_ALIGN_UP((uintptr_t) (p), (n))) + +/* Check if pointer p is n-bytes aligned */ +#define QEMU_PTR_IS_ALIGNED(p, n) QEMU_IS_ALIGNED((uintptr_t) (p), (n)) + +/* + * Round number down to multiple. Requires that d be a power of 2 (see + * QEMU_ALIGN_UP for a safer but slower version on arbitrary + * numbers); works even if d is a smaller type than n. + */ +#ifndef ROUND_DOWN +#define ROUND_DOWN(n, d) ((n) & -(0 ? (n) : (d))) +#endif + +/* + * Round number up to multiple. Requires that d be a power of 2 (see + * QEMU_ALIGN_UP for a safer but slower version on arbitrary + * numbers); works even if d is a smaller type than n. + */ +#ifndef ROUND_UP +#define ROUND_UP(n, d) ROUND_DOWN((n) + (d) - 1, (d)) +#endif + +#ifndef DIV_ROUND_UP +#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) +#endif + +/* + * &(x)[0] is always a pointer - if it's same type as x then the argument is a + * pointer, not an array. + */ +#define QEMU_IS_ARRAY(x) (!__builtin_types_compatible_p(typeof(x), typeof(&(x)[0]))) +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(x) ((sizeof(x) / sizeof((x)[0])) + QEMU_BUILD_BUG_ON_ZERO(!QEMU_IS_ARRAY(x))) +#endif + +/* Using intptr_t ensures that qemu_*_page_mask is sign-extended even + * when intptr_t is 32-bit and we are aligning a long long. + */ static inline uintptr_t qemu_real_host_page_size(void) { return getpagesize(); } @@ -220,28 +410,45 @@ static inline intptr_t qemu_real_host_page_mask(void) { return -(intptr_t) qemu_real_host_page_size(); } +/** + * qemu_get_host_physmem: + * + * Operating system agnostic way of querying host memory. + * + * Returns amount of physical memory on the system. This is purely + * advisery and may return 0 if we can't work it out. At the other + * end we saturate to SIZE_MAX if you are lucky enough to have that + * much memory. + */ size_t qemu_get_host_physmem(void); -#define QEMU_BUILD_BUG_ON_STRUCT(x) \ - struct { \ - int : (x) ? -1 : 1; \ - } - -#define QEMU_BUILD_BUG_MSG(x, msg) _Static_assert(!(x), msg) - -#define QEMU_BUILD_BUG_ON(x) QEMU_BUILD_BUG_MSG(x, "not expecting: " #x) - -#define QEMU_BUILD_BUG_ON_ZERO(x) (sizeof(QEMU_BUILD_BUG_ON_STRUCT(x)) - sizeof(QEMU_BUILD_BUG_ON_STRUCT(x))) - -#ifdef CONFIG_CFI /* - * If CFI is enabled, use an attribute to disable cfi-icall on the following - * function + * Toggle write/execute on the pages marked MAP_JIT + * for the current thread. */ -#define QEMU_DISABLE_CFI __attribute__((no_sanitize("cfi-icall"))) +#ifdef __APPLE__ +static inline void qemu_thread_jit_execute(void) { + pthread_jit_write_protect_np(true); +} + +static inline void qemu_thread_jit_write(void) { + pthread_jit_write_protect_np(false); +} #else -/* If CFI is not enabled, use an empty define to not change the behavior */ -#define QEMU_DISABLE_CFI +static inline void qemu_thread_jit_write(void) { +} +static inline void qemu_thread_jit_execute(void) { +} +#endif + +#ifdef __cplusplus +/* S2E keeps the plain forms for C++; the ones above rely on statement expressions and __builtin_types_compatible_p. */ +#undef MIN +#undef MAX +#undef ARRAY_SIZE +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #endif #ifdef __cplusplus diff --git a/libutils/include/utils/rounding.h b/libutils/include/utils/rounding.h deleted file mode 100644 index 561c7b3b5..000000000 --- a/libutils/include/utils/rounding.h +++ /dev/null @@ -1,61 +0,0 @@ -// Helper macros for pointer arithmetic. -// -// Contains code derived from these sources: -// https://github.com/lattera/glibc/blob/master/include/libc-pointer-arith.h - -// Copyright (C) 2012-2019 Free Software Foundation, Inc. -// This file is part of the GNU C Library. -// -// The GNU C Library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// The GNU C Library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with the GNU C Library; if not, see -// . - -#ifndef LIBTCG_ROUNDING - -#define LIBTCG_ROUNDING - -#ifdef __cplusplus -extern "C" { -#endif - -// Round number down to multiple -#define ALIGN_DOWN(base, size) ((base) / (size) * (size)) -#define QEMU_ALIGN_DOWN ALIGN_DOWN - -// Align a value by rounding up to closest size. -// E.g. Using size of 4096, we get this behavior: -// {4095, 4096, 4097} = {4096, 4096, 8192}. -// Note: The size argument has side effects (expanded multiple times). -#define ALIGN_UP(base, size) ALIGN_DOWN((base) + (size) - 1, (base)) - -// Same as ALIGN_DOWN(), but automatically casts when base is a pointer -#define ALIGN_PTR_DOWN(base, size) ((typeof(base)) ALIGN_DOWN((uintptr_t) (base), (size))) - -// Same as ALIGN_UP(), but automatically casts when base is a pointer -#define ALIGN_PTR_UP(base, size) ((typeof(base)) ALIGN_UP((uintptr_t) (base), (size))) -#define QEMU_ALIGN_PTR_UP ALIGN_PTR_UP - -// Round number up to multiple. -// Requires that size be a power of 2. -#ifndef ROUND_UP -#define ROUND_UP(base, size) (((base) + (size) - 1) & -(size)) -#endif - -#ifndef DIV_ROUND_UP -#define DIV_ROUND_UP(base, size) (((base) + (size) - 1) / (size)) -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libutils/scripts/upgrade/mapping.tsv b/libutils/scripts/upgrade/mapping.tsv index 7f28b9dd4..9cc952e19 100644 --- a/libutils/scripts/upgrade/mapping.tsv +++ b/libutils/scripts/upgrade/mapping.tsv @@ -3,10 +3,9 @@ # Only the vendored QEMU utilities below include/utils/ and src/utils/ appear # here. The rest of libutils (QAPI, QObject, the visitors, coroutines, # fsigc++) is S2E-original or diverged far enough that it is not merged -# mechanically, and the S2E-original utilities (utils/cache.h, utils/cache.c, -# utils/config-host.h, utils/mutex.h, utils/spinlock.h, utils/rounding.h) have -# no upstream counterpart at all. The merge driver is scripts/upgrade/merge.sh -# at the S2E source root. +# mechanically, and the S2E-original utilities (utils/config-host.h, +# utils/mutex.h, utils/spinlock.h) have no upstream counterpart at all. The +# merge driver is scripts/upgrade/merge.sh at the S2E source root. # # upstream-dirs: util/ include/qemu/ host/include/ # @@ -24,23 +23,34 @@ src/utils/cpuinfo-i386.c util/cpuinfo-i386.c include/utils/atomic.h include/qemu/atomic.h include/utils/atomic128.h include/qemu/atomic128.h include/utils/bitops.h include/qemu/bitops.h +include/utils/cacheflush.h include/qemu/cacheflush.h +include/utils/cacheinfo.h include/qemu/cacheinfo.h +include/utils/compiler.h include/qemu/compiler.h include/utils/cpuid.h include/qemu/cpuid.h +include/utils/ctype.h include/qemu/ctype.h include/utils/debug-assert.h include/tcg/debug-assert.h include/utils/host-utils.h include/qemu/host-utils.h include/utils/int128.h include/qemu/int128.h include/utils/interval-tree.h include/qemu/interval-tree.h +include/utils/madvise.h include/qemu/madvise.h +include/utils/memalign.h include/qemu/memalign.h +include/utils/mprotect.h include/qemu/mprotect.h include/utils/qtree.h include/qemu/qtree.h include/utils/units.h include/qemu/units.h include/utils/registerfields.h include/hw/core/registerfields.h +src/utils/cacheflush.c util/cacheflush.c +src/utils/hexdump.c util/hexdump.c src/utils/host-utils.c util/host-utils.c src/utils/interval-tree.c util/interval-tree.c src/utils/memalign.c util/memalign.c src/utils/qtree.c util/qtree.c -# Heavily reduced S2E-specific subsets, still v8.1.0-era: these are hand -# written rather than vendored, so merge by hand, not mechanically. -include/utils/memalign.h include/qemu/memalign.h -include/utils/bitmap.h include/qemu/bitmap.h +# Pruned copies: upstream text with whole sections removed because they need +# meson configuration, os-posix.h, the Error API or sockets. They merge +# mechanically as long as upstream leaves the kept sections alone; a conflict +# in a removed section is resolved by deleting it again. cutils.h drops the +# prototypes whose bodies cutils.c prunes. include/utils/cutils.h include/qemu/cutils.h include/utils/osdep.h include/qemu/osdep.h src/utils/cutils.c util/cutils.c src/utils/osdep.c util/osdep.c +src/utils/oslib-posix.c util/oslib-posix.c diff --git a/libutils/src/CMakeLists.txt b/libutils/src/CMakeLists.txt index 443e544d5..986f368b9 100644 --- a/libutils/src/CMakeLists.txt +++ b/libutils/src/CMakeLists.txt @@ -50,15 +50,16 @@ add_library ( q/qapi/qapi-util.c q/error.c q/unicode.c - q/cutils.c - utils/cache.c + utils/cacheflush.c utils/cpuinfo-i386.c utils/cutils.c + utils/hexdump.c utils/host-utils.c utils/interval-tree.c utils/memalign.c utils/osdep.c + utils/oslib-posix.c utils/qtree.c ) diff --git a/libutils/src/coroutine/coroutine-ucontext.c b/libutils/src/coroutine/coroutine-ucontext.c index 78293280e..4af514912 100644 --- a/libutils/src/coroutine/coroutine-ucontext.c +++ b/libutils/src/coroutine/coroutine-ucontext.c @@ -37,10 +37,6 @@ #include #include "coroutine-int.h" -#define container_of(addr, type, field) ((type *) ((uintptr_t) (addr) - (uintptr_t) (&((type *) 0)->field))) - -#define DO_UPCAST(type, field, dev) container_of(dev, type, field) - typedef struct { Coroutine base; void *stack; diff --git a/libutils/src/q/cutils.c b/libutils/src/q/cutils.c deleted file mode 100644 index 2684ea6f2..000000000 --- a/libutils/src/q/cutils.c +++ /dev/null @@ -1,543 +0,0 @@ -/* - * Simple C functions to supplement the C library - * - * Copyright (c) 2006 Fabrice Bellard - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "cutils.h" - -#include - -static int64_t suffix_mul(char suffix, int64_t unit) { - switch (toupper(suffix)) { - case 'B': - return 1; - case 'K': - return unit; - case 'M': - return unit * unit; - case 'G': - return unit * unit * unit; - case 'T': - return unit * unit * unit * unit; - case 'P': - return unit * unit * unit * unit * unit; - case 'E': - return unit * unit * unit * unit * unit * unit; - } - return -1; -} - -static inline void mulu64(uint64_t *plow, uint64_t *phigh, uint64_t a, uint64_t b) { - __uint128_t r = (__uint128_t) a * b; - *plow = r; - *phigh = r >> 64; -} - -/* - * Convert size string to bytes. - * - * The size parsing supports the following syntaxes - * - 12345 - decimal, scale determined by @default_suffix and @unit - * - 12345{bBkKmMgGtTpPeE} - decimal, scale determined by suffix and @unit - * - 12345.678{kKmMgGtTpPeE} - decimal, scale determined by suffix, and - * fractional portion is truncated to byte - * - 0x7fEE - hexadecimal, unit determined by @default_suffix - * - * The following cause a deprecation warning, and may be removed in the future - * - 0xabc{kKmMgGtTpP} - hex with scaling suffix - * - * The following are intentionally not supported - * - octal, such as 08 - * - fractional hex, such as 0x1.8 - * - floating point exponents, such as 1e3 - * - * The end pointer will be returned in *end, if not NULL. If there is - * no fraction, the input can be decimal or hexadecimal; if there is a - * fraction, then the input must be decimal and there must be a suffix - * (possibly by @default_suffix) larger than Byte, and the fractional - * portion may suffer from precision loss or rounding. The input must - * be positive. - * - * Return -ERANGE on overflow (with *@end advanced), and -EINVAL on - * other error (with *@end left unchanged). - */ -static int do_strtosz(const char *nptr, const char **end, const char default_suffix, int64_t unit, uint64_t *result) { - int retval; - const char *endptr, *f; - unsigned char c; - bool hex = false; - uint64_t val, valf = 0; - int64_t mul; - - /* Parse integral portion as decimal. */ - retval = libq_strtou64(nptr, &endptr, 10, &val); - if (retval) { - goto out; - } - if (memchr(nptr, '-', endptr - nptr) != NULL) { - endptr = nptr; - retval = -EINVAL; - goto out; - } - if (val == 0 && (*endptr == 'x' || *endptr == 'X')) { - /* Input looks like hex, reparse, and insist on no fraction. */ - retval = libq_strtou64(nptr, &endptr, 16, &val); - if (retval) { - goto out; - } - if (*endptr == '.') { - endptr = nptr; - retval = -EINVAL; - goto out; - } - hex = true; - } else if (*endptr == '.') { - /* - * Input looks like a fraction. Make sure even 1.k works - * without fractional digits. If we see an exponent, treat - * the entire input as invalid instead. - */ - double fraction; - - f = endptr; - retval = libq_strtod_finite(f, &endptr, &fraction); - if (retval) { - endptr++; - } else if (memchr(f, 'e', endptr - f) || memchr(f, 'E', endptr - f)) { - endptr = nptr; - retval = -EINVAL; - goto out; - } else { - /* Extract into a 64-bit fixed-point fraction. */ - valf = (uint64_t) (fraction * 0x1p64); - } - } - c = *endptr; - mul = suffix_mul(c, unit); - if (mul > 0) { - if (hex) { - fprintf(stderr, - "Using a multiplier suffix on hex numbers " - "is deprecated: %s", - nptr); - } - endptr++; - } else { - mul = suffix_mul(default_suffix, unit); - assert(mul > 0); - } - if (mul == 1) { - /* When a fraction is present, a scale is required. */ - if (valf != 0) { - endptr = nptr; - retval = -EINVAL; - goto out; - } - } else { - uint64_t valh, tmp; - - /* Compute exact result: 64.64 x 64.0 -> 128.64 fixed point */ - mulu64(&val, &valh, val, mul); - mulu64(&valf, &tmp, valf, mul); - val += tmp; - valh += val < tmp; - - /* Round 0.5 upward. */ - tmp = valf >> 63; - val += tmp; - valh += val < tmp; - - /* Report overflow. */ - if (valh != 0) { - retval = -ERANGE; - goto out; - } - } - - retval = 0; - -out: - if (end) { - *end = endptr; - } else if (*endptr) { - retval = -EINVAL; - } - if (retval == 0) { - *result = val; - } - - return retval; -} - -int libq_strtosz(const char *nptr, const char **end, uint64_t *result) { - return do_strtosz(nptr, end, 'B', 1024, result); -} - -/** - * Helper function for error checking after strtol() and the like - */ -static int check_strtox_error(const char *nptr, char *ep, const char **endptr, bool check_zero, int libc_errno) { - assert(ep >= nptr); - - /* Windows has a bug in that it fails to parse 0 from "0x" in base 16 */ - if (check_zero && ep == nptr && libc_errno == 0) { - char *tmp; - - errno = 0; - if (strtol(nptr, &tmp, 10) == 0 && errno == 0 && (*tmp == 'x' || *tmp == 'X')) { - ep = tmp; - } - } - - if (endptr) { - *endptr = ep; - } - - /* Turn "no conversion" into an error */ - if (libc_errno == 0 && ep == nptr) { - return -EINVAL; - } - - /* Fail when we're expected to consume the string, but didn't */ - if (!endptr && *ep) { - return -EINVAL; - } - - return -libc_errno; -} - -/** - * Convert string @nptr to an integer, and store it in @result. - * - * This is a wrapper around strtol() that is harder to misuse. - * Semantics of @nptr, @endptr, @base match strtol() with differences - * noted below. - * - * @nptr may be null, and no conversion is performed then. - * - * If no conversion is performed, store @nptr in *@endptr and return - * -EINVAL. - * - * If @endptr is null, and the string isn't fully converted, return - * -EINVAL. This is the case when the pointer that would be stored in - * a non-null @endptr points to a character other than '\0'. - * - * If the conversion overflows @result, store INT_MAX in @result, - * and return -ERANGE. - * - * If the conversion underflows @result, store INT_MIN in @result, - * and return -ERANGE. - * - * Else store the converted value in @result, and return zero. - */ -int libq_strtoi(const char *nptr, const char **endptr, int base, int *result) { - char *ep; - long long lresult; - - assert((unsigned) base <= 36 && base != 1); - if (!nptr) { - if (endptr) { - *endptr = nptr; - } - return -EINVAL; - } - - errno = 0; - lresult = strtoll(nptr, &ep, base); - if (lresult < INT_MIN) { - *result = INT_MIN; - errno = ERANGE; - } else if (lresult > INT_MAX) { - *result = INT_MAX; - errno = ERANGE; - } else { - *result = lresult; - } - return check_strtox_error(nptr, ep, endptr, lresult == 0, errno); -} - -/** - * Convert string @nptr to an unsigned integer, and store it in @result. - * - * This is a wrapper around strtoul() that is harder to misuse. - * Semantics of @nptr, @endptr, @base match strtoul() with differences - * noted below. - * - * @nptr may be null, and no conversion is performed then. - * - * If no conversion is performed, store @nptr in *@endptr and return - * -EINVAL. - * - * If @endptr is null, and the string isn't fully converted, return - * -EINVAL. This is the case when the pointer that would be stored in - * a non-null @endptr points to a character other than '\0'. - * - * If the conversion overflows @result, store UINT_MAX in @result, - * and return -ERANGE. - * - * Else store the converted value in @result, and return zero. - * - * Note that a number with a leading minus sign gets converted without - * the minus sign, checked for overflow (see above), then negated (in - * @result's type). This is exactly how strtoul() works. - */ -int libq_strtoui(const char *nptr, const char **endptr, int base, unsigned int *result) { - char *ep; - long long lresult; - - assert((unsigned) base <= 36 && base != 1); - if (!nptr) { - if (endptr) { - *endptr = nptr; - } - return -EINVAL; - } - - errno = 0; - lresult = strtoull(nptr, &ep, base); - - /* Windows returns 1 for negative out-of-range values. */ - if (errno == ERANGE) { - *result = -1; - } else { - if (lresult > UINT_MAX) { - *result = UINT_MAX; - errno = ERANGE; - } else if (lresult < INT_MIN) { - *result = UINT_MAX; - errno = ERANGE; - } else { - *result = lresult; - } - } - return check_strtox_error(nptr, ep, endptr, lresult == 0, errno); -} - -/** - * Convert string @nptr to a long integer, and store it in @result. - * - * This is a wrapper around strtol() that is harder to misuse. - * Semantics of @nptr, @endptr, @base match strtol() with differences - * noted below. - * - * @nptr may be null, and no conversion is performed then. - * - * If no conversion is performed, store @nptr in *@endptr and return - * -EINVAL. - * - * If @endptr is null, and the string isn't fully converted, return - * -EINVAL. This is the case when the pointer that would be stored in - * a non-null @endptr points to a character other than '\0'. - * - * If the conversion overflows @result, store LONG_MAX in @result, - * and return -ERANGE. - * - * If the conversion underflows @result, store LONG_MIN in @result, - * and return -ERANGE. - * - * Else store the converted value in @result, and return zero. - */ -int libq_strtol(const char *nptr, const char **endptr, int base, long *result) { - char *ep; - - assert((unsigned) base <= 36 && base != 1); - if (!nptr) { - if (endptr) { - *endptr = nptr; - } - return -EINVAL; - } - - errno = 0; - *result = strtol(nptr, &ep, base); - return check_strtox_error(nptr, ep, endptr, *result == 0, errno); -} - -/** - * Convert string @nptr to an unsigned long, and store it in @result. - * - * This is a wrapper around strtoul() that is harder to misuse. - * Semantics of @nptr, @endptr, @base match strtoul() with differences - * noted below. - * - * @nptr may be null, and no conversion is performed then. - * - * If no conversion is performed, store @nptr in *@endptr and return - * -EINVAL. - * - * If @endptr is null, and the string isn't fully converted, return - * -EINVAL. This is the case when the pointer that would be stored in - * a non-null @endptr points to a character other than '\0'. - * - * If the conversion overflows @result, store ULONG_MAX in @result, - * and return -ERANGE. - * - * Else store the converted value in @result, and return zero. - * - * Note that a number with a leading minus sign gets converted without - * the minus sign, checked for overflow (see above), then negated (in - * @result's type). This is exactly how strtoul() works. - */ -int libq_strtoul(const char *nptr, const char **endptr, int base, unsigned long *result) { - char *ep; - - assert((unsigned) base <= 36 && base != 1); - if (!nptr) { - if (endptr) { - *endptr = nptr; - } - return -EINVAL; - } - - errno = 0; - *result = strtoul(nptr, &ep, base); - /* Windows returns 1 for negative out-of-range values. */ - if (errno == ERANGE) { - *result = -1; - } - return check_strtox_error(nptr, ep, endptr, *result == 0, errno); -} - -/** - * Convert string @nptr to an int64_t. - * - * Works like libq_strtol(), except it stores INT64_MAX on overflow, - * and INT64_MIN on underflow. - */ -int libq_strtoi64(const char *nptr, const char **endptr, int base, int64_t *result) { - char *ep; - - assert((unsigned) base <= 36 && base != 1); - if (!nptr) { - if (endptr) { - *endptr = nptr; - } - return -EINVAL; - } - - /* This assumes int64_t is long long TODO relax */ - LIBQ_BUILD_BUG_ON(sizeof(int64_t) != sizeof(long long)); - errno = 0; - *result = strtoll(nptr, &ep, base); - return check_strtox_error(nptr, ep, endptr, *result == 0, errno); -} - -/** - * Convert string @nptr to an uint64_t. - * - * Works like libq_strtoul(), except it stores UINT64_MAX on overflow. - */ -int libq_strtou64(const char *nptr, const char **endptr, int base, uint64_t *result) { - char *ep; - - assert((unsigned) base <= 36 && base != 1); - if (!nptr) { - if (endptr) { - *endptr = nptr; - } - return -EINVAL; - } - - /* This assumes uint64_t is unsigned long long TODO relax */ - LIBQ_BUILD_BUG_ON(sizeof(uint64_t) != sizeof(unsigned long long)); - errno = 0; - *result = strtoull(nptr, &ep, base); - /* Windows returns 1 for negative out-of-range values. */ - if (errno == ERANGE) { - *result = -1; - } - return check_strtox_error(nptr, ep, endptr, *result == 0, errno); -} - -/** - * Convert string @nptr to a double. - * - * This is a wrapper around strtod() that is harder to misuse. - * Semantics of @nptr and @endptr match strtod() with differences - * noted below. - * - * @nptr may be null, and no conversion is performed then. - * - * If no conversion is performed, store @nptr in *@endptr and return - * -EINVAL. - * - * If @endptr is null, and the string isn't fully converted, return - * -EINVAL. This is the case when the pointer that would be stored in - * a non-null @endptr points to a character other than '\0'. - * - * If the conversion overflows, store +/-HUGE_VAL in @result, depending - * on the sign, and return -ERANGE. - * - * If the conversion underflows, store +/-0.0 in @result, depending on the - * sign, and return -ERANGE. - * - * Else store the converted value in @result, and return zero. - */ -int libq_strtod(const char *nptr, const char **endptr, double *result) { - char *ep; - - if (!nptr) { - if (endptr) { - *endptr = nptr; - } - return -EINVAL; - } - - errno = 0; - *result = strtod(nptr, &ep); - return check_strtox_error(nptr, ep, endptr, false, errno); -} - -/** - * Convert string @nptr to a finite double. - * - * Works like libq_strtod(), except that "NaN" and "inf" are rejected - * with -EINVAL and no conversion is performed. - */ -int libq_strtod_finite(const char *nptr, const char **endptr, double *result) { - double tmp; - int ret; - - ret = libq_strtod(nptr, endptr, &tmp); - if (!ret && !isfinite(tmp)) { - if (endptr) { - *endptr = nptr; - } - ret = -EINVAL; - } - - if (ret != -EINVAL) { - *result = tmp; - } - return ret; -} \ No newline at end of file diff --git a/libutils/src/q/qapi/qapi-forward-visitor.c b/libutils/src/q/qapi/qapi-forward-visitor.c index cb00aeac6..88836197e 100644 --- a/libutils/src/q/qapi/qapi-forward-visitor.c +++ b/libutils/src/q/qapi/qapi-forward-visitor.c @@ -8,7 +8,7 @@ * */ -#include "../cutils.h" +#include #include "qapi/error.h" #include "qapi/forward-visitor.h" #include "qapi/qmp/qbool.h" diff --git a/libutils/src/q/qapi/qobject-input-visitor.c b/libutils/src/q/qapi/qobject-input-visitor.c index f66cf1039..6f191b719 100644 --- a/libutils/src/q/qapi/qobject-input-visitor.c +++ b/libutils/src/q/qapi/qobject-input-visitor.c @@ -15,7 +15,7 @@ #include #include -#include "../cutils.h" +#include #include "qapi/error.h" #include "qapi/qmp/qbool.h" #include "qapi/qmp/qdict.h" @@ -379,7 +379,7 @@ static bool qobject_input_type_int64_keyval(Visitor *v, const char *name, int64_ return false; } - if (libq_strtoi64(str, NULL, 0, obj) < 0) { + if (qemu_strtoi64(str, NULL, 0, obj) < 0) { /* TODO report -ERANGE more nicely */ error_setg(errp, QERR_INVALID_PARAMETER_VALUE, full_name(qiv, name), "integer"); return false; @@ -424,7 +424,7 @@ static bool qobject_input_type_uint64_keyval(Visitor *v, const char *name, uint6 return false; } - if (libq_strtou64(str, NULL, 0, obj) < 0) { + if (qemu_strtou64(str, NULL, 0, obj) < 0) { /* TODO report -ERANGE more nicely */ error_setg(errp, QERR_INVALID_PARAMETER_VALUE, full_name(qiv, name), "integer"); return false; @@ -519,7 +519,7 @@ static bool qobject_input_type_number_keyval(Visitor *v, const char *name, doubl return false; } - if (libq_strtod_finite(str, NULL, &val)) { + if (qemu_strtod_finite(str, NULL, &val)) { /* TODO report -ERANGE more nicely */ error_setg(errp, QERR_INVALID_PARAMETER_TYPE, full_name(qiv, name), "number"); return false; @@ -567,7 +567,7 @@ static bool qobject_input_type_size_keyval(Visitor *v, const char *name, uint64_ return false; } - if (libq_strtosz(str, NULL, obj) < 0) { + if (qemu_strtosz(str, NULL, obj) < 0) { /* TODO report -ERANGE more nicely */ error_setg(errp, QERR_INVALID_PARAMETER_VALUE, full_name(qiv, name), "size"); return false; diff --git a/libutils/src/q/qobject/json-parser.c b/libutils/src/q/qobject/json-parser.c index 4085dc7f8..bfdc43c8b 100644 --- a/libutils/src/q/qobject/json-parser.c +++ b/libutils/src/q/qobject/json-parser.c @@ -27,7 +27,7 @@ #include "qapi/qmp/qnum.h" #include "qapi/qmp/qstring.h" -#include "../cutils.h" +#include #include "../unicode.h" struct JSONToken { @@ -485,8 +485,8 @@ static QObject *parse_literal(JSONParserContext *ctxt) { case JSON_INTEGER: { /* * Represent JSON_INTEGER as QNUM_I64 if possible, else as - * QNUM_U64, else as QNUM_DOUBLE. Note that libq_strtoi64() - * and libq_strtou64() fail with ERANGE when it's not + * QNUM_U64, else as QNUM_DOUBLE. Note that qemu_strtoi64() + * and qemu_strtou64() fail with ERANGE when it's not * possible. * * qnum_get_int() will then work for any signed 64-bit @@ -499,14 +499,14 @@ static QObject *parse_literal(JSONParserContext *ctxt) { int64_t value; uint64_t uvalue; - ret = libq_strtoi64(token->str, NULL, 10, &value); + ret = qemu_strtoi64(token->str, NULL, 10, &value); if (!ret) { return QOBJECT(qnum_from_int(value)); } assert(ret == -ERANGE); if (token->str[0] != '-') { - ret = libq_strtou64(token->str, NULL, 10, &uvalue); + ret = qemu_strtou64(token->str, NULL, 10, &uvalue); if (!ret) { return QOBJECT(qnum_from_uint(uvalue)); } diff --git a/libutils/src/utils/cache.c b/libutils/src/utils/cache.c deleted file mode 100644 index 01c5f8a79..000000000 --- a/libutils/src/utils/cache.c +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2023 Vitaly Chipounov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#include - -#include - -int g_icache_linesize = 0; -int g_dcache_linesize = 0; - -static int sys_cache_info(int *isize, int *dsize) { - int ret = (int) sysconf(_SC_LEVEL1_ICACHE_LINESIZE); - if (ret > 0) { - *isize = ret; - } else { - return -1; - } - - ret = (int) sysconf(_SC_LEVEL1_DCACHE_LINESIZE); - if (ret > 0) { - *dsize = ret; - } else { - return -2; - } - - return 0; -} - -int init_cache_info() { - return sys_cache_info(&g_icache_linesize, &g_dcache_linesize); -} diff --git a/libutils/src/utils/cacheflush.c b/libutils/src/utils/cacheflush.c new file mode 100644 index 000000000..9ad054e3f --- /dev/null +++ b/libutils/src/utils/cacheflush.c @@ -0,0 +1,351 @@ +/* + * Info about, and flushing the host cpu caches. + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#include +#include +#include +#include +#include +#include + +int qemu_icache_linesize = 0; +int qemu_icache_linesize_log; +int qemu_dcache_linesize = 0; +int qemu_dcache_linesize_log; + +/* + * Operating system specific cache detection mechanisms. + */ + +#if defined(_WIN32) + +static void sys_cache_info(int *isize, int *dsize) { + SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buf; + DWORD size = 0; + BOOL success; + size_t i, n; + + /* + * Check for the required buffer size first. Note that if the zero + * size we use for the probe results in success, then there is no + * data available; fail in that case. + */ + success = GetLogicalProcessorInformation(0, &size); + if (success || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + return; + } + + n = size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); + size = n * sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); + buf = g_new0(SYSTEM_LOGICAL_PROCESSOR_INFORMATION, n); + if (!GetLogicalProcessorInformation(buf, &size)) { + goto fail; + } + + for (i = 0; i < n; i++) { + if (buf[i].Relationship == RelationCache && buf[i].Cache.Level == 1) { + switch (buf[i].Cache.Type) { + case CacheUnified: + *isize = *dsize = buf[i].Cache.LineSize; + break; + case CacheInstruction: + *isize = buf[i].Cache.LineSize; + break; + case CacheData: + *dsize = buf[i].Cache.LineSize; + break; + default: + break; + } + } + } +fail: + g_free(buf); +} + +#elif defined(CONFIG_DARWIN) +#include +static void sys_cache_info(int *isize, int *dsize) { + /* There's only a single sysctl for both I/D cache line sizes. */ + long size; + size_t len = sizeof(size); + if (!sysctlbyname("hw.cachelinesize", &size, &len, NULL, 0)) { + *isize = *dsize = size; + } +} +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) +#include +static void sys_cache_info(int *isize, int *dsize) { + /* There's only a single sysctl for both I/D cache line sizes. */ + int size; + size_t len = sizeof(size); + if (!sysctlbyname("machdep.cacheline_size", &size, &len, NULL, 0)) { + *isize = *dsize = size; + } +} +#else +/* POSIX */ + +static void sys_cache_info(int *isize, int *dsize) { +#ifdef _SC_LEVEL1_ICACHE_LINESIZE + int tmp_isize = (int) sysconf(_SC_LEVEL1_ICACHE_LINESIZE); + if (tmp_isize > 0) { + *isize = tmp_isize; + } +#endif +#ifdef _SC_LEVEL1_DCACHE_LINESIZE + int tmp_dsize = (int) sysconf(_SC_LEVEL1_DCACHE_LINESIZE); + if (tmp_dsize > 0) { + *dsize = tmp_dsize; + } +#endif +} +#endif /* sys_cache_info */ + +/* + * Architecture (+ OS) specific cache detection mechanisms. + */ + +#if defined(__powerpc__) +static bool have_coherent_icache; +#endif + +#if defined(__aarch64__) && !defined(CONFIG_DARWIN) && !defined(CONFIG_WIN32) +/* + * Apple does not expose CTR_EL0, so we must use system interfaces. + * Windows neither, but we use a generic implementation of flush_idcache_range + * in this case. + */ +static uint64_t save_ctr_el0; +static void arch_cache_info(int *isize, int *dsize) { + uint64_t ctr; + + /* + * The real cache geometry is in CCSIDR_EL1/CLIDR_EL1/CSSELR_EL1, + * but (at least under Linux) these are marked protected by the + * kernel. However, CTR_EL0 contains the minimum linesize in the + * entire hierarchy, and is used by userspace cache flushing. + * + * We will also use this value in flush_idcache_range. + */ + asm volatile("mrs\t%0, ctr_el0" : "=r"(ctr)); + save_ctr_el0 = ctr; + + if (*isize == 0 || *dsize == 0) { + if (*isize == 0) { + *isize = 4 << (ctr & 0xf); + } + if (*dsize == 0) { + *dsize = 4 << ((ctr >> 16) & 0xf); + } + } +} + +#elif defined(_ARCH_PPC64) && defined(__linux__) +#include "elf.h" + +static void arch_cache_info(int *isize, int *dsize) { + if (*isize == 0) { + *isize = qemu_getauxval(AT_ICACHEBSIZE); + } + if (*dsize == 0) { + *dsize = qemu_getauxval(AT_DCACHEBSIZE); + } + have_coherent_icache = qemu_getauxval(AT_HWCAP) & PPC_FEATURE_ICACHE_SNOOP; +} + +#else +static void arch_cache_info(int *isize, int *dsize) { +} +#endif /* arch_cache_info */ + +/* + * ... and if all else fails ... + */ + +static void fallback_cache_info(int *isize, int *dsize) { + /* If we can only find one of the two, assume they're the same. */ + if (*isize) { + if (*dsize) { + /* Success! */ + } else { + *dsize = *isize; + } + } else if (*dsize) { + *isize = *dsize; + } else { +#if defined(_ARCH_PPC64) + /* + * For PPC, we're going to use the cache sizes computed for + * flush_idcache_range. Which means that we must use the + * architecture minimum. + */ + *isize = *dsize = 16; +#else + /* Otherwise, 64 bytes is not uncommon. */ + *isize = *dsize = 64; +#endif + } +} + +static void __attribute__((constructor)) init_cache_info(void) { + int isize = 0, dsize = 0; + + sys_cache_info(&isize, &dsize); + arch_cache_info(&isize, &dsize); + fallback_cache_info(&isize, &dsize); + + assert((isize & (isize - 1)) == 0); + assert((dsize & (dsize - 1)) == 0); + + qemu_icache_linesize = isize; + qemu_icache_linesize_log = ctz32(isize); + qemu_dcache_linesize = dsize; + qemu_dcache_linesize_log = ctz32(dsize); +} + +/* + * Architecture (+ OS) specific cache flushing mechanisms. + */ + +#if defined(__x86_64__) || defined(__s390x__) + +/* Caches are coherent and do not require flushing; symbol inline. */ + +#elif defined(EMSCRIPTEN) + +/* Wasm doesn't have executable region of memory. */ + +#elif defined(__aarch64__) && !defined(CONFIG_WIN32) +/* + * For Windows, we use generic implementation of flush_idcache_range, that + * performs a call to FlushInstructionCache, through __builtin___clear_cache. + */ + +#ifdef CONFIG_DARWIN +/* Apple does not expose CTR_EL0, so we must use system interfaces. */ +#include + +void flush_idcache_range(uintptr_t rx, uintptr_t rw, size_t len) { + if (rx == rw) { + /* + * sys_icache_invalidate() syncs the dcache and icache, + * so no need to call sys_dcache_flush(). + */ + } else { + sys_dcache_flush((void *) rw, len); + } + sys_icache_invalidate((void *) rx, len); +} +#else + +/* + * This is a copy of gcc's __aarch64_sync_cache_range, modified + * to fit this three-operand interface. + */ +void flush_idcache_range(uintptr_t rx, uintptr_t rw, size_t len) { + const unsigned CTR_IDC = 1u << 28; + const unsigned CTR_DIC = 1u << 29; + const uint64_t ctr_el0 = save_ctr_el0; + const uintptr_t icache_lsize = qemu_icache_linesize; + const uintptr_t dcache_lsize = qemu_dcache_linesize; + uintptr_t p; + + /* + * If CTR_EL0.IDC is enabled, Data cache clean to the Point of Unification + * is not required for instruction to data coherence. + */ + if (!(ctr_el0 & CTR_IDC)) { + /* + * Loop over the address range, clearing one cache line at once. + * Data cache must be flushed to unification first to make sure + * the instruction cache fetches the updated data. + */ + for (p = rw & -dcache_lsize; p < rw + len; p += dcache_lsize) { + asm volatile("dc\tcvau, %0" : : "r"(p) : "memory"); + } + } + + /* DSB unconditionally to ensure any outstanding writes are committed. */ + asm volatile("dsb\tish" : : : "memory"); + + /* + * If CTR_EL0.DIC is enabled, Instruction cache cleaning to the Point + * of Unification is not required for instruction to data coherence. + */ + if (!(ctr_el0 & CTR_DIC)) { + for (p = rx & -icache_lsize; p < rx + len; p += icache_lsize) { + asm volatile("ic\tivau, %0" : : "r"(p) : "memory"); + } + asm volatile("dsb\tish" : : : "memory"); + } + + asm volatile("isb" : : : "memory"); +} +#endif /* CONFIG_DARWIN */ + +#elif defined(__powerpc__) + +void flush_idcache_range(uintptr_t rx, uintptr_t rw, size_t len) { + uintptr_t p, b, e; + size_t dsize, isize; + + /* + * Some processors have coherent caches and support a simplified + * flushing procedure. See + * POWER9 UM, 4.6.2.2 Instruction Cache Block Invalidate (icbi) + * https://ibm.ent.box.com/s/tmklq90ze7aj8f4n32er1mu3sy9u8k3k + */ + if (have_coherent_icache) { + asm volatile("sync\n\t" + "icbi 0,%0\n\t" + "isync" + : + : "r"(rx) + : "memory"); + return; + } + + dsize = qemu_dcache_linesize; + isize = qemu_icache_linesize; + + b = rw & ~(dsize - 1); + e = (rw + len + dsize - 1) & ~(dsize - 1); + for (p = b; p < e; p += dsize) { + asm volatile("dcbst 0,%0" : : "r"(p) : "memory"); + } + asm volatile("sync" : : : "memory"); + + b = rx & ~(isize - 1); + e = (rx + len + isize - 1) & ~(isize - 1); + for (p = b; p < e; p += isize) { + asm volatile("icbi 0,%0" : : "r"(p) : "memory"); + } + asm volatile("sync" : : : "memory"); + asm volatile("isync" : : : "memory"); +} + +#elif defined(__sparc__) + +void flush_idcache_range(uintptr_t rx, uintptr_t rw, size_t len) { + /* No additional data flush to the RW virtual address required. */ + uintptr_t p, end = (rx + len + 7) & -8; + for (p = rx & -8; p < end; p += 8) { + __asm__ __volatile__("flush\t%0" : : "r"(p)); + } +} + +#else + +void flush_idcache_range(uintptr_t rx, uintptr_t rw, size_t len) { + if (rw != rx) { + __builtin___clear_cache((char *) rw, (char *) rw + len); + } + __builtin___clear_cache((char *) rx, (char *) rx + len); +} + +#endif diff --git a/libutils/src/utils/cutils.c b/libutils/src/utils/cutils.c index be2054b4f..3d352cd96 100644 --- a/libutils/src/utils/cutils.c +++ b/libutils/src/utils/cutils.c @@ -22,112 +22,903 @@ * THE SOFTWARE. */ -#include -#include -#include -#include #include -#include -#include +#include +#include +#ifdef __FreeBSD__ +#include +#include +#endif + +#ifdef __NetBSD__ +#include +#endif + +#ifdef __HAIKU__ +#include +#endif + +#ifdef __APPLE__ +#include +#endif + +#ifdef G_OS_WIN32 +#include +#include +#endif + +#include #include +void strpadcpy(char *buf, int buf_size, const char *str, char pad) { + size_t len = strnlen(str, buf_size); + memcpy(buf, str, len); + memset(buf + len, pad, buf_size - len); +} + +void pstrcpy(char *buf, int buf_size, const char *str) { + int c; + char *q = buf; + + if (buf_size <= 0) + return; + + for (;;) { + c = *str++; + if (c == 0 || q >= buf + buf_size - 1) + break; + *q++ = c; + } + *q = '\0'; +} + +/* strcat and truncate. */ +char *pstrcat(char *buf, int buf_size, const char *s) { + int len; + len = strlen(buf); + if (len < buf_size) + pstrcpy(buf + len, buf_size - len, s); + return buf; +} + +int strstart(const char *str, const char *val, const char **ptr) { + const char *p, *q; + p = str; + q = val; + while (*q != '\0') { + if (*p != *q) + return 0; + p++; + q++; + } + if (ptr) + *ptr = p; + return 1; +} + +int stristart(const char *str, const char *val, const char **ptr) { + const char *p, *q; + p = str; + q = val; + while (*q != '\0') { + if (qemu_toupper(*p) != qemu_toupper(*q)) + return 0; + p++; + q++; + } + if (ptr) + *ptr = p; + return 1; +} + +char *qemu_strsep(char **input, const char *delim) { + char *result = *input; + if (result != NULL) { + char *p; + + for (p = result; *p != '\0'; p++) { + if (strchr(delim, *p)) { + break; + } + } + if (*p == '\0') { + *input = NULL; + } else { + *p = '\0'; + *input = p + 1; + } + } + return result; +} + +time_t mktimegm(struct tm *tm) { + time_t t; + int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday; + if (m < 3) { + m += 12; + y--; + } + t = 86400ULL * (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469); + t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec; + return t; +} + static int64_t suffix_mul(char suffix, int64_t unit) { - switch (toupper(suffix)) { - case STRTOSZ_DEFSUFFIX_B: + switch (qemu_toupper(suffix)) { + case 'B': return 1; - case STRTOSZ_DEFSUFFIX_KB: + case 'K': return unit; - case STRTOSZ_DEFSUFFIX_MB: + case 'M': return unit * unit; - case STRTOSZ_DEFSUFFIX_GB: + case 'G': return unit * unit * unit; - case STRTOSZ_DEFSUFFIX_TB: + case 'T': return unit * unit * unit * unit; + case 'P': + return unit * unit * unit * unit * unit; + case 'E': + return unit * unit * unit * unit * unit * unit; } return -1; } -/// -/// \brief strtosz_suffix_unit Convert string to bytes, allowing either B/b for bytes, K/k for KB, -/// M/m for MB, G/g for GB or T/t for TB. End pointer will be returned -/// in *end, if not NULL. -/// -/// \param nptr -/// \param end -/// \param default_suffix -/// \param unit -/// \return -1 on error -/// -int64_t strtosz_suffix_unit(const char *nptr, char **end, const char default_suffix, int64_t unit) { - int64_t retval = -1; - char *endptr; +/* + * Convert size string to bytes. + * + * The size parsing supports the following syntaxes + * - 12345 - decimal, scale determined by @default_suffix and @unit + * - 12345{bBkKmMgGtTpPeE} - decimal, scale determined by suffix and @unit + * - 12345.678{kKmMgGtTpPeE} - decimal, scale determined by suffix, and + * fractional portion is truncated to byte, either side of . may be empty + * - 0x7fEE - hexadecimal, unit determined by @default_suffix + * + * The following are intentionally not supported + * - hex with scaling suffix, such as 0x20M or 0x1p3 (both fail with + * -EINVAL), while 0x1b is 27 (not 1 with byte scale) + * - octal, such as 08 (parsed as decimal instead) + * - binary, such as 0b1000 (parsed as 0b with trailing garbage "1000") + * - fractional hex, such as 0x1.8 (parsed as 0 with trailing garbage "x1.8") + * - negative values, including -0 (fail with -ERANGE) + * - floating point exponents, such as 1e3 (parsed as 1e with trailing + * garbage "3") or 0x1p3 (rejected as hex with scaling suffix) + * - non-finite values, such as inf or NaN (fail with -EINVAL) + * + * The end pointer will be returned in *end, if not NULL. If there is + * no fraction, the input can be decimal or hexadecimal; if there is a + * non-zero fraction, then the input must be decimal and there must be + * a suffix (possibly by @default_suffix) larger than Byte, and the + * fractional portion may suffer from precision loss or rounding. The + * input must be positive. + * + * Return -ERANGE on overflow (with *@end advanced), and -EINVAL on + * other error (with *@end at @nptr). Unlike strtoull, *@result is + * set to 0 on all errors, as returning UINT64_MAX on overflow is less + * likely to be usable as a size. + */ +static int do_strtosz(const char *nptr, const char **end, const char default_suffix, int64_t unit, uint64_t *result) { + int retval; + const char *endptr; unsigned char c; - int mul_required = 0; - double val, mul, integral, fraction; + uint64_t val = 0, valf = 0; + int64_t mul; - errno = 0; - val = strtod(nptr, &endptr); - if (__builtin_isnan(val) || endptr == nptr || errno != 0) { - goto fail; + /* Parse integral portion as decimal. */ + retval = parse_uint(nptr, &endptr, 10, &val); + if (retval == -ERANGE || !nptr) { + goto out; + } + if (retval == 0 && val == 0 && (*endptr == 'x' || *endptr == 'X')) { + /* Input looks like hex; reparse, and insist on no fraction or suffix. */ + retval = qemu_strtou64(nptr, &endptr, 16, &val); + if (retval) { + goto out; + } + if (*endptr == '.' || suffix_mul(*endptr, unit) > 0) { + endptr = nptr; + retval = -EINVAL; + goto out; + } + } else if (*endptr == '.' || (endptr == nptr && strchr(nptr, '.'))) { + /* + * Input looks like a fraction. Make sure even 1.k works + * without fractional digits. strtod tries to treat 'e' as an + * exponent, but we want to treat it as a scaling suffix; + * doing this requires modifying a copy of the fraction. + */ + double fraction = 0.0; + + if (retval == 0 && *endptr == '.' && !isdigit(endptr[1])) { + /* If we got here, we parsed at least one digit already. */ + endptr++; + } else { + char *e; + const char *tail; + g_autofree char *copy = g_strdup(endptr); + + e = strchr(copy, 'e'); + if (e) { + *e = '\0'; + } + e = strchr(copy, 'E'); + if (e) { + *e = '\0'; + } + /* + * If this is a floating point, we are guaranteed that '.' + * appears before any possible digits in copy. If it is + * not a floating point, strtod will fail. Either way, + * there is now no exponent in copy, so if it parses, we + * know 0.0 <= abs(result) <= 1.0 (after rounding), and + * ERANGE is only possible on underflow which is okay. + */ + retval = qemu_strtod_finite(copy, &tail, &fraction); + endptr += tail - copy; + if (signbit(fraction)) { + retval = -ERANGE; + goto out; + } + } + + /* Extract into a 64-bit fixed-point fraction. */ + if (fraction == 1.0) { + if (val == UINT64_MAX) { + retval = -ERANGE; + goto out; + } + val++; + } else if (retval == -ERANGE) { + /* See comments above about underflow */ + valf = 1; + retval = 0; + } else { + /* We want non-zero valf for any non-zero fraction */ + valf = (uint64_t) (fraction * 0x1p64); + if (valf == 0 && fraction > 0.0) { + valf = 1; + } + } } - fraction = modf(val, &integral); - if (fraction != 0) { - mul_required = 1; + if (retval) { + goto out; } c = *endptr; mul = suffix_mul(c, unit); - if (mul >= 0) { + if (mul > 0) { endptr++; } else { mul = suffix_mul(default_suffix, unit); - assert(mul >= 0); + assert(mul > 0); } - if (mul == 1 && mul_required) { - goto fail; - } - if (((long) (val * mul) >= INT64_MAX) || val < 0) { - goto fail; + if (mul == 1) { + /* When a fraction is present, a scale is required. */ + if (valf != 0) { + endptr = nptr; + retval = -EINVAL; + goto out; + } + } else { + uint64_t valh, tmp; + + /* Compute exact result: 64.64 x 64.0 -> 128.64 fixed point */ + mulu64(&val, &valh, val, mul); + mulu64(&valf, &tmp, valf, mul); + val += tmp; + valh += val < tmp; + + /* Round 0.5 upward. */ + tmp = valf >> 63; + val += tmp; + valh += val < tmp; + + /* Report overflow. */ + if (valh != 0) { + retval = -ERANGE; + goto out; + } } - retval = val * mul; -fail: + retval = 0; + +out: if (end) { *end = endptr; + } else if (nptr && *endptr) { + retval = -EINVAL; + } + if (retval == 0) { + *result = val; + } else { + *result = 0; + if (end && retval == -EINVAL) { + *end = nptr; + } } return retval; } -int64_t strtosz_suffix(const char *nptr, char **end, const char default_suffix) { - return strtosz_suffix_unit(nptr, end, default_suffix, 1024); +int qemu_strtosz(const char *nptr, const char **end, uint64_t *result) { + return do_strtosz(nptr, end, 'B', 1024, result); } -int64_t strtosz(const char *nptr, char **end) { - return strtosz_suffix(nptr, end, STRTOSZ_DEFSUFFIX_MB); +int qemu_strtosz_MiB(const char *nptr, const char **end, uint64_t *result) { + return do_strtosz(nptr, end, 'M', 1024, result); } -void pstrcpy(char *buf, int buf_size, const char *str) { - int c; - char *q = buf; +int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result) { + return do_strtosz(nptr, end, 'B', 1000, result); +} - if (buf_size <= 0) - return; +/** + * Helper function for error checking after strtol() and the like + */ +static int check_strtox_error(const char *nptr, char *ep, const char **endptr, bool check_zero, int libc_errno) { + assert(ep >= nptr); - for (;;) { - c = *str++; - if (c == 0 || q >= buf + buf_size - 1) - break; - *q++ = c; + /* Windows has a bug in that it fails to parse 0 from "0x" in base 16 */ + if (check_zero && ep == nptr && libc_errno == 0) { + char *tmp; + + errno = 0; + if (strtol(nptr, &tmp, 10) == 0 && errno == 0 && (*tmp == 'x' || *tmp == 'X')) { + ep = tmp; + } } - *q = '\0'; + + if (endptr) { + *endptr = ep; + } + + /* Turn "no conversion" into an error */ + if (libc_errno == 0 && ep == nptr) { + return -EINVAL; + } + + /* Fail when we're expected to consume the string, but didn't */ + if (!endptr && *ep) { + return -EINVAL; + } + + return -libc_errno; } -/* strcat and truncate. */ -char *pstrcat(char *buf, int buf_size, const char *s) { - int len; - len = strlen(buf); - if (len < buf_size) - pstrcpy(buf + len, buf_size - len, s); - return buf; +/** + * Convert string @nptr to an integer, and store it in @result. + * + * This is a wrapper around strtol() that is harder to misuse. + * Semantics of @nptr, @endptr, @base match strtol() with differences + * noted below. + * + * @nptr may be null, and no conversion is performed then. + * + * If no conversion is performed, store @nptr in *@endptr, 0 in + * @result, and return -EINVAL. + * + * If @endptr is null, and the string isn't fully converted, return + * -EINVAL with @result set to the parsed value. This is the case + * when the pointer that would be stored in a non-null @endptr points + * to a character other than '\0'. + * + * If the conversion overflows @result, store INT_MAX in @result, + * and return -ERANGE. + * + * If the conversion underflows @result, store INT_MIN in @result, + * and return -ERANGE. + * + * Else store the converted value in @result, and return zero. + * + * This matches the behavior of strtol() on 32-bit platforms, even on + * platforms where long is 64-bits. + */ +int qemu_strtoi(const char *nptr, const char **endptr, int base, int *result) { + char *ep; + long long lresult; + + assert((unsigned) base <= 36 && base != 1); + if (!nptr) { + *result = 0; + if (endptr) { + *endptr = nptr; + } + return -EINVAL; + } + + errno = 0; + lresult = strtoll(nptr, &ep, base); + if (lresult < INT_MIN) { + *result = INT_MIN; + errno = ERANGE; + } else if (lresult > INT_MAX) { + *result = INT_MAX; + errno = ERANGE; + } else { + *result = lresult; + } + return check_strtox_error(nptr, ep, endptr, lresult == 0, errno); +} + +/** + * Convert string @nptr to an unsigned integer, and store it in @result. + * + * This is a wrapper around strtoul() that is harder to misuse. + * Semantics of @nptr, @endptr, @base match strtoul() with differences + * noted below. + * + * @nptr may be null, and no conversion is performed then. + * + * If no conversion is performed, store @nptr in *@endptr, 0 in + * @result, and return -EINVAL. + * + * If @endptr is null, and the string isn't fully converted, return + * -EINVAL with @result set to the parsed value. This is the case + * when the pointer that would be stored in a non-null @endptr points + * to a character other than '\0'. + * + * If the conversion overflows @result, store UINT_MAX in @result, + * and return -ERANGE. + * + * Else store the converted value in @result, and return zero. + * + * Note that a number with a leading minus sign gets converted without + * the minus sign, checked for overflow (see above), then negated (in + * @result's type). This matches the behavior of strtoul() on 32-bit + * platforms, even on platforms where long is 64-bits. + */ +int qemu_strtoui(const char *nptr, const char **endptr, int base, unsigned int *result) { + char *ep; + unsigned long long lresult; + bool neg; + + assert((unsigned) base <= 36 && base != 1); + if (!nptr) { + *result = 0; + if (endptr) { + *endptr = nptr; + } + return -EINVAL; + } + + errno = 0; + lresult = strtoull(nptr, &ep, base); + + /* Windows returns 1 for negative out-of-range values. */ + if (errno == ERANGE) { + *result = -1; + } else { + /* + * Note that platforms with 32-bit strtoul only accept input + * in the range [-4294967295, 4294967295]; but we used 64-bit + * strtoull which wraps -18446744073709551615 to 1 instead of + * declaring overflow. So we must check if '-' was parsed, + * and if so, undo the negation before doing our bounds check. + */ + neg = memchr(nptr, '-', ep - nptr) != NULL; + if (neg) { + lresult = -lresult; + } + if (lresult > UINT_MAX) { + *result = UINT_MAX; + errno = ERANGE; + } else { + *result = neg ? -lresult : lresult; + } + } + return check_strtox_error(nptr, ep, endptr, lresult == 0, errno); +} + +/** + * Convert string @nptr to a long integer, and store it in @result. + * + * This is a wrapper around strtol() that is harder to misuse. + * Semantics of @nptr, @endptr, @base match strtol() with differences + * noted below. + * + * @nptr may be null, and no conversion is performed then. + * + * If no conversion is performed, store @nptr in *@endptr, 0 in + * @result, and return -EINVAL. + * + * If @endptr is null, and the string isn't fully converted, return + * -EINVAL with @result set to the parsed value. This is the case + * when the pointer that would be stored in a non-null @endptr points + * to a character other than '\0'. + * + * If the conversion overflows @result, store LONG_MAX in @result, + * and return -ERANGE. + * + * If the conversion underflows @result, store LONG_MIN in @result, + * and return -ERANGE. + * + * Else store the converted value in @result, and return zero. + */ +int qemu_strtol(const char *nptr, const char **endptr, int base, long *result) { + char *ep; + + assert((unsigned) base <= 36 && base != 1); + if (!nptr) { + *result = 0; + if (endptr) { + *endptr = nptr; + } + return -EINVAL; + } + + errno = 0; + *result = strtol(nptr, &ep, base); + return check_strtox_error(nptr, ep, endptr, *result == 0, errno); +} + +/** + * Convert string @nptr to an unsigned long, and store it in @result. + * + * This is a wrapper around strtoul() that is harder to misuse. + * Semantics of @nptr, @endptr, @base match strtoul() with differences + * noted below. + * + * @nptr may be null, and no conversion is performed then. + * + * If no conversion is performed, store @nptr in *@endptr, 0 in + * @result, and return -EINVAL. + * + * If @endptr is null, and the string isn't fully converted, return + * -EINVAL with @result set to the parsed value. This is the case + * when the pointer that would be stored in a non-null @endptr points + * to a character other than '\0'. + * + * If the conversion overflows @result, store ULONG_MAX in @result, + * and return -ERANGE. + * + * Else store the converted value in @result, and return zero. + * + * Note that a number with a leading minus sign gets converted without + * the minus sign, checked for overflow (see above), then negated (in + * @result's type). This is exactly how strtoul() works. + */ +int qemu_strtoul(const char *nptr, const char **endptr, int base, unsigned long *result) { + char *ep; + + assert((unsigned) base <= 36 && base != 1); + if (!nptr) { + *result = 0; + if (endptr) { + *endptr = nptr; + } + return -EINVAL; + } + + errno = 0; + *result = strtoul(nptr, &ep, base); + /* Windows returns 1 for negative out-of-range values. */ + if (errno == ERANGE) { + *result = -1; + } + return check_strtox_error(nptr, ep, endptr, *result == 0, errno); +} + +/** + * Convert string @nptr to an int64_t. + * + * Works like qemu_strtol(), except it stores INT64_MAX on overflow, + * and INT64_MIN on underflow. + */ +int qemu_strtoi64(const char *nptr, const char **endptr, int base, int64_t *result) { + char *ep; + + assert((unsigned) base <= 36 && base != 1); + if (!nptr) { + *result = 0; + if (endptr) { + *endptr = nptr; + } + return -EINVAL; + } + + /* This assumes int64_t is long long TODO relax */ + QEMU_BUILD_BUG_ON(sizeof(int64_t) != sizeof(long long)); + errno = 0; + *result = strtoll(nptr, &ep, base); + return check_strtox_error(nptr, ep, endptr, *result == 0, errno); +} + +/** + * Convert string @nptr to an uint64_t. + * + * Works like qemu_strtoul(), except it stores UINT64_MAX on overflow. + * (If you want to prohibit negative numbers that wrap around to + * positive, use parse_uint()). + */ +int qemu_strtou64(const char *nptr, const char **endptr, int base, uint64_t *result) { + char *ep; + + assert((unsigned) base <= 36 && base != 1); + if (!nptr) { + *result = 0; + if (endptr) { + *endptr = nptr; + } + return -EINVAL; + } + + /* This assumes uint64_t is unsigned long long TODO relax */ + QEMU_BUILD_BUG_ON(sizeof(uint64_t) != sizeof(unsigned long long)); + errno = 0; + *result = strtoull(nptr, &ep, base); + /* Windows returns 1 for negative out-of-range values. */ + if (errno == ERANGE) { + *result = -1; + } + return check_strtox_error(nptr, ep, endptr, *result == 0, errno); +} + +/** + * Convert string @nptr to a double. + * + * This is a wrapper around strtod() that is harder to misuse. + * Semantics of @nptr and @endptr match strtod() with differences + * noted below. + * + * @nptr may be null, and no conversion is performed then. + * + * If no conversion is performed, store @nptr in *@endptr, +0.0 in + * @result, and return -EINVAL. + * + * If @endptr is null, and the string isn't fully converted, return + * -EINVAL with @result set to the parsed value. This is the case + * when the pointer that would be stored in a non-null @endptr points + * to a character other than '\0'. + * + * If the conversion overflows, store +/-HUGE_VAL in @result, depending + * on the sign, and return -ERANGE. + * + * If the conversion underflows, store +/-0.0 in @result, depending on the + * sign, and return -ERANGE. + * + * Else store the converted value in @result, and return zero. + */ +int qemu_strtod(const char *nptr, const char **endptr, double *result) { + char *ep; + + if (!nptr) { + *result = 0.0; + if (endptr) { + *endptr = nptr; + } + return -EINVAL; + } + + errno = 0; + *result = strtod(nptr, &ep); + return check_strtox_error(nptr, ep, endptr, false, errno); +} + +/** + * Convert string @nptr to a finite double. + * + * Works like qemu_strtod(), except that "NaN", "inf", and strings + * that cause ERANGE overflow errors are rejected with -EINVAL as if + * no conversion is performed, storing 0.0 into @result regardless of + * any sign. -ERANGE failures for underflow still preserve the parsed + * sign. + */ +int qemu_strtod_finite(const char *nptr, const char **endptr, double *result) { + const char *tmp; + int ret; + + ret = qemu_strtod(nptr, &tmp, result); + if (!isfinite(*result)) { + if (endptr) { + *endptr = nptr; + } + *result = 0.0; + ret = -EINVAL; + } else if (endptr) { + *endptr = tmp; + } else if (*tmp) { + ret = -EINVAL; + } + return ret; +} + +/** + * Searches for the first occurrence of 'c' in 's', and returns a pointer + * to the trailing null byte if none was found. + */ +#ifndef HAVE_STRCHRNUL +const char *qemu_strchrnul(const char *s, int c) { + const char *e = strchr(s, c); + if (!e) { + e = s + strlen(s); + } + return e; +} +#endif + +/** + * parse_uint: + * + * @s: String to parse + * @endptr: Destination for pointer to first character not consumed + * @base: integer base, between 2 and 36 inclusive, or 0 + * @value: Destination for parsed integer value + * + * Parse unsigned integer + * + * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional + * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits. + * + * If @s is null, or @s doesn't start with an integer in the syntax + * above, set *@value to 0, *@endptr to @s, and return -EINVAL. + * + * Set *@endptr to point right beyond the parsed integer (even if the integer + * overflows or is negative, all digits will be parsed and *@endptr will + * point right beyond them). If @endptr is %NULL, any trailing character + * instead causes a result of -EINVAL with *@value of 0. + * + * If the integer is negative, set *@value to 0, and return -ERANGE. + * (If you want to allow negative numbers that wrap around within + * bounds, use qemu_strtou64()). + * + * If the integer overflows unsigned long long, set *@value to + * ULLONG_MAX, and return -ERANGE. + * + * Else, set *@value to the parsed integer, and return 0. + */ +int parse_uint(const char *s, const char **endptr, int base, uint64_t *value) { + int r = 0; + char *endp = (char *) s; + unsigned long long val = 0; + + assert((unsigned) base <= 36 && base != 1); + if (!s) { + r = -EINVAL; + goto out; + } + + errno = 0; + val = strtoull(s, &endp, base); + if (errno) { + r = -errno; + goto out; + } + + if (endp == s) { + r = -EINVAL; + goto out; + } + + /* make sure we reject negative numbers: */ + while (qemu_isspace(*s)) { + s++; + } + if (*s == '-') { + val = 0; + r = -ERANGE; + goto out; + } + +out: + *value = val; + if (endptr) { + *endptr = endp; + } else if (s && *endp) { + r = -EINVAL; + *value = 0; + } + return r; +} + +/** + * parse_uint_full: + * + * @s: String to parse + * @base: integer base, between 2 and 36 inclusive, or 0 + * @value: Destination for parsed integer value + * + * Parse unsigned integer from entire string, rejecting any trailing slop. + * + * Shorthand for parse_uint(s, NULL, base, value). + */ +int parse_uint_full(const char *s, int base, uint64_t *value) { + return parse_uint(s, NULL, base, value); +} + +int qemu_parse_fd(const char *param) { + long fd; + char *endptr; + + errno = 0; + fd = strtol(param, &endptr, 10); + if (param == endptr /* no conversion performed */ || errno != 0 /* not representable as long; possibly others */ || + *endptr != '\0' /* final string not empty */ || fd < 0 /* invalid as file descriptor */ || + fd > INT_MAX /* not representable as int */) { + return -1; + } + return fd; +} + +/* + * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128) + * Input is limited to 14-bit numbers + */ +int uleb128_encode_small(uint8_t *out, uint32_t n) { + g_assert(n <= 0x3fff); + if (n < 0x80) { + *out = n; + return 1; + } else { + *out++ = (n & 0x7f) | 0x80; + *out = n >> 7; + return 2; + } +} + +int uleb128_decode_small(const uint8_t *in, uint32_t *n) { + if (!(*in & 0x80)) { + *n = *in; + return 1; + } else { + *n = *in++ & 0x7f; + /* we exceed 14 bit number */ + if (*in & 0x80) { + return -1; + } + *n |= *in << 7; + return 2; + } +} + +const char *si_prefix(unsigned int exp10) { + static const char *prefixes[] = {"a", "f", "p", "n", "u", "m", "", "K", "M", "G", "T", "P", "E"}; + + exp10 += 18; + assert(exp10 % 3 == 0 && exp10 / 3 < ARRAY_SIZE(prefixes)); + return prefixes[exp10 / 3]; +} + +const char *iec_binary_prefix(unsigned int exp2) { + static const char *prefixes[] = {"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei"}; + + assert(exp2 % 10 == 0 && exp2 / 10 < ARRAY_SIZE(prefixes)); + return prefixes[exp2 / 10]; +} + +/* + * Return human readable string for size @val. + * @val can be anything that uint64_t allows (no more than "16 EiB"). + * Use IEC binary units like KiB, MiB, and so forth. + * Caller is responsible for passing it to g_free(). + */ +char *size_to_str(uint64_t val) { + uint64_t div; + int i; + + /* + * The exponent (returned in i) minus one gives us + * floor(log2(val * 1024 / 1000). The correction makes us + * switch to the higher power when the integer part is >= 1000. + * (see e41b509d68afb1f for more info) + */ + frexp(val / (1000.0 / 1024.0), &i); + i = (i - 1) / 10 * 10; + div = 1ULL << i; + + return g_strdup_printf("%0.3g %sB", (double) val / div, iec_binary_prefix(i)); +} + +char *freq_to_str(uint64_t freq_hz) { + double freq = freq_hz; + size_t exp10 = 0; + + while (freq >= 1000.0) { + freq /= 1000.0; + exp10 += 3; + } + + return g_strdup_printf("%0.3g %sHz", freq, si_prefix(exp10)); +} + +int qemu_pstrcmp0(const char **str1, const char **str2) { + return g_strcmp0(*str1, *str2); } diff --git a/libutils/src/utils/hexdump.c b/libutils/src/utils/hexdump.c new file mode 100644 index 000000000..fdde453ab --- /dev/null +++ b/libutils/src/utils/hexdump.c @@ -0,0 +1,112 @@ +/* + * Helper to hexdump a buffer + * + * Copyright (c) 2013 Red Hat, Inc. + * Copyright (c) 2013 Gerd Hoffmann + * Copyright (c) 2013 Peter Crosthwaite + * Copyright (c) 2013 Xilinx, Inc + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + * Contributions after 2012-01-13 are licensed under the terms of the + * GNU GPL, version 2 or (at your option) any later version. + */ + +#include +#include +#include + +static inline char hexdump_nibble(unsigned x) { + return (x < 10 ? '0' : 'a' - 10) + x; +} + +static size_t hexdump_line_length(size_t buf_len, size_t unit_len, size_t block_len) { + size_t est = buf_len * 2; + if (unit_len) { + est += buf_len / unit_len; + } + if (block_len) { + est += buf_len / block_len; + } + return est; +} + +GString *qemu_hexdump_line(GString *str, const void *vbuf, size_t len, size_t unit_len, size_t block_len) { + const uint8_t *buf = vbuf; + size_t u, b; + + if (str == NULL) { + /* Estimate the length of the output to avoid reallocs. */ + str = g_string_sized_new(hexdump_line_length(len, unit_len, block_len) + 1); + } + + for (u = 0, b = 0; len; u++, b++, len--, buf++) { + uint8_t c; + + if (unit_len && u == unit_len) { + g_string_append_c(str, ' '); + u = 0; + } + if (block_len && b == block_len) { + g_string_append_c(str, ' '); + b = 0; + } + + c = *buf; + g_string_append_c(str, hexdump_nibble(c / 16)); + g_string_append_c(str, hexdump_nibble(c % 16)); + } + + return str; +} + +static void asciidump_line(char *line, const void *bufptr, size_t len) { + const char *buf = bufptr; + + for (size_t i = 0; i < len; i++) { + char c = buf[i]; + + if (c < ' ' || c > '~') { + c = '.'; + } + *line++ = c; + } + *line = '\0'; +} + +#define QEMU_HEXDUMP_LINE_BYTES 16 +#define QEMU_HEXDUMP_UNIT 1 +#define QEMU_HEXDUMP_BLOCK 4 + +void qemu_hexdump(FILE *fp, const char *prefix, const void *bufptr, size_t size) { + int width = hexdump_line_length(QEMU_HEXDUMP_LINE_BYTES, QEMU_HEXDUMP_UNIT, QEMU_HEXDUMP_BLOCK); + g_autoptr(GString) str = g_string_sized_new(width + 1); + char ascii[QEMU_HEXDUMP_LINE_BYTES + 1]; + size_t b, len; + + for (b = 0; b < size; b += len) { + len = MIN(size - b, QEMU_HEXDUMP_LINE_BYTES); + + g_string_truncate(str, 0); + qemu_hexdump_line(str, bufptr + b, len, QEMU_HEXDUMP_UNIT, QEMU_HEXDUMP_BLOCK); + asciidump_line(ascii, bufptr + b, len); + + fprintf(fp, "%s: %04zx: %-*s %s\n", prefix, b, width, str->str, ascii); + } +} + +void qemu_hexdump_to_buffer(char *restrict buffer, size_t buffer_size, const uint8_t *restrict data, size_t data_size) { + size_t i; + uint64_t required_buffer_size; + bool overflow = umul64_overflow(data_size, 2, &required_buffer_size); + overflow |= uadd64_overflow(required_buffer_size, 1, &required_buffer_size); + assert(!overflow && buffer_size >= required_buffer_size); + + for (i = 0; i < data_size; i++) { + uint8_t val = data[i]; + *(buffer++) = hexdump_nibble(val >> 4); + *(buffer++) = hexdump_nibble(val & 0xf); + } + *buffer = '\0'; +} diff --git a/libutils/src/utils/memalign.c b/libutils/src/utils/memalign.c index db081eb3c..bcd3bdcee 100644 --- a/libutils/src/utils/memalign.c +++ b/libutils/src/utils/memalign.c @@ -31,8 +31,7 @@ #include #include - -#define CONFIG_POSIX_MEMALIGN +#include void *qemu_try_memalign(size_t alignment, size_t size) { void *ptr; diff --git a/libutils/src/utils/osdep.c b/libutils/src/utils/osdep.c index 136ea75a6..c0bc5e309 100644 --- a/libutils/src/utils/osdep.c +++ b/libutils/src/utils/osdep.c @@ -21,17 +21,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#include -#include -#include -#include -#include -#include +#include +#include #include -#define CONFIG_MADVISE - int qemu_madvise(void *addr, size_t len, int advice) { if (advice == QEMU_MADV_INVALID) { errno = EINVAL; @@ -40,9 +33,14 @@ int qemu_madvise(void *addr, size_t len, int advice) { #if defined(CONFIG_MADVISE) return madvise(addr, len, advice); #elif defined(CONFIG_POSIX_MADVISE) - return posix_madvise(addr, len, advice); + int rc = posix_madvise(addr, len, advice); + if (rc) { + errno = rc; + return -1; + } + return 0; #else - errno = EINVAL; + errno = ENOSYS; return -1; #endif } @@ -56,7 +54,7 @@ static int qemu_mprotect__osdep(void *addr, size_t size, int prot) { if (!VirtualProtect(addr, size, prot, &old_protect)) { g_autofree gchar *emsg = g_win32_error_message(GetLastError()); - fprintf(stderr, ("%s: VirtualProtect failed: %s", __func__, emsg); + fprintf(stderr, "%s: VirtualProtect failed: %s", __func__, emsg); return -1; } return 0; @@ -92,17 +90,3 @@ int qemu_mprotect_none(void *addr, size_t size) { return qemu_mprotect__osdep(addr, size, PROT_NONE); #endif } - -size_t qemu_get_host_physmem(void) { -#ifdef _SC_PHYS_PAGES - long pages = sysconf(_SC_PHYS_PAGES); - if (pages > 0) { - if (pages > SIZE_MAX / qemu_real_host_page_size()) { - return SIZE_MAX; - } else { - return pages * qemu_real_host_page_size(); - } - } -#endif - return 0; -} \ No newline at end of file diff --git a/libutils/src/q/cutils.h b/libutils/src/utils/oslib-posix.c similarity index 55% rename from libutils/src/q/cutils.h rename to libutils/src/utils/oslib-posix.c index f2d65a23c..7cd652338 100644 --- a/libutils/src/q/cutils.h +++ b/libutils/src/utils/oslib-posix.c @@ -1,7 +1,11 @@ /* - * Simple C functions to supplement the C library + * os-posix-lib.c * - * Copyright (c) 2006 Fabrice Bellard + * Copyright (c) 2003-2008 Fabrice Bellard + * Copyright (c) 2010 Red Hat, Inc. + * + * QEMU library functions on POSIX which are shared between QEMU and + * the QEMU tools. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -22,20 +26,18 @@ * THE SOFTWARE. */ -#ifndef LIBQ_CUTILS_H -#define LIBQ_CUTILS_H - -#include - -int libq_strtosz(const char *nptr, const char **end, uint64_t *result); - -int libq_strtoi(const char *nptr, const char **endptr, int base, int *result); -int libq_strtoui(const char *nptr, const char **endptr, int base, unsigned int *result); -int libq_strtol(const char *nptr, const char **endptr, int base, long *result); -int libq_strtoul(const char *nptr, const char **endptr, int base, unsigned long *result); -int libq_strtoi64(const char *nptr, const char **endptr, int base, int64_t *result); -int libq_strtou64(const char *nptr, const char **endptr, int base, uint64_t *result); -int libq_strtod(const char *nptr, const char **endptr, double *result); -int libq_strtod_finite(const char *nptr, const char **endptr, double *result); +#include +size_t qemu_get_host_physmem(void) { +#ifdef _SC_PHYS_PAGES + long pages = sysconf(_SC_PHYS_PAGES); + if (pages > 0) { + if (pages > SIZE_MAX / qemu_real_host_page_size()) { + return SIZE_MAX; + } else { + return pages * qemu_real_host_page_size(); + } + } #endif + return 0; +} diff --git a/scripts/upgrade/README.md b/scripts/upgrade/README.md index ddf85cd86..d19aaa3de 100644 --- a/scripts/upgrade/README.md +++ b/scripts/upgrade/README.md @@ -64,16 +64,26 @@ of those need a human decision. `--apply` writes conflicted files with their conflict markers and lists them at the end, so the tree does not build until they are resolved. -## Hand-written subsets - -Not every file tracks upstream closely. The rows below the "hand written" -marker in each `mapping.tsv` are heavily reduced S2E-specific subsets rather -than vendored copies, and are still v8.1.0-era. They are listed for reference -but want a manual look rather than a mechanical merge: - -- libutils: `utils/memalign.h`, `utils/bitmap.h`, `utils/cutils.{h,c}`, - `utils/osdep.{h,c}`. -- libtcg: `utils/bswap.h`, `utils/log.{h,c}`. +## Hand-written subsets and pruned copies + +Not every file tracks upstream closely: + +- libtcg's `utils/bswap.h` and `utils/log.{h,c}` are heavily reduced + S2E-specific subsets rather than vendored copies, still v8.1.0-era. They are + listed in `mapping.tsv` for reference but want a manual look rather than a + mechanical merge. +- libutils' `utils/cutils.h`, `utils/osdep.h`, `src/utils/cutils.c`, + `src/utils/osdep.c` and `src/utils/oslib-posix.c` are pruned copies: upstream + text with whole sections deleted because they need meson configuration, + `os-posix.h`, the `Error` API, `error_report()` or sockets. The kept sections + are verbatim, so they merge mechanically; a conflict inside a deleted section + is resolved by deleting it again. `merge.sh` reports them like any other row. + `cutils.h` drops the prototypes (`qemu_init_exec_dir`, `get_relocated_path`, + `parse_debug_env`) whose bodies `cutils.c` prunes. + +libutils' `utils/mutex.h` and `utils/spinlock.h` stay S2E-original: upstream's +`qemu/thread.h` drags in `qsp`, `notify`, `trace` and the generated +`config-host.h`, which is far more than the two wrappers replace. ## Deviations that must survive every merge @@ -83,14 +93,29 @@ but want a manual look rather than a mechanical merge: these headers are included from C++. - `utils/bitops.h` wraps `#define BIT(nr)` in `#ifndef BIT`, because `libcpu/include/cpu/kvm.h` also defines it. -- `utils/osdep.h` carries what upstream keeps in `include/qemu/compiler.h` - (`QEMU_FLATTEN`, `QEMU_ALWAYS_INLINE`, `typeof_strip_qual`, ...). When a merge - pulls in code that needs a new compiler macro, add it here. +- `utils/compiler.h` includes `` and `` itself and, in + C++, defines `typeof` as `__typeof__`: upstream's `container_of`, + `QEMU_ALIGN_PTR_*` and `MIN`/`MAX` use GNU C `typeof`, which strict + `-std=c++20` does not have. `utils/osdep.h` additionally redefines `MIN`, + `MAX` and `ARRAY_SIZE` for C++ with the plain forms, since upstream's use + statement expressions and `__builtin_types_compatible_p`, and drops + upstream's `#error` on `NDEBUG` because libtcg and libcpu build with it in + release. - `utils/int128.h` and `utils/osdep.h` include ``, the - S2E-original header that defines `CONFIG_INT128`, `HOST_BIG_ENDIAN` and - `HAVE_GLIB_WITH_SLICE_ALLOCATOR` from compiler builtins. Upstream gets them - from meson through `qemu/osdep.h`; here the header is what keeps every - translation unit, in every component, on the same definitions. + S2E-original header that defines the host configuration macros + (`CONFIG_INT128`, `CONFIG_MADVISE` and the rest) from compiler builtins. + Upstream gets them from meson through `qemu/osdep.h`; here the header is + what keeps every translation unit, in every component, on the same + definitions. `int128.h` also includes `` for + `HOST_BIG_ENDIAN`. +- `utils/cutils.h` spells `restrict` as `__restrict` in + `qemu_hexdump_to_buffer()` and casts the `buffer_is_zero()` argument, so + the header compiles as C++ behind its `extern "C"` guard. +- `src/utils/osdep.c` reports `mprotect` failures with `fprintf(stderr)`, + since libutils has no `error_report()`. +- `utils/madvise.h` includes `` for `CONFIG_MADVISE` and the + `MADV_*` constants; every other vendored header likewise includes what it + needs, because S2E has no `qemu/osdep.h` prelude. - `src/utils/cpuinfo-i386.c` includes `` where upstream includes `qemu/cpuid.h`, and `CONFIG_CPUID_H` stays undefined on purpose; see `utils/config-host.h`. From fc26cfa34d53d3043717828402e0a8bad3059370 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Fri, 21 Aug 2026 17:27:50 +0000 Subject: [PATCH 21/52] libutils: split bswap.h into a host half and a target half libtcg's utils/bswap.h was the last v8.1.0-era hand-written subset besides log.{h,c}. It was target-dependent only through its tswap*() tail, and it still tested HOST_WORDS_BIGENDIAN, which nothing defines. Upstream's include/qemu/bswap.h is host-only until its final section, which needs exec/memop.h (ldm_p/stm_p) and target-info.h (ld*_p/st*_p following target endianness). The file is now split along that line: - libutils' utils/bswap.h is the host half, verbatim minus the two includes and the tail. - libtcg's utils/bswap.h is the MemOp and target-endian half, on top of tcg-memop.h, utils/target-info.h and utils/bswap.h. - libtcg's utils/target-info.h is upstream's declarations plus one S2E block: under COMPILING_PER_TARGET, target_big_endian() is TARGET_BIG_ENDIAN, since S2E has no runtime TargetInfo and ldl_p() and friends sit on libcpu's softmmu paths. The block errors out if the macro is missing, since it expands inside inline functions and would otherwise fail one include order at a time. TARGET_BIG_ENDIAN is defined (0) where upstream's meson would define it: libcpu's generated config-target.h and libtcg's CMake flags. - libtcg's exec/tswap.h is upstream's without the CPUState-based cpu_internal_tswap*(); it replaces the old tswap tail. cpu-all.h drops its lduw_p..stq_p macros, now inline functions from the libtcg half, and keeps only the float ldfl_p/stfq_p mapping, keyed on TARGET_BIG_ENDIAN. exec.c includes for its one tswap64() and optimize.c includes . With bswap.h in libutils, bitmap.{h,c} and bufferiszero.c with its x86_64 bufferiszero.c.inc are vendored too, so every declaration in cutils.h has a definition. CONFIG_AVX2_OPT joins config-host.h behind CONFIG_CPUID_H, the dependency upstream's meson enforces; with CONFIG_CPUID_H left undefined, cpuinfo never reports SSE2/AVX2 and buffer_is_zero() takes the integer path. Both halves map to the same upstream file, so each component's merge reports the other half's changes as a conflict in a deleted section, which is resolved by deleting it again; README and the upgrade skill say so. Co-Authored-By: Claude Fable 5 Signed-off-by: Vitaly Chipounov --- .claude/skills/upgrade-libtcg/SKILL.md | 25 +- libcpu/CMakeLists.txt | 1 + libcpu/src/cpu-all.h | 18 +- libcpu/src/exec.c | 1 + libtcg/include/tcg/exec/tswap.h | 76 +++ libtcg/include/tcg/utils/bswap.h | 378 ++++--------- libtcg/include/tcg/utils/target-info.h | 127 +++++ libtcg/scripts/upgrade/mapping.tsv | 10 +- libtcg/src/CMakeLists.txt | 2 +- libtcg/src/optimize.c | 2 +- libutils/include/utils/bitmap.h | 250 +++++++++ libutils/include/utils/bswap.h | 393 ++++++++++++++ libutils/include/utils/config-host.h | 5 + .../utils/host/x86_64/bufferiszero.c.inc | 131 +++++ libutils/scripts/upgrade/mapping.tsv | 10 +- libutils/src/CMakeLists.txt | 2 + libutils/src/utils/bitmap.c | 499 ++++++++++++++++++ libutils/src/utils/bufferiszero.c | 120 +++++ scripts/upgrade/README.md | 14 +- 19 files changed, 1758 insertions(+), 306 deletions(-) create mode 100644 libtcg/include/tcg/exec/tswap.h create mode 100644 libtcg/include/tcg/utils/target-info.h create mode 100644 libutils/include/utils/bitmap.h create mode 100644 libutils/include/utils/bswap.h create mode 100644 libutils/include/utils/host/x86_64/bufferiszero.c.inc create mode 100644 libutils/src/utils/bitmap.c create mode 100644 libutils/src/utils/bufferiszero.c diff --git a/.claude/skills/upgrade-libtcg/SKILL.md b/.claude/skills/upgrade-libtcg/SKILL.md index e525edcd2..6622a5de4 100644 --- a/.claude/skills/upgrade-libtcg/SKILL.md +++ b/.claude/skills/upgrade-libtcg/SKILL.md @@ -43,16 +43,18 @@ include block or where S2E's `extern "C"` guard meets appended upstream code. git -C ~/qemu log --oneline .. -- tcg/ include/tcg/ util/ include/qemu/ host/include/ **Neither component is uniformly at one version.** The TCG core, `fpu/` and the -vendored utilities track `BASELINE`, but libtcg's hand-written subsets -(`log.*`, `bswap.h`, flagged below the "hand written" marker in its -`mapping.tsv`) are still v8.1.0-era and are not vendored. libutils has no -hand-written subsets left, only pruned copies (`cutils.h`, `osdep.h`, -`cutils.c`, `osdep.c`, `oslib-posix.c`: upstream text with sections deleted), -which merge like any other row. Before assuming a file's baseline, check it: -format the file at several candidate tags and pick the smallest diff. A file -that is stale relative to its neighbors is a bug waiting to happen: the 11.1 -upgrade found `tcg-gvec-desc.h` stranded at an old descriptor encoding while -`simd_desc()` already wrote the new one. +vendored utilities track `BASELINE`, but libtcg's hand-written subset (`log.*`, +flagged below the "hand written" marker in its `mapping.tsv`) is still +v8.1.0-era and is not vendored. libutils has no hand-written subsets left, only +pruned copies (`cutils.h`, `osdep.h`, `bswap.h`, `cutils.c`, `osdep.c`, +`oslib-posix.c`: upstream text with sections deleted), which merge like any +other row. `bswap.h` is split between the two components (host half in +libutils, `MemOp`/target-endian half in libtcg), so each side's merge reports +the other half as a conflict in a deleted section. Before assuming a file's +baseline, check it: format the file at several candidate tags and pick the +smallest diff. A file that is stale relative to its neighbors is a bug waiting +to happen: the 11.1 upgrade found `tcg-gvec-desc.h` stranded at an old +descriptor encoding while `simd_desc()` already wrote the new one. Note deleted, added and renamed files in the upstream range; `merge.sh` reports them but cannot decide what to do about them. @@ -176,6 +178,9 @@ libtcg: that upstream keeps in `include/qemu/cpu-float.h`. Leaving them in `bswap.h` creates a cycle: `softfloat-types.h` -> `registerfields.h` -> `bitops.h` -> `host-utils.h` -> `bswap.h`. +- **`tcg/utils/target-info.h`** defines `target_big_endian()` as + `TARGET_BIG_ENDIAN` under `COMPILING_PER_TARGET`; `TARGET_BIG_ENDIAN` is + defined (0) by libcpu's generated `config-target.h` and libtcg's CMake. - **`accel/getpc.h`** drops upstream's `#ifndef CONFIG_TCG #error` guard. - **`exec/helper-head.h.inc`** keeps its `#ifdef TARGET_LONG_BITS` guard instead of including `exec/target_long.h`. diff --git a/libcpu/CMakeLists.txt b/libcpu/CMakeLists.txt index 90f0501fc..b23bd263d 100644 --- a/libcpu/CMakeLists.txt +++ b/libcpu/CMakeLists.txt @@ -56,6 +56,7 @@ file(WRITE ${CONFIG_TARGET_H} #define TARGET_INT_ALIGNMENT 4 #define TARGET_LLONG_ALIGNMENT 8 #define TARGET_I386 1 +#define TARGET_BIG_ENDIAN 0 #define TARGET_PHYS_ADDR_BITS 64 #define CONFIG_SOFTMMU 1 #define CONFIG_I386_DIS 1 diff --git a/libcpu/src/cpu-all.h b/libcpu/src/cpu-all.h index bcc249b08..564973a1c 100644 --- a/libcpu/src/cpu-all.h +++ b/libcpu/src/cpu-all.h @@ -68,29 +68,15 @@ * kernel : kernel mode access using soft MMU */ -/* target-endianness CPU memory access functions */ -#if defined(TARGET_WORDS_BIGENDIAN) -#define lduw_p(p) lduw_be_p(p) -#define ldsw_p(p) ldsw_be_p(p) -#define ldl_p(p) ldl_be_p(p) -#define ldq_p(p) ldq_be_p(p) +/* target-endianness float access functions; the integer ones come from tcg/utils/bswap.h */ +#if TARGET_BIG_ENDIAN #define ldfl_p(p) ldfl_be_p(p) #define ldfq_p(p) ldfq_be_p(p) -#define stw_p(p, v) stw_be_p(p, v) -#define stl_p(p, v) stl_be_p(p, v) -#define stq_p(p, v) stq_be_p(p, v) #define stfl_p(p, v) stfl_be_p(p, v) #define stfq_p(p, v) stfq_be_p(p, v) #else -#define lduw_p(p) lduw_le_p(p) -#define ldsw_p(p) ldsw_le_p(p) -#define ldl_p(p) ldl_le_p(p) -#define ldq_p(p) ldq_le_p(p) #define ldfl_p(p) ldfl_le_p(p) #define ldfq_p(p) ldfq_le_p(p) -#define stw_p(p, v) stw_le_p(p, v) -#define stl_p(p, v) stl_le_p(p, v) -#define stq_p(p, v) stq_le_p(p, v) #define stfl_p(p, v) stfl_le_p(p, v) #define stfq_p(p, v) stfq_le_p(p, v) #endif diff --git a/libcpu/src/exec.c b/libcpu/src/exec.c index 4ff7dbeb7..cf78f7123 100644 --- a/libcpu/src/exec.c +++ b/libcpu/src/exec.c @@ -22,6 +22,7 @@ #include #include +#include #include #include #include "cpu.h" diff --git a/libtcg/include/tcg/exec/tswap.h b/libtcg/include/tcg/exec/tswap.h new file mode 100644 index 000000000..d1c15909a --- /dev/null +++ b/libtcg/include/tcg/exec/tswap.h @@ -0,0 +1,76 @@ +/* + * Macros for swapping a value if the endianness is different + * between the target and the host. + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifndef TSWAP_H +#define TSWAP_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * If we're in target-specific code, we can hard-code the swapping + * condition, otherwise we have to do (slower) run-time checks. + */ +#ifdef COMPILING_PER_TARGET +#define target_needs_bswap() (HOST_BIG_ENDIAN != TARGET_BIG_ENDIAN) +#else +#define target_needs_bswap() (HOST_BIG_ENDIAN != target_big_endian()) +#endif /* COMPILING_PER_TARGET */ + +#if defined(CONFIG_USER_ONLY) || !defined(TARGET_NOT_USING_LEGACY_NATIVE_ENDIAN_API) +static inline uint16_t tswap16(uint16_t s) { + if (target_needs_bswap()) { + return bswap16(s); + } else { + return s; + } +} + +static inline uint32_t tswap32(uint32_t s) { + if (target_needs_bswap()) { + return bswap32(s); + } else { + return s; + } +} + +static inline uint64_t tswap64(uint64_t s) { + if (target_needs_bswap()) { + return bswap64(s); + } else { + return s; + } +} + +static inline void tswap16s(uint16_t *s) { + if (target_needs_bswap()) { + *s = bswap16(*s); + } +} + +static inline void tswap32s(uint32_t *s) { + if (target_needs_bswap()) { + *s = bswap32(*s); + } +} + +static inline void tswap64s(uint64_t *s) { + if (target_needs_bswap()) { + *s = bswap64(*s); + } +} +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* TSWAP_H */ diff --git a/libtcg/include/tcg/utils/bswap.h b/libtcg/include/tcg/utils/bswap.h index 9db21834c..381d50b6e 100644 --- a/libtcg/include/tcg/utils/bswap.h +++ b/libtcg/include/tcg/utils/bswap.h @@ -1,308 +1,148 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -#ifndef BSWAP_H -#define BSWAP_H - -// #include +/* + * The target-dependent half of QEMU's include/qemu/bswap.h: MemOp and + * target-endian accessors. The host-only half is in utils/bswap.h (libutils). + */ +#ifndef TCG_BSWAP_H +#define TCG_BSWAP_H -#include +#include +#include +#include #ifdef __cplusplus extern "C" { #endif -#ifdef CONFIG_MACHINE_BSWAP_H -#include -#include -#include -#else - -#include - -static inline uint16_t bswap16(uint16_t x) { - return bswap_16(x); -} - -static inline uint32_t bswap32(uint32_t x) { - return bswap_32(x); -} - -static inline uint64_t bswap64(uint64_t x) { - return bswap_64(x); -} - -#endif /* ! CONFIG_MACHINE_BSWAP_H */ - -static inline void bswap16s(uint16_t *s) { - *s = bswap16(*s); -} - -static inline void bswap32s(uint32_t *s) { - *s = bswap32(*s); -} - -static inline void bswap64s(uint64_t *s) { - *s = bswap64(*s); -} - -#if defined(HOST_WORDS_BIGENDIAN) -#define be_bswap(v, size) (v) -#define le_bswap(v, size) bswap##size(v) -#define be_bswaps(v, size) -#define le_bswaps(p, size) *p = bswap##size(*p); -#else -#define le_bswap(v, size) (v) -#define be_bswap(v, size) bswap##size(v) -#define le_bswaps(v, size) -#define be_bswaps(p, size) *p = bswap##size(*p); -#endif - -#define CPU_CONVERT(endian, size, type) \ - static inline type endian##size##_to_cpu(type v) { \ - return endian##_bswap(v, size); \ - } \ - \ - static inline type cpu_to_##endian##size(type v) { \ - return endian##_bswap(v, size); \ - } \ - \ - static inline void endian##size##_to_cpus(type *p) { \ - endian##_bswaps(p, size) \ - } \ - \ - static inline void cpu_to_##endian##size##s(type *p) { \ - endian##_bswaps(p, size) \ - } \ - \ - static inline type endian##size##_to_cpup(const type *p) { \ - return endian##size##_to_cpu(*p); \ - } \ - \ - static inline void cpu_to_##endian##size##w(type *p, type v) { \ - *p = cpu_to_##endian##size(v); \ +/** + * ldm_p: Load value from host memory (byteswapping if necessary) + * + * @ptr: the host pointer to be accessed + * @mop: #MemOp mask containing access size and optional byteswapping + * + * Convert the value stored at @ptr in host memory and byteswap if necessary. + * + * Returns: the converted value. + */ +static inline uint64_t ldm_p(const void *ptr, MemOp mop) { + switch (mop & (MO_SIZE | MO_BSWAP)) { + case MO_8: + return ldub_p(ptr); + case MO_16 | MO_LE: + return lduw_le_p(ptr); + case MO_16 | MO_BE: + return lduw_be_p(ptr); + case MO_32 | MO_LE: + return ldl_le_p(ptr); + case MO_32 | MO_BE: + return ldl_be_p(ptr); + case MO_64 | MO_LE: + return ldq_le_p(ptr); + case MO_64 | MO_BE: + return ldq_be_p(ptr); + default: + g_assert_not_reached(); } - -CPU_CONVERT(be, 16, uint16_t) -CPU_CONVERT(be, 32, uint32_t) -CPU_CONVERT(be, 64, uint64_t) - -CPU_CONVERT(le, 16, uint16_t) -CPU_CONVERT(le, 32, uint32_t) -CPU_CONVERT(le, 64, uint64_t) - -/* unaligned versions (optimized for frequent unaligned accesses)*/ - -#if defined(__i386__) || defined(_ARCH_PPC) - -#define cpu_to_le16wu(p, v) cpu_to_le16w(p, v) -#define cpu_to_le32wu(p, v) cpu_to_le32w(p, v) -#define le16_to_cpupu(p) le16_to_cpup(p) -#define le32_to_cpupu(p) le32_to_cpup(p) -#define be32_to_cpupu(p) be32_to_cpup(p) - -#define cpu_to_be16wu(p, v) cpu_to_be16w(p, v) -#define cpu_to_be32wu(p, v) cpu_to_be32w(p, v) - -#else - -static inline void cpu_to_le16wu(uint16_t *p, uint16_t v) { - uint8_t *p1 = (uint8_t *) p; - - p1[0] = v & 0xff; - p1[1] = v >> 8; -} - -static inline void cpu_to_le32wu(uint32_t *p, uint32_t v) { - uint8_t *p1 = (uint8_t *) p; - - p1[0] = v & 0xff; - p1[1] = v >> 8; - p1[2] = v >> 16; - p1[3] = v >> 24; -} - -static inline uint16_t le16_to_cpupu(const uint16_t *p) { - const uint8_t *p1 = (const uint8_t *) p; - return p1[0] | (p1[1] << 8); -} - -static inline uint32_t le32_to_cpupu(const uint32_t *p) { - const uint8_t *p1 = (const uint8_t *) p; - return p1[0] | (p1[1] << 8) | (p1[2] << 16) | (p1[3] << 24); -} - -static inline uint32_t be32_to_cpupu(const uint32_t *p) { - const uint8_t *p1 = (const uint8_t *) p; - return p1[3] | (p1[2] << 8) | (p1[1] << 16) | (p1[0] << 24); -} - -static inline void cpu_to_be16wu(uint16_t *p, uint16_t v) { - uint8_t *p1 = (uint8_t *) p; - - p1[0] = v >> 8; - p1[1] = v & 0xff; -} - -static inline void cpu_to_be32wu(uint32_t *p, uint32_t v) { - uint8_t *p1 = (uint8_t *) p; - - p1[0] = v >> 24; - p1[1] = v >> 16; - p1[2] = v >> 8; - p1[3] = v & 0xff; -} - -#endif - -#ifdef HOST_WORDS_BIGENDIAN -#define cpu_to_32wu cpu_to_be32wu -#else -#define cpu_to_32wu cpu_to_le32wu -#endif - -#undef le_bswap -#undef be_bswap -#undef le_bswaps -#undef be_bswaps - -static inline int ldub_p(const void *ptr) { - return *(uint8_t *) ptr; -} - -static inline int ldsb_p(const void *ptr) { - return *(int8_t *) ptr; -} - -static inline void stb_p(void *ptr, int v) { - *(uint8_t *) ptr = v; -} - -static inline int lduw_le_p(const void *ptr) { - return *(uint16_t *) ptr; -} - -static inline int ldsw_le_p(const void *ptr) { - return *(int16_t *) ptr; -} - -static inline int ldl_le_p(const void *ptr) { - return *(uint32_t *) ptr; -} - -static inline uint64_t ldq_le_p(const void *ptr) { - return *(uint64_t *) ptr; -} - -static inline void stw_le_p(void *ptr, int v) { - *(uint16_t *) ptr = v; } -static inline void stl_le_p(void *ptr, int v) { - *(uint32_t *) ptr = v; -} - -static inline void stq_le_p(void *ptr, uint64_t v) { - *(uint64_t *) ptr = v; -} - -/* float access */ - -/* some important defines: - * - * WORDS_ALIGNED : if defined, the host cpu can only make word aligned - * memory accesses. +/** + * stm_p: Store value to host memory (byteswapping if necessary) * - * HOST_WORDS_BIGENDIAN : if defined, the host cpu is big endian and - * otherwise little endian. + * @ptr: the host pointer to be accessed + * @mop: #MemOp mask containing access size and optional byteswapping + * @val: the value to store * - * (TARGET_WORDS_ALIGNED : same for target cpu (not supported yet)) - * - * TARGET_WORDS_BIGENDIAN : same for target cpu + * Convert the value (byteswap if necessary) and store at @ptr in host memory. */ - -#if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN) -#define BSWAP_NEEDED -#endif - -#ifdef BSWAP_NEEDED - -static inline uint16_t tswap16(uint16_t s) { - return bswap16(s); +static inline void stm_p(void *ptr, MemOp mop, uint64_t val) { + switch (mop & (MO_SIZE | MO_BSWAP)) { + case MO_8: + stb_p(ptr, val); + break; + case MO_16 | MO_LE: + stw_le_p(ptr, val); + break; + case MO_16 | MO_BE: + stw_be_p(ptr, val); + break; + case MO_32 | MO_LE: + stl_le_p(ptr, val); + break; + case MO_32 | MO_BE: + stl_be_p(ptr, val); + break; + case MO_64 | MO_LE: + stq_le_p(ptr, val); + break; + case MO_64 | MO_BE: + stq_be_p(ptr, val); + break; + default: + g_assert_not_reached(); + } } -static inline uint32_t tswap32(uint32_t s) { - return bswap32(s); -} +/* Return ld{word}_{le,be}_p following target endianness. */ +#define LOAD_IMPL(word, args...) \ + do { \ + if (target_big_endian()) { \ + return glue(glue(ld, word), _be_p)(args); \ + } else { \ + return glue(glue(ld, word), _le_p)(args); \ + } \ + } while (0) -static inline uint64_t tswap64(uint64_t s) { - return bswap64(s); +static inline int lduw_p(const void *ptr) { + LOAD_IMPL(uw, ptr); } -static inline void tswap16s(uint16_t *s) { - *s = bswap16(*s); +static inline int ldsw_p(const void *ptr) { + LOAD_IMPL(sw, ptr); } -static inline void tswap32s(uint32_t *s) { - *s = bswap32(*s); +static inline int ldl_p(const void *ptr) { + LOAD_IMPL(l, ptr); } -static inline void tswap64s(uint64_t *s) { - *s = bswap64(*s); +static inline uint64_t ldq_p(const void *ptr) { + LOAD_IMPL(q, ptr); } -#else - -static inline uint16_t tswap16(uint16_t s) { - return s; +static inline uint64_t ldn_p(const void *ptr, int sz) { + LOAD_IMPL(n, ptr, sz); } -static inline uint32_t tswap32(uint32_t s) { - return s; -} +#undef LOAD_IMPL -static inline uint64_t tswap64(uint64_t s) { - return s; -} +/* Call st{word}_{le,be}_p following target endianness. */ +#define STORE_IMPL(word, args...) \ + do { \ + if (target_big_endian()) { \ + glue(glue(st, word), _be_p)(args); \ + } else { \ + glue(glue(st, word), _le_p)(args); \ + } \ + } while (0) -static inline void tswap16s(uint16_t *s) { +static inline void stw_p(void *ptr, uint16_t v) { + STORE_IMPL(w, ptr, v); } -static inline void tswap32s(uint32_t *s) { +static inline void stl_p(void *ptr, uint32_t v) { + STORE_IMPL(l, ptr, v); } -static inline void tswap64s(uint64_t *s) { +static inline void stq_p(void *ptr, uint64_t v) { + STORE_IMPL(q, ptr, v); } -#endif +static inline void stn_p(void *ptr, int sz, uint64_t v) { + STORE_IMPL(n, ptr, sz, v); +} -#if TARGET_LONG_SIZE == 4 -#define tswapl(s) tswap32(s) -#define tswapls(s) tswap32s((uint32_t *) (s)) -#define bswaptls(s) bswap32s(s) -#else -#define tswapl(s) tswap64(s) -#define tswapls(s) tswap64s((uint64_t *) (s)) -#define bswaptls(s) bswap64s(s) -#endif +#undef STORE_IMPL #ifdef __cplusplus } #endif -#endif /* BSWAP_H */ +#endif /* TCG_BSWAP_H */ diff --git a/libtcg/include/tcg/utils/target-info.h b/libtcg/include/tcg/utils/target-info.h new file mode 100644 index 000000000..516744f3f --- /dev/null +++ b/libtcg/include/tcg/utils/target-info.h @@ -0,0 +1,127 @@ +/* + * QEMU target info API (returning native types) + * + * Copyright (c) Linaro + * + * SPDX-License-Identifier: GPL-2.0-or-later + */ + +#ifndef QEMU_TARGET_INFO_H +#define QEMU_TARGET_INFO_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * target_name: + * + * Returns: Canonical target name (i.e. "i386"). + */ +const char *target_name(void); + +/** + * target_long_bits: + * + * Returns: number of bits in a long type for this target (i.e. 64). + */ +unsigned target_long_bits(void); + +/** + * target_machine_typename: + * + * Returns: Name of the QOM interface implemented by machines + * usable on this target binary. + */ +const char *target_machine_typename(void); + +/** + * target_cpu_type: + * + * Returns: target CPU base QOM type name (i.e. TYPE_X86_CPU). + */ +const char *target_cpu_type(void); + +/** + * target_big_endian: + * + * Returns: %true if the (default) endianness of the target is big endian, + * %false otherwise. + * + * Common code should normally never need to know about the endianness of + * the target, so please do *not* use this function unless you know very + * well what you are doing! + */ +bool target_big_endian(void); + +/** + * target_base_arm: + * + * Returns whether the target architecture is ARM or Aarch64. + */ +bool target_base_arm(void); + +/** + * target_arm: + * + * Returns whether the target architecture is ARM (32-bit, not Aarch64). + */ +bool target_arm(void); + +/** + * target_aarch64: + * + * Returns whether the target architecture is Aarch64. + */ +bool target_aarch64(void); + +/** + * target_base_ppc: + * + * Returns whether the target architecture is PowerPC 32-bit or 64-bit. + */ +bool target_base_ppc(void); + +/** + * target_ppc: + * + * Returns whether the target architecture is PowerPC 32-bit. + */ +bool target_ppc(void); + +/** + * target_ppc64: + * + * Returns whether the target architecture is PowerPC 64-bit. + */ +bool target_ppc64(void); + +/** + * target_s390x: + * + * Returns whether the target architecture is S390x. + */ +bool target_s390x(void); + +/** + * target_riscv64: + * + * Returns whether the target architecture is riscv64 + */ +bool target_riscv64(void); + +#ifdef COMPILING_PER_TARGET +/* S2E has no runtime TargetInfo: every component is built per target. */ +#ifndef TARGET_BIG_ENDIAN +#error "TARGET_BIG_ENDIAN must be defined (cpu/config-target.h or -D) before tcg/utils/target-info.h" +#endif +#define target_big_endian() (TARGET_BIG_ENDIAN) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* QEMU_TARGET_INFO_H */ diff --git a/libtcg/scripts/upgrade/mapping.tsv b/libtcg/scripts/upgrade/mapping.tsv index 7db5ba164..d18b97ee6 100644 --- a/libtcg/scripts/upgrade/mapping.tsv +++ b/libtcg/scripts/upgrade/mapping.tsv @@ -65,13 +65,17 @@ src/atomic_common.c.inc accel/tcg/atomic_common.c.inc src/atomic_template.h accel/tcg/atomic_template.h # --- target-dependent utilities ----------------------------------------- # What is left of the old utils/ subset: everything platform-independent -# moved to libutils. cpu-float.h needs the softfloat types, and bswap.h and -# log.c test TARGET_* / CONFIG_SYMBEX macros, so all three stay here. +# moved to libutils. cpu-float.h needs the softfloat types, bswap.h is the +# MemOp and target-endian half of upstream's (the host half is libutils' +# utils/bswap.h), target-info.h answers target_big_endian() at compile time, +# and log.c tests TARGET_* / CONFIG_SYMBEX macros. include/tcg/utils/cpu-float.h include/qemu/cpu-float.h +include/tcg/utils/bswap.h include/qemu/bswap.h +include/tcg/utils/target-info.h include/qemu/target-info.h +include/tcg/exec/tswap.h include/exec/tswap.h src/elf.h include/elf.h # Heavily reduced S2E-specific subsets, still v8.1.0-era: these are hand # written rather than vendored, so merge by hand, not mechanically. -include/tcg/utils/bswap.h include/qemu/bswap.h include/tcg/utils/log.h include/qemu/log.h src/utils/log.c util/log.c # --- fpu ---------------------------------------------------------------- diff --git a/libtcg/src/CMakeLists.txt b/libtcg/src/CMakeLists.txt index e20806a60..9951d296a 100644 --- a/libtcg/src/CMakeLists.txt +++ b/libtcg/src/CMakeLists.txt @@ -34,7 +34,7 @@ endif (WITH_SYMBEX) add_library(tcg ${TCG_SOURCES}) set (COMMON_FLAGS "-Wall -fPIC -Werror -Wno-zero-length-array -Wno-mismatched-tags -Wno-initializer-overrides") -set (COMMON_FLAGS "${COMMON_FLAGS} -DCOMPILING_PER_TARGET -DCONFIG_SOFTMMU -DCPU_TEMP_BUF_NLONGS=128") +set (COMMON_FLAGS "${COMMON_FLAGS} -DCOMPILING_PER_TARGET -DCONFIG_SOFTMMU -DCPU_TEMP_BUF_NLONGS=128 -DTARGET_BIG_ENDIAN=0") if (WITH_SYMBEX) set (COMMON_FLAGS "${COMMON_FLAGS} -DCONFIG_SYMBEX -DTCG_ENABLE_MEM_TRACING") diff --git a/libtcg/src/optimize.c b/libtcg/src/optimize.c index 481575a82..71c9191dd 100644 --- a/libtcg/src/optimize.c +++ b/libtcg/src/optimize.c @@ -25,7 +25,7 @@ #include -#include "tcg/utils/bswap.h" +#include #include "utils/int128.h" #include "utils/interval-tree.h" #include "utils/osdep.h" diff --git a/libutils/include/utils/bitmap.h b/libutils/include/utils/bitmap.h new file mode 100644 index 000000000..44354300f --- /dev/null +++ b/libutils/include/utils/bitmap.h @@ -0,0 +1,250 @@ +/* + * Bitmap Module + * + * Copyright (C) 2010 Corentin Chary + * + * Mostly inspired by (stolen from) linux/bitmap.h and linux/bitops.h + * + * This work is licensed under the terms of the GNU LGPL, version 2.1 or later. + * See the COPYING.LIB file in the top-level directory. + */ + +#ifndef BITMAP_H +#define BITMAP_H + +#include "bitops.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * The available bitmap operations and their rough meaning in the + * case that the bitmap is a single unsigned long are thus: + * + * Note that nbits should be always a compile time evaluable constant. + * Otherwise many inlines will generate horrible code. + * + * bitmap_zero(dst, nbits) *dst = 0UL + * bitmap_fill(dst, nbits) *dst = ~0UL + * bitmap_copy(dst, src, nbits) *dst = *src + * bitmap_and(dst, src1, src2, nbits) *dst = *src1 & *src2 + * bitmap_or(dst, src1, src2, nbits) *dst = *src1 | *src2 + * bitmap_xor(dst, src1, src2, nbits) *dst = *src1 ^ *src2 + * bitmap_andnot(dst, src1, src2, nbits) *dst = *src1 & ~(*src2) + * bitmap_complement(dst, src, nbits) *dst = ~(*src) + * bitmap_equal(src1, src2, nbits) Are *src1 and *src2 equal? + * bitmap_intersects(src1, src2, nbits) Do *src1 and *src2 overlap? + * bitmap_empty(src, nbits) Are all bits zero in *src? + * bitmap_full(src, nbits) Are all bits set in *src? + * bitmap_set(dst, pos, nbits) Set specified bit area + * bitmap_set_atomic(dst, pos, nbits) Set specified bit area with atomic ops + * bitmap_clear(dst, pos, nbits) Clear specified bit area + * bitmap_test_and_clear_atomic(dst, pos, nbits) Test and clear area + * bitmap_find_next_zero_area(buf, len, pos, n, mask) Find bit free area + * bitmap_to_le(dst, src, nbits) Convert bitmap to little endian + * bitmap_from_le(dst, src, nbits) Convert bitmap from little endian + * bitmap_copy_with_src_offset(dst, src, offset, nbits) + * *dst = *src (with an offset into src) + * bitmap_copy_with_dst_offset(dst, src, offset, nbits) + * *dst = *src (with an offset into dst) + */ + +/* + * Also the following operations apply to bitmaps. + * + * set_bit(bit, addr) *addr |= bit + * clear_bit(bit, addr) *addr &= ~bit + * change_bit(bit, addr) *addr ^= bit + * test_bit(bit, addr) Is bit set in *addr? + * test_and_set_bit(bit, addr) Set bit and return old value + * test_and_clear_bit(bit, addr) Clear bit and return old value + * test_and_change_bit(bit, addr) Change bit and return old value + * find_first_zero_bit(addr, nbits) Position first zero bit in *addr + * find_first_bit(addr, nbits) Position first set bit in *addr + * find_next_zero_bit(addr, nbits, bit) Position next zero bit in *addr >= bit + * find_next_bit(addr, nbits, bit) Position next set bit in *addr >= bit + */ + +#define BITMAP_FIRST_WORD_MASK(start) (~0UL << ((start) & (BITS_PER_LONG - 1))) +#define BITMAP_LAST_WORD_MASK(nbits) (~0UL >> (-(nbits) & (BITS_PER_LONG - 1))) + +#define DECLARE_BITMAP(name, bits) unsigned long name[BITS_TO_LONGS(bits)] + +/* + * This is for use with the bit32 versions of set_bit() etc; + * we don't currently support the full range of bitmap operations + * on bitmaps backed by an array of uint32_t. + */ +#define DECLARE_BITMAP32(name, bits) uint32_t name[BITS_TO_U32S(bits)] + +#define small_nbits(nbits) ((nbits) <= BITS_PER_LONG) + +int slow_bitmap_empty(const unsigned long *bitmap, long bits); +int slow_bitmap_full(const unsigned long *bitmap, long bits); +int slow_bitmap_equal(const unsigned long *bitmap1, const unsigned long *bitmap2, long bits); +void slow_bitmap_complement(unsigned long *dst, const unsigned long *src, long bits); +int slow_bitmap_and(unsigned long *dst, const unsigned long *bitmap1, const unsigned long *bitmap2, long bits); +void slow_bitmap_or(unsigned long *dst, const unsigned long *bitmap1, const unsigned long *bitmap2, long bits); +void slow_bitmap_xor(unsigned long *dst, const unsigned long *bitmap1, const unsigned long *bitmap2, long bits); +int slow_bitmap_andnot(unsigned long *dst, const unsigned long *bitmap1, const unsigned long *bitmap2, long bits); +int slow_bitmap_intersects(const unsigned long *bitmap1, const unsigned long *bitmap2, long bits); +long slow_bitmap_count_one(const unsigned long *bitmap, long nbits); + +static inline unsigned long *bitmap_try_new(long nbits) { + long nelem = BITS_TO_LONGS(nbits); + return g_try_new0(unsigned long, nelem); +} + +static inline unsigned long *bitmap_new(long nbits) { + long nelem = BITS_TO_LONGS(nbits); + return g_new0(unsigned long, nelem); +} + +static inline void bitmap_zero(unsigned long *dst, long nbits) { + if (small_nbits(nbits)) { + *dst = 0UL; + } else { + long len = BITS_TO_LONGS(nbits) * sizeof(unsigned long); + memset(dst, 0, len); + } +} + +static inline void bitmap_fill(unsigned long *dst, long nbits) { + size_t nlongs = BITS_TO_LONGS(nbits); + if (!small_nbits(nbits)) { + long len = (nlongs - 1) * sizeof(unsigned long); + memset(dst, 0xff, len); + } + dst[nlongs - 1] = BITMAP_LAST_WORD_MASK(nbits); +} + +static inline void bitmap_copy(unsigned long *dst, const unsigned long *src, long nbits) { + if (small_nbits(nbits)) { + *dst = *src; + } else { + long len = BITS_TO_LONGS(nbits) * sizeof(unsigned long); + memcpy(dst, src, len); + } +} + +static inline int bitmap_and(unsigned long *dst, const unsigned long *src1, const unsigned long *src2, long nbits) { + if (small_nbits(nbits)) { + return (*dst = *src1 & *src2) != 0; + } + return slow_bitmap_and(dst, src1, src2, nbits); +} + +static inline void bitmap_or(unsigned long *dst, const unsigned long *src1, const unsigned long *src2, long nbits) { + if (small_nbits(nbits)) { + *dst = *src1 | *src2; + } else { + slow_bitmap_or(dst, src1, src2, nbits); + } +} + +static inline void bitmap_xor(unsigned long *dst, const unsigned long *src1, const unsigned long *src2, long nbits) { + if (small_nbits(nbits)) { + *dst = *src1 ^ *src2; + } else { + slow_bitmap_xor(dst, src1, src2, nbits); + } +} + +static inline int bitmap_andnot(unsigned long *dst, const unsigned long *src1, const unsigned long *src2, long nbits) { + if (small_nbits(nbits)) { + return (*dst = *src1 & ~(*src2)) != 0; + } + return slow_bitmap_andnot(dst, src1, src2, nbits); +} + +static inline void bitmap_complement(unsigned long *dst, const unsigned long *src, long nbits) { + if (small_nbits(nbits)) { + *dst = ~(*src) & BITMAP_LAST_WORD_MASK(nbits); + } else { + slow_bitmap_complement(dst, src, nbits); + } +} + +static inline int bitmap_equal(const unsigned long *src1, const unsigned long *src2, long nbits) { + if (small_nbits(nbits)) { + return !((*src1 ^ *src2) & BITMAP_LAST_WORD_MASK(nbits)); + } else { + return slow_bitmap_equal(src1, src2, nbits); + } +} + +static inline int bitmap_empty(const unsigned long *src, long nbits) { + if (small_nbits(nbits)) { + return !(*src & BITMAP_LAST_WORD_MASK(nbits)); + } else { + return slow_bitmap_empty(src, nbits); + } +} + +static inline int bitmap_full(const unsigned long *src, long nbits) { + if (small_nbits(nbits)) { + return !(~(*src) & BITMAP_LAST_WORD_MASK(nbits)); + } else { + return slow_bitmap_full(src, nbits); + } +} + +static inline int bitmap_intersects(const unsigned long *src1, const unsigned long *src2, long nbits) { + if (small_nbits(nbits)) { + return ((*src1 & *src2) & BITMAP_LAST_WORD_MASK(nbits)) != 0; + } else { + return slow_bitmap_intersects(src1, src2, nbits); + } +} + +static inline long bitmap_count_one(const unsigned long *bitmap, long nbits) { + if (unlikely(!nbits)) { + return 0; + } + + if (small_nbits(nbits)) { + return ctpopl(*bitmap & BITMAP_LAST_WORD_MASK(nbits)); + } else { + return slow_bitmap_count_one(bitmap, nbits); + } +} + +static inline long bitmap_count_one_with_offset(const unsigned long *bitmap, long offset, long nbits) { + long aligned_offset = QEMU_ALIGN_DOWN(offset, BITS_PER_LONG); + long redundant_bits = offset - aligned_offset; + long bits_to_count = nbits + redundant_bits; + const unsigned long *bitmap_start = bitmap + aligned_offset / BITS_PER_LONG; + + return bitmap_count_one(bitmap_start, bits_to_count) - bitmap_count_one(bitmap_start, redundant_bits); +} + +void bitmap_set(unsigned long *map, long i, long len); +void bitmap_set_atomic(unsigned long *map, long i, long len); +void bitmap_clear(unsigned long *map, long start, long nr); +bool bitmap_test_and_clear_atomic(unsigned long *map, long start, long nr); +bool bitmap_test_and_clear(unsigned long *map, long start, long nr); +void bitmap_copy_and_clear_atomic(unsigned long *dst, unsigned long *src, long nr); +unsigned long bitmap_find_next_zero_area(unsigned long *map, unsigned long size, unsigned long start, unsigned long nr, + unsigned long align_mask); + +static inline unsigned long *bitmap_zero_extend(unsigned long *old, long old_nbits, long new_nbits) { + long new_nelem = BITS_TO_LONGS(new_nbits); + unsigned long *ptr = g_renew(unsigned long, old, new_nelem); + bitmap_clear(ptr, old_nbits, new_nbits - old_nbits); + return ptr; +} + +void bitmap_to_le(unsigned long *dst, const unsigned long *src, long nbits); +void bitmap_from_le(unsigned long *dst, const unsigned long *src, long nbits); + +void bitmap_copy_with_src_offset(unsigned long *dst, const unsigned long *src, unsigned long offset, + unsigned long nbits); +void bitmap_copy_with_dst_offset(unsigned long *dst, const unsigned long *src, unsigned long shift, + unsigned long nbits); + +#ifdef __cplusplus +} +#endif + +#endif /* BITMAP_H */ diff --git a/libutils/include/utils/bswap.h b/libutils/include/utils/bswap.h new file mode 100644 index 000000000..292819347 --- /dev/null +++ b/libutils/include/utils/bswap.h @@ -0,0 +1,393 @@ +#ifndef BSWAP_H +#define BSWAP_H + +#include +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#undef bswap16 +#define bswap16(_x) __builtin_bswap16(_x) +#undef bswap32 +#define bswap32(_x) __builtin_bswap32(_x) +#undef bswap64 +#define bswap64(_x) __builtin_bswap64(_x) + +static inline uint32_t bswap24(uint32_t x) { + return (((x & 0x000000ffU) << 16) | ((x & 0x0000ff00U) << 0) | ((x & 0x00ff0000U) >> 16)); +} + +static inline void bswap16s(uint16_t *s) { + *s = __builtin_bswap16(*s); +} + +static inline void bswap24s(uint32_t *s) { + *s = bswap24(*s & 0x00ffffffU); +} + +static inline void bswap32s(uint32_t *s) { + *s = __builtin_bswap32(*s); +} + +static inline void bswap64s(uint64_t *s) { + *s = __builtin_bswap64(*s); +} + +#if HOST_BIG_ENDIAN +#define be_bswap(v, size) (v) +#define le_bswap(v, size) glue(__builtin_bswap, size)(v) +#define be_bswap24(v) (v) +#define le_bswap24(v) bswap24(v) +#define be_bswaps(v, size) +#define le_bswaps(p, size) \ + do { \ + *p = glue(__builtin_bswap, size)(*p); \ + } while (0) +#else +#define le_bswap(v, size) (v) +#define be_bswap24(v) bswap24(v) +#define le_bswap24(v) (v) +#define be_bswap(v, size) glue(__builtin_bswap, size)(v) +#define le_bswaps(v, size) +#define be_bswaps(p, size) \ + do { \ + *p = glue(__builtin_bswap, size)(*p); \ + } while (0) +#endif + +/** + * Endianness conversion functions between host cpu and specified endianness. + * (We list the complete set of prototypes produced by the macros below + * to assist people who search the headers to find their definitions.) + * + * uint16_t le16_to_cpu(uint16_t v); + * uint32_t le32_to_cpu(uint32_t v); + * uint64_t le64_to_cpu(uint64_t v); + * uint16_t be16_to_cpu(uint16_t v); + * uint32_t be32_to_cpu(uint32_t v); + * uint64_t be64_to_cpu(uint64_t v); + * + * Convert the value @v from the specified format to the native + * endianness of the host CPU by byteswapping if necessary, and + * return the converted value. + * + * uint16_t cpu_to_le16(uint16_t v); + * uint32_t cpu_to_le32(uint32_t v); + * uint64_t cpu_to_le64(uint64_t v); + * uint16_t cpu_to_be16(uint16_t v); + * uint32_t cpu_to_be32(uint32_t v); + * uint64_t cpu_to_be64(uint64_t v); + * + * Convert the value @v from the native endianness of the host CPU to + * the specified format by byteswapping if necessary, and return + * the converted value. + * + * void le16_to_cpus(uint16_t *v); + * void le32_to_cpus(uint32_t *v); + * void le64_to_cpus(uint64_t *v); + * void be16_to_cpus(uint16_t *v); + * void be32_to_cpus(uint32_t *v); + * void be64_to_cpus(uint64_t *v); + * + * Do an in-place conversion of the value pointed to by @v from the + * specified format to the native endianness of the host CPU. + * + * void cpu_to_le16s(uint16_t *v); + * void cpu_to_le32s(uint32_t *v); + * void cpu_to_le64s(uint64_t *v); + * void cpu_to_be16s(uint16_t *v); + * void cpu_to_be32s(uint32_t *v); + * void cpu_to_be64s(uint64_t *v); + * + * Do an in-place conversion of the value pointed to by @v from the + * native endianness of the host CPU to the specified format. + * + * Both X_to_cpu() and cpu_to_X() perform the same operation; you + * should use whichever one is better documenting of the function your + * code is performing. + * + * Do not use these functions for conversion of values which are in guest + * memory, since the data may not be sufficiently aligned for the host CPU's + * load and store instructions. Instead you should use the ld*_p() and + * st*_p() functions, which perform loads and stores of data of any + * required size and endianness and handle possible misalignment. + */ + +#define CPU_CONVERT(endian, size, type) \ + static inline type endian##size##_to_cpu(type v) { \ + return glue(endian, _bswap)(v, size); \ + } \ + \ + static inline type cpu_to_##endian##size(type v) { \ + return glue(endian, _bswap)(v, size); \ + } \ + \ + static inline void endian##size##_to_cpus(type *p) { \ + glue(endian, _bswaps)(p, size); \ + } \ + \ + static inline void cpu_to_##endian##size##s(type *p) { \ + glue(endian, _bswaps)(p, size); \ + } + +CPU_CONVERT(be, 16, uint16_t) +CPU_CONVERT(be, 32, uint32_t) +CPU_CONVERT(be, 64, uint64_t) + +CPU_CONVERT(le, 16, uint16_t) +CPU_CONVERT(le, 32, uint32_t) +CPU_CONVERT(le, 64, uint64_t) + +#undef CPU_CONVERT + +/* + * Same as cpu_to_le{16,32,64}, except that gcc will figure the result is + * a compile-time constant if you pass in a constant. So this can be + * used to initialize static variables. + */ +#if HOST_BIG_ENDIAN +#define const_le64(_x) \ + ((((_x) & 0x00000000000000ffULL) << 56) | (((_x) & 0x000000000000ff00ULL) << 40) | \ + (((_x) & 0x0000000000ff0000ULL) << 24) | (((_x) & 0x00000000ff000000ULL) << 8) | \ + (((_x) & 0x000000ff00000000ULL) >> 8) | (((_x) & 0x0000ff0000000000ULL) >> 24) | \ + (((_x) & 0x00ff000000000000ULL) >> 40) | (((_x) & 0xff00000000000000ULL) >> 56)) +#define const_le32(_x) \ + ((((_x) & 0x000000ffU) << 24) | (((_x) & 0x0000ff00U) << 8) | (((_x) & 0x00ff0000U) >> 8) | \ + (((_x) & 0xff000000U) >> 24)) +#define const_le16(_x) ((((_x) & 0x00ff) << 8) | (((_x) & 0xff00) >> 8)) +#else +#define const_le64(_x) (_x) +#define const_le32(_x) (_x) +#define const_le16(_x) (_x) +#endif + +/* unaligned/endian-independent pointer access */ + +/* + * the generic syntax is: + * + * load: ld{type}{sign}{size}_{endian}_p(ptr) + * + * store: st{type}{size}_{endian}_p(ptr, val) + * + * Note there are small differences with the softmmu access API! + * + * type is: + * (empty): integer access + * f : float access + * + * sign is: + * (empty): for 32 or 64 bit sizes (including floats and doubles) + * u : unsigned + * s : signed + * + * size is: + * b: 8 bits + * w: 16 bits + * 24: 24 bits + * l: 32 bits + * q: 64 bits + * + * endian is: + * he : host endian + * be : big endian + * le : little endian + * te : target endian + * (except for byte accesses, which have no endian infix). + * + * In all cases these functions take a host pointer. + * For accessors that take a guest address rather than a + * host address, see the cpu_{ld,st}_* accessors defined in + * cpu_ldst.h. + * + * For cases where the size to be used is not fixed at compile time, + * there are + * stn_{endian}_p(ptr, sz, val) + * which stores @val to @ptr as an @endian-order number @sz bytes in size + * and + * ldn_{endian}_p(ptr, sz) + * which loads @sz bytes from @ptr as an unsigned @endian-order number + * and returns it in a uint64_t. + */ + +static inline int ldub_p(const void *ptr) { + return *(uint8_t *) ptr; +} + +static inline int ldsb_p(const void *ptr) { + return *(int8_t *) ptr; +} + +static inline void stb_p(void *ptr, uint8_t v) { + *(uint8_t *) ptr = v; +} + +/* + * Any compiler worth its salt will turn these memcpy into native unaligned + * operations. Thus we don't need to play games with packed attributes, or + * inline byte-by-byte stores. + * Some compilation environments (eg some fortify-source implementations) + * may intercept memcpy() in a way that defeats the compiler optimization, + * though, so we use __builtin_memcpy() to give ourselves the best chance + * of good performance. + */ + +static inline int lduw_he_p(const void *ptr) { + uint16_t r; + __builtin_memcpy(&r, ptr, sizeof(r)); + return r; +} + +static inline int ldsw_he_p(const void *ptr) { + int16_t r; + __builtin_memcpy(&r, ptr, sizeof(r)); + return r; +} + +static inline void stw_he_p(void *ptr, uint16_t v) { + __builtin_memcpy(ptr, &v, sizeof(v)); +} + +static inline void st24_he_p(void *ptr, uint32_t v) { + __builtin_memcpy(ptr, &v, 3); +} + +static inline int ldl_he_p(const void *ptr) { + int32_t r; + __builtin_memcpy(&r, ptr, sizeof(r)); + return r; +} + +static inline void stl_he_p(void *ptr, uint32_t v) { + __builtin_memcpy(ptr, &v, sizeof(v)); +} + +static inline uint64_t ldq_he_p(const void *ptr) { + uint64_t r; + __builtin_memcpy(&r, ptr, sizeof(r)); + return r; +} + +static inline void stq_he_p(void *ptr, uint64_t v) { + __builtin_memcpy(ptr, &v, sizeof(v)); +} + +static inline int lduw_le_p(const void *ptr) { + return (uint16_t) le_bswap(lduw_he_p(ptr), 16); +} + +static inline int ldsw_le_p(const void *ptr) { + return (int16_t) le_bswap(lduw_he_p(ptr), 16); +} + +static inline int ldl_le_p(const void *ptr) { + return le_bswap(ldl_he_p(ptr), 32); +} + +static inline uint64_t ldq_le_p(const void *ptr) { + return le_bswap(ldq_he_p(ptr), 64); +} + +static inline void stw_le_p(void *ptr, uint16_t v) { + stw_he_p(ptr, le_bswap(v, 16)); +} + +static inline void st24_le_p(void *ptr, uint32_t v) { + st24_he_p(ptr, le_bswap24(v)); +} + +static inline void stl_le_p(void *ptr, uint32_t v) { + stl_he_p(ptr, le_bswap(v, 32)); +} + +static inline void stq_le_p(void *ptr, uint64_t v) { + stq_he_p(ptr, le_bswap(v, 64)); +} + +static inline int lduw_be_p(const void *ptr) { + return (uint16_t) be_bswap(lduw_he_p(ptr), 16); +} + +static inline int ldsw_be_p(const void *ptr) { + return (int16_t) be_bswap(lduw_he_p(ptr), 16); +} + +static inline int ldl_be_p(const void *ptr) { + return be_bswap(ldl_he_p(ptr), 32); +} + +static inline uint64_t ldq_be_p(const void *ptr) { + return be_bswap(ldq_he_p(ptr), 64); +} + +static inline void stw_be_p(void *ptr, uint16_t v) { + stw_he_p(ptr, be_bswap(v, 16)); +} + +static inline void st24_be_p(void *ptr, uint32_t v) { + st24_he_p(ptr, be_bswap24(v)); +} + +static inline void stl_be_p(void *ptr, uint32_t v) { + stl_he_p(ptr, be_bswap(v, 32)); +} + +static inline void stq_be_p(void *ptr, uint64_t v) { + stq_he_p(ptr, be_bswap(v, 64)); +} + +/* Store v to p as a sz byte value in host order */ +#define DO_STN_LDN_P(END) \ + static inline void stn_##END##_p(void *ptr, int sz, uint64_t v) { \ + switch (sz) { \ + case 1: \ + stb_p(ptr, v); \ + break; \ + case 2: \ + stw_##END##_p(ptr, v); \ + break; \ + case 4: \ + stl_##END##_p(ptr, v); \ + break; \ + case 8: \ + stq_##END##_p(ptr, v); \ + break; \ + default: \ + g_assert_not_reached(); \ + } \ + } \ + static inline uint64_t ldn_##END##_p(const void *ptr, int sz) { \ + switch (sz) { \ + case 1: \ + return ldub_p(ptr); \ + case 2: \ + return lduw_##END##_p(ptr); \ + case 4: \ + return (uint32_t) ldl_##END##_p(ptr); \ + case 8: \ + return ldq_##END##_p(ptr); \ + default: \ + g_assert_not_reached(); \ + } \ + } + +DO_STN_LDN_P(he) +DO_STN_LDN_P(le) +DO_STN_LDN_P(be) + +#undef DO_STN_LDN_P + +#undef le_bswap +#undef be_bswap +#undef le_bswaps +#undef be_bswaps + +#ifdef __cplusplus +} +#endif + +#endif /* BSWAP_H */ diff --git a/libutils/include/utils/config-host.h b/libutils/include/utils/config-host.h index 93df1af39..824f3c087 100644 --- a/libutils/include/utils/config-host.h +++ b/libutils/include/utils/config-host.h @@ -37,6 +37,11 @@ #define CONFIG_MADVISE 1 #define CONFIG_POSIX_MEMALIGN 1 +// Upstream only enables AVX2 when cpuid.h is usable; keep that dependency. +#ifdef CONFIG_CPUID_H +#define CONFIG_AVX2_OPT 1 +#endif + // Always use QEMU's own QTree rather than aliasing it to GTree. Upstream // switches on the glib version; keeping one implementation avoids a behavior // change when the host glib is upgraded. diff --git a/libutils/include/utils/host/x86_64/bufferiszero.c.inc b/libutils/include/utils/host/x86_64/bufferiszero.c.inc new file mode 100644 index 000000000..a9cdcfd6e --- /dev/null +++ b/libutils/include/utils/host/x86_64/bufferiszero.c.inc @@ -0,0 +1,131 @@ +/* + * SPDX-License-Identifier: GPL-2.0-or-later + * buffer_is_zero acceleration, x86 version. + */ + +#include + +/* Helper for preventing the compiler from reassociating + chains of binary vector operations. */ +#define SSE_REASSOC_BARRIER(vec0, vec1) asm("" : "+x"(vec0), "+x"(vec1)) + +/* Note that these vectorized functions may assume len >= 256. */ + +static bool __attribute__((target("sse2"))) buffer_zero_sse2(const void *buf, size_t len) { + /* Unaligned loads at head/tail. */ + __m128i v = *(__m128i_u *) (buf); + __m128i w = *(__m128i_u *) (buf + len - 16); + /* Align head/tail to 16-byte boundaries. */ + const __m128i *p = QEMU_ALIGN_PTR_DOWN(buf + 16, 16); + const __m128i *e = QEMU_ALIGN_PTR_DOWN(buf + len - 1, 16); + __m128i zero = {0}; + + /* Collect a partial block at tail end. */ + v |= e[-1]; + w |= e[-2]; + SSE_REASSOC_BARRIER(v, w); + v |= e[-3]; + w |= e[-4]; + SSE_REASSOC_BARRIER(v, w); + v |= e[-5]; + w |= e[-6]; + SSE_REASSOC_BARRIER(v, w); + v |= e[-7]; + v |= w; + + /* + * Loop over complete 128-byte blocks. + * With the head and tail removed, e - p >= 14, so the loop + * must iterate at least once. + */ + do { + v = _mm_cmpeq_epi8(v, zero); + if (unlikely(_mm_movemask_epi8(v) != 0xFFFF)) { + return false; + } + v = p[0]; + w = p[1]; + SSE_REASSOC_BARRIER(v, w); + v |= p[2]; + w |= p[3]; + SSE_REASSOC_BARRIER(v, w); + v |= p[4]; + w |= p[5]; + SSE_REASSOC_BARRIER(v, w); + v |= p[6]; + w |= p[7]; + SSE_REASSOC_BARRIER(v, w); + v |= w; + p += 8; + } while (p < e - 7); + + return _mm_movemask_epi8(_mm_cmpeq_epi8(v, zero)) == 0xFFFF; +} + +#ifdef CONFIG_AVX2_OPT +static bool __attribute__((target("avx2"))) buffer_zero_avx2(const void *buf, size_t len) { + /* Unaligned loads at head/tail. */ + __m256i v = *(__m256i_u *) (buf); + __m256i w = *(__m256i_u *) (buf + len - 32); + /* Align head/tail to 32-byte boundaries. */ + const __m256i *p = QEMU_ALIGN_PTR_DOWN(buf + 32, 32); + const __m256i *e = QEMU_ALIGN_PTR_DOWN(buf + len - 1, 32); + __m256i zero = {0}; + + /* Collect a partial block at tail end. */ + v |= e[-1]; + w |= e[-2]; + SSE_REASSOC_BARRIER(v, w); + v |= e[-3]; + w |= e[-4]; + SSE_REASSOC_BARRIER(v, w); + v |= e[-5]; + w |= e[-6]; + SSE_REASSOC_BARRIER(v, w); + v |= e[-7]; + v |= w; + + /* Loop over complete 256-byte blocks. */ + for (; p < e - 7; p += 8) { + /* PTEST is not profitable here. */ + v = _mm256_cmpeq_epi8(v, zero); + if (unlikely(_mm256_movemask_epi8(v) != 0xFFFFFFFF)) { + return false; + } + v = p[0]; + w = p[1]; + SSE_REASSOC_BARRIER(v, w); + v |= p[2]; + w |= p[3]; + SSE_REASSOC_BARRIER(v, w); + v |= p[4]; + w |= p[5]; + SSE_REASSOC_BARRIER(v, w); + v |= p[6]; + w |= p[7]; + SSE_REASSOC_BARRIER(v, w); + v |= w; + } + + return _mm256_movemask_epi8(_mm256_cmpeq_epi8(v, zero)) == 0xFFFFFFFF; +} +#endif /* CONFIG_AVX2_OPT */ + +static biz_accel_fn const accel_table[] = { + buffer_is_zero_int_ge256, + buffer_zero_sse2, +#ifdef CONFIG_AVX2_OPT + buffer_zero_avx2, +#endif +}; + +static unsigned best_accel(void) { + unsigned info = cpuinfo_init(); + +#ifdef CONFIG_AVX2_OPT + if (info & CPUINFO_AVX2) { + return 2; + } +#endif + return info & CPUINFO_SSE2 ? 1 : 0; +} diff --git a/libutils/scripts/upgrade/mapping.tsv b/libutils/scripts/upgrade/mapping.tsv index 9cc952e19..9fbb0d6eb 100644 --- a/libutils/scripts/upgrade/mapping.tsv +++ b/libutils/scripts/upgrade/mapping.tsv @@ -12,6 +12,7 @@ # --- host support ------------------------------------------------------- include/utils/host/x86_64/cpuinfo.h host/include/x86_64/host/cpuinfo.h include/utils/host/x86_64/atomic128-ldst.h host/include/x86_64/host/atomic128-ldst.h.inc +include/utils/host/x86_64/bufferiszero.c.inc host/include/x86_64/host/bufferiszero.c.inc include/utils/host/generic/atomic128-cas.h host/include/generic/host/atomic128-cas.h.inc include/utils/host/generic/atomic128-ldst.h host/include/generic/host/atomic128-ldst.h.inc include/utils/host/generic/load-extract-al16-al8.h host/include/generic/host/load-extract-al16-al8.h.inc @@ -22,6 +23,7 @@ src/utils/cpuinfo-i386.c util/cpuinfo-i386.c # were simply never touched there, so they are current by definition. include/utils/atomic.h include/qemu/atomic.h include/utils/atomic128.h include/qemu/atomic128.h +include/utils/bitmap.h include/qemu/bitmap.h include/utils/bitops.h include/qemu/bitops.h include/utils/cacheflush.h include/qemu/cacheflush.h include/utils/cacheinfo.h include/qemu/cacheinfo.h @@ -38,6 +40,8 @@ include/utils/mprotect.h include/qemu/mprotect.h include/utils/qtree.h include/qemu/qtree.h include/utils/units.h include/qemu/units.h include/utils/registerfields.h include/hw/core/registerfields.h +src/utils/bitmap.c util/bitmap.c +src/utils/bufferiszero.c util/bufferiszero.c src/utils/cacheflush.c util/cacheflush.c src/utils/hexdump.c util/hexdump.c src/utils/host-utils.c util/host-utils.c @@ -47,8 +51,10 @@ src/utils/qtree.c util/qtree.c # Pruned copies: upstream text with whole sections removed because they need # meson configuration, os-posix.h, the Error API or sockets. They merge # mechanically as long as upstream leaves the kept sections alone; a conflict -# in a removed section is resolved by deleting it again. cutils.h drops the -# prototypes whose bodies cutils.c prunes. +# in a removed section is resolved by deleting it again. bswap.h keeps the +# host-only half; the MemOp and target-endian half is libtcg's utils/bswap.h. +# cutils.h drops the prototypes whose bodies cutils.c prunes. +include/utils/bswap.h include/qemu/bswap.h include/utils/cutils.h include/qemu/cutils.h include/utils/osdep.h include/qemu/osdep.h src/utils/cutils.c util/cutils.c diff --git a/libutils/src/CMakeLists.txt b/libutils/src/CMakeLists.txt index 986f368b9..b8c160383 100644 --- a/libutils/src/CMakeLists.txt +++ b/libutils/src/CMakeLists.txt @@ -51,6 +51,8 @@ add_library ( q/error.c q/unicode.c + utils/bitmap.c + utils/bufferiszero.c utils/cacheflush.c utils/cpuinfo-i386.c utils/cutils.c diff --git a/libutils/src/utils/bitmap.c b/libutils/src/utils/bitmap.c new file mode 100644 index 000000000..0b98cf6cf --- /dev/null +++ b/libutils/src/utils/bitmap.c @@ -0,0 +1,499 @@ +/* + * Bitmap Module + * + * Stolen from linux/src/lib/bitmap.c + * + * Copyright (C) 2010 Corentin Chary + * + * This source code is licensed under the GNU General Public License, + * Version 2. + */ + +#include +#include +#include +#include +#include + +/* + * bitmaps provide an array of bits, implemented using an + * array of unsigned longs. The number of valid bits in a + * given bitmap does _not_ need to be an exact multiple of + * BITS_PER_LONG. + * + * The possible unused bits in the last, partially used word + * of a bitmap are 'don't care'. The implementation makes + * no particular effort to keep them zero. It ensures that + * their value will not affect the results of any operation. + * The bitmap operations that return Boolean (bitmap_empty, + * for example) or scalar (bitmap_weight, for example) results + * carefully filter out these unused bits from impacting their + * results. + * + * These operations actually hold to a slightly stronger rule: + * if you don't input any bitmaps to these ops that have some + * unused bits set, then they won't output any set unused bits + * in output bitmaps. + * + * The byte ordering of bitmaps is more natural on little + * endian architectures. + */ + +int slow_bitmap_empty(const unsigned long *bitmap, long bits) { + long k, lim = bits / BITS_PER_LONG; + + for (k = 0; k < lim; ++k) { + if (bitmap[k]) { + return 0; + } + } + if (bits % BITS_PER_LONG) { + if (bitmap[k] & BITMAP_LAST_WORD_MASK(bits)) { + return 0; + } + } + + return 1; +} + +int slow_bitmap_full(const unsigned long *bitmap, long bits) { + long k, lim = bits / BITS_PER_LONG; + + for (k = 0; k < lim; ++k) { + if (~bitmap[k]) { + return 0; + } + } + + if (bits % BITS_PER_LONG) { + if (~bitmap[k] & BITMAP_LAST_WORD_MASK(bits)) { + return 0; + } + } + + return 1; +} + +int slow_bitmap_equal(const unsigned long *bitmap1, const unsigned long *bitmap2, long bits) { + long k, lim = bits / BITS_PER_LONG; + + for (k = 0; k < lim; ++k) { + if (bitmap1[k] != bitmap2[k]) { + return 0; + } + } + + if (bits % BITS_PER_LONG) { + if ((bitmap1[k] ^ bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits)) { + return 0; + } + } + + return 1; +} + +void slow_bitmap_complement(unsigned long *dst, const unsigned long *src, long bits) { + long k, lim = bits / BITS_PER_LONG; + + for (k = 0; k < lim; ++k) { + dst[k] = ~src[k]; + } + + if (bits % BITS_PER_LONG) { + dst[k] = ~src[k] & BITMAP_LAST_WORD_MASK(bits); + } +} + +int slow_bitmap_and(unsigned long *dst, const unsigned long *bitmap1, const unsigned long *bitmap2, long bits) { + long k; + long nr = BITS_TO_LONGS(bits); + unsigned long result = 0; + + for (k = 0; k < nr; k++) { + result |= (dst[k] = bitmap1[k] & bitmap2[k]); + } + return result != 0; +} + +void slow_bitmap_or(unsigned long *dst, const unsigned long *bitmap1, const unsigned long *bitmap2, long bits) { + long k; + long nr = BITS_TO_LONGS(bits); + + for (k = 0; k < nr; k++) { + dst[k] = bitmap1[k] | bitmap2[k]; + } +} + +void slow_bitmap_xor(unsigned long *dst, const unsigned long *bitmap1, const unsigned long *bitmap2, long bits) { + long k; + long nr = BITS_TO_LONGS(bits); + + for (k = 0; k < nr; k++) { + dst[k] = bitmap1[k] ^ bitmap2[k]; + } +} + +int slow_bitmap_andnot(unsigned long *dst, const unsigned long *bitmap1, const unsigned long *bitmap2, long bits) { + long k; + long nr = BITS_TO_LONGS(bits); + unsigned long result = 0; + + for (k = 0; k < nr; k++) { + result |= (dst[k] = bitmap1[k] & ~bitmap2[k]); + } + return result != 0; +} + +void bitmap_set(unsigned long *map, long start, long nr) { + unsigned long *p = map + BIT_WORD(start); + const long size = start + nr; + int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG); + unsigned long mask_to_set = BITMAP_FIRST_WORD_MASK(start); + + assert(start >= 0 && nr >= 0); + + while (nr - bits_to_set >= 0) { + *p |= mask_to_set; + nr -= bits_to_set; + bits_to_set = BITS_PER_LONG; + mask_to_set = ~0UL; + p++; + } + if (nr) { + mask_to_set &= BITMAP_LAST_WORD_MASK(size); + *p |= mask_to_set; + } +} + +void bitmap_set_atomic(unsigned long *map, long start, long nr) { + unsigned long *p = map + BIT_WORD(start); + const long size = start + nr; + int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG); + unsigned long mask_to_set = BITMAP_FIRST_WORD_MASK(start); + + assert(start >= 0 && nr >= 0); + + /* First word */ + if (nr - bits_to_set > 0) { + qatomic_or(p, mask_to_set); + nr -= bits_to_set; + bits_to_set = BITS_PER_LONG; + mask_to_set = ~0UL; + p++; + } + + /* Full words */ + if (bits_to_set == BITS_PER_LONG) { + while (nr >= BITS_PER_LONG) { + *p = ~0UL; + nr -= BITS_PER_LONG; + p++; + } + } + + /* Last word */ + if (nr) { + mask_to_set &= BITMAP_LAST_WORD_MASK(size); + qatomic_or(p, mask_to_set); + } else { + /* If we avoided the full barrier in qatomic_or(), issue a + * barrier to account for the assignments in the while loop. + */ + smp_mb(); + } +} + +void bitmap_clear(unsigned long *map, long start, long nr) { + unsigned long *p = map + BIT_WORD(start); + const long size = start + nr; + int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG); + unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start); + + assert(start >= 0 && nr >= 0); + + while (nr - bits_to_clear >= 0) { + *p &= ~mask_to_clear; + nr -= bits_to_clear; + bits_to_clear = BITS_PER_LONG; + mask_to_clear = ~0UL; + p++; + } + if (nr) { + mask_to_clear &= BITMAP_LAST_WORD_MASK(size); + *p &= ~mask_to_clear; + } +} + +bool bitmap_test_and_clear(unsigned long *map, long start, long nr) { + unsigned long *p = map + BIT_WORD(start); + const long size = start + nr; + int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG); + unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start); + bool dirty = false; + + assert(start >= 0 && nr >= 0); + + /* First word */ + if (nr - bits_to_clear > 0) { + if ((*p) & mask_to_clear) { + dirty = true; + } + *p &= ~mask_to_clear; + nr -= bits_to_clear; + bits_to_clear = BITS_PER_LONG; + p++; + } + + /* Full words */ + if (bits_to_clear == BITS_PER_LONG) { + while (nr >= BITS_PER_LONG) { + if (*p) { + dirty = true; + *p = 0; + } + nr -= BITS_PER_LONG; + p++; + } + } + + /* Last word */ + if (nr) { + mask_to_clear &= BITMAP_LAST_WORD_MASK(size); + if ((*p) & mask_to_clear) { + dirty = true; + } + *p &= ~mask_to_clear; + } + + return dirty; +} + +bool bitmap_test_and_clear_atomic(unsigned long *map, long start, long nr) { + unsigned long *p = map + BIT_WORD(start); + const long size = start + nr; + int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG); + unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start); + unsigned long dirty = 0; + unsigned long old_bits; + + assert(start >= 0 && nr >= 0); + + /* First word */ + if (nr - bits_to_clear > 0) { + old_bits = qatomic_fetch_and(p, ~mask_to_clear); + dirty |= old_bits & mask_to_clear; + nr -= bits_to_clear; + bits_to_clear = BITS_PER_LONG; + mask_to_clear = ~0UL; + p++; + } + + /* Full words */ + if (bits_to_clear == BITS_PER_LONG) { + while (nr >= BITS_PER_LONG) { + if (*p) { + old_bits = qatomic_xchg(p, 0); + dirty |= old_bits; + } + nr -= BITS_PER_LONG; + p++; + } + } + + /* Last word */ + if (nr) { + mask_to_clear &= BITMAP_LAST_WORD_MASK(size); + old_bits = qatomic_fetch_and(p, ~mask_to_clear); + dirty |= old_bits & mask_to_clear; + } else { + if (!dirty) { + smp_mb(); + } + } + + return dirty != 0; +} + +void bitmap_copy_and_clear_atomic(unsigned long *dst, unsigned long *src, long nr) { + while (nr > 0) { + *dst = qatomic_xchg(src, 0); + dst++; + src++; + nr -= BITS_PER_LONG; + } +} + +#define ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask)) + +/** + * bitmap_find_next_zero_area - find a contiguous aligned zero area + * @map: The address to base the search on + * @size: The bitmap size in bits + * @start: The bitnumber to start searching at + * @nr: The number of zeroed bits we're looking for + * @align_mask: Alignment mask for zero area + * + * The @align_mask should be one less than a power of 2; the effect is that + * the bit offset of all zero areas this function finds is multiples of that + * power of 2. A @align_mask of 0 means no alignment is required. + */ +unsigned long bitmap_find_next_zero_area(unsigned long *map, unsigned long size, unsigned long start, unsigned long nr, + unsigned long align_mask) { + unsigned long index, end, i; +again: + index = find_next_zero_bit(map, size, start); + + /* Align allocation */ + index = ALIGN_MASK(index, align_mask); + + end = index + nr; + if (end > size) { + return end; + } + i = find_next_bit(map, end, index); + if (i < end) { + start = i + 1; + goto again; + } + return index; +} + +int slow_bitmap_intersects(const unsigned long *bitmap1, const unsigned long *bitmap2, long bits) { + long k, lim = bits / BITS_PER_LONG; + + for (k = 0; k < lim; ++k) { + if (bitmap1[k] & bitmap2[k]) { + return 1; + } + } + + if (bits % BITS_PER_LONG) { + if ((bitmap1[k] & bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits)) { + return 1; + } + } + return 0; +} + +long slow_bitmap_count_one(const unsigned long *bitmap, long nbits) { + long k, lim = nbits / BITS_PER_LONG, result = 0; + + for (k = 0; k < lim; k++) { + result += ctpopl(bitmap[k]); + } + + if (nbits % BITS_PER_LONG) { + result += ctpopl(bitmap[k] & BITMAP_LAST_WORD_MASK(nbits)); + } + + return result; +} + +static void bitmap_to_from_le(unsigned long *dst, const unsigned long *src, long nbits) { + long len = BITS_TO_LONGS(nbits); + +#if HOST_BIG_ENDIAN + long index; + + for (index = 0; index < len; index++) { +#if HOST_LONG_BITS == 64 + dst[index] = bswap64(src[index]); +#else + dst[index] = bswap32(src[index]); +#endif + } +#else + memcpy(dst, src, len * sizeof(unsigned long)); +#endif +} + +void bitmap_from_le(unsigned long *dst, const unsigned long *src, long nbits) { + bitmap_to_from_le(dst, src, nbits); +} + +void bitmap_to_le(unsigned long *dst, const unsigned long *src, long nbits) { + bitmap_to_from_le(dst, src, nbits); +} + +/* + * Copy "src" bitmap with a positive offset and put it into the "dst" + * bitmap. The caller needs to make sure the bitmap size of "src" + * is bigger than (shift + nbits). + */ +void bitmap_copy_with_src_offset(unsigned long *dst, const unsigned long *src, unsigned long shift, + unsigned long nbits) { + unsigned long left_mask, right_mask, last_mask; + + /* Proper shift src pointer to the first word to copy from */ + src += BIT_WORD(shift); + shift %= BITS_PER_LONG; + + if (!shift) { + /* Fast path */ + bitmap_copy(dst, src, nbits); + return; + } + + right_mask = (1ul << shift) - 1; + left_mask = ~right_mask; + + while (nbits >= BITS_PER_LONG) { + *dst = (*src & left_mask) >> shift; + *dst |= (src[1] & right_mask) << (BITS_PER_LONG - shift); + dst++; + src++; + nbits -= BITS_PER_LONG; + } + + if (nbits > BITS_PER_LONG - shift) { + *dst = (*src & left_mask) >> shift; + nbits -= BITS_PER_LONG - shift; + last_mask = (1ul << nbits) - 1; + *dst |= (src[1] & last_mask) << (BITS_PER_LONG - shift); + } else if (nbits) { + last_mask = (1ul << nbits) - 1; + *dst = (*src >> shift) & last_mask; + } +} + +/* + * Copy "src" bitmap into the "dst" bitmap with an offset in the + * "dst". The caller needs to make sure the bitmap size of "dst" is + * bigger than (shift + nbits). + */ +void bitmap_copy_with_dst_offset(unsigned long *dst, const unsigned long *src, unsigned long shift, + unsigned long nbits) { + unsigned long left_mask, right_mask, last_mask; + + /* Proper shift dst pointer to the first word to copy from */ + dst += BIT_WORD(shift); + shift %= BITS_PER_LONG; + + if (!shift) { + /* Fast path */ + bitmap_copy(dst, src, nbits); + return; + } + + right_mask = (1ul << (BITS_PER_LONG - shift)) - 1; + left_mask = ~right_mask; + + *dst &= (1ul << shift) - 1; + while (nbits >= BITS_PER_LONG) { + *dst |= (*src & right_mask) << shift; + dst[1] = (*src & left_mask) >> (BITS_PER_LONG - shift); + dst++; + src++; + nbits -= BITS_PER_LONG; + } + + if (nbits > BITS_PER_LONG - shift) { + *dst |= (*src & right_mask) << shift; + nbits -= BITS_PER_LONG - shift; + last_mask = ((1ul << nbits) - 1) << (BITS_PER_LONG - shift); + dst[1] = (*src & last_mask) >> (BITS_PER_LONG - shift); + } else if (nbits) { + last_mask = (1ul << nbits) - 1; + *dst |= (*src & last_mask) << shift; + } +} diff --git a/libutils/src/utils/bufferiszero.c b/libutils/src/utils/bufferiszero.c new file mode 100644 index 000000000..774d7ccc7 --- /dev/null +++ b/libutils/src/utils/bufferiszero.c @@ -0,0 +1,120 @@ +/* + * Simple C functions to supplement the C library + * + * Copyright (c) 2006 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#include +#include +#include +#include + +typedef bool (*biz_accel_fn)(const void *, size_t); + +static bool buffer_is_zero_int_lt256(const void *buf, size_t len) { + uint64_t t; + const uint64_t *p, *e; + + /* + * Use unaligned memory access functions to handle + * the beginning and end of the buffer. + */ + if (unlikely(len <= 8)) { + return (ldl_he_p(buf) | ldl_he_p(buf + len - 4)) == 0; + } + + t = ldq_he_p(buf) | ldq_he_p(buf + len - 8); + p = QEMU_ALIGN_PTR_DOWN(buf + 8, 8); + e = QEMU_ALIGN_PTR_DOWN(buf + len - 1, 8); + + /* Read 0 to 31 aligned words from the middle. */ + while (p < e) { + t |= *p++; + } + return t == 0; +} + +static bool buffer_is_zero_int_ge256(const void *buf, size_t len) { + /* + * Use unaligned memory access functions to handle + * the beginning and end of the buffer. + */ + uint64_t t = ldq_he_p(buf) | ldq_he_p(buf + len - 8); + const uint64_t *p = QEMU_ALIGN_PTR_DOWN(buf + 8, 8); + const uint64_t *e = QEMU_ALIGN_PTR_DOWN(buf + len - 1, 8); + + /* Collect a partial block at the tail end. */ + t |= e[-7] | e[-6] | e[-5] | e[-4] | e[-3] | e[-2] | e[-1]; + + /* + * Loop over 64 byte blocks. + * With the head and tail removed, e - p >= 30, + * so the loop must iterate at least 3 times. + */ + do { + if (t) { + return false; + } + t = p[0] | p[1] | p[2] | p[3] | p[4] | p[5] | p[6] | p[7]; + p += 8; + } while (p < e - 7); + + return t == 0; +} + +#include + +static biz_accel_fn buffer_is_zero_accel; +static unsigned accel_index; + +bool buffer_is_zero_ool(const void *buf, size_t len) { + if (unlikely(len == 0)) { + return true; + } + if (!buffer_is_zero_sample3(buf, len)) { + return false; + } + /* All bytes are covered for any len <= 3. */ + if (unlikely(len <= 3)) { + return true; + } + + if (likely(len >= 256)) { + return buffer_is_zero_accel(buf, len); + } + return buffer_is_zero_int_lt256(buf, len); +} + +bool buffer_is_zero_ge256(const void *buf, size_t len) { + return buffer_is_zero_accel(buf, len); +} + +bool test_buffer_is_zero_next_accel(void) { + if (accel_index != 0) { + buffer_is_zero_accel = accel_table[--accel_index]; + return true; + } + return false; +} + +static void __attribute__((constructor)) init_accel(void) { + accel_index = best_accel(); + buffer_is_zero_accel = accel_table[accel_index]; +} diff --git a/scripts/upgrade/README.md b/scripts/upgrade/README.md index d19aaa3de..054594e9e 100644 --- a/scripts/upgrade/README.md +++ b/scripts/upgrade/README.md @@ -68,10 +68,16 @@ they are resolved. Not every file tracks upstream closely: -- libtcg's `utils/bswap.h` and `utils/log.{h,c}` are heavily reduced - S2E-specific subsets rather than vendored copies, still v8.1.0-era. They are - listed in `mapping.tsv` for reference but want a manual look rather than a - mechanical merge. +- libtcg's `utils/log.{h,c}` are heavily reduced S2E-specific subsets rather + than vendored copies, still v8.1.0-era. They are listed in `mapping.tsv` for + reference but want a manual look rather than a mechanical merge. +- `include/qemu/bswap.h` is split: the host-only half is libutils' + `utils/bswap.h`, the `MemOp` and target-endian half is libtcg's + `utils/bswap.h`. Both rows map to the same upstream file, so each merge + reports the other half's upstream changes as a conflict in a deleted + section; delete it again. libtcg's `utils/target-info.h` answers + `target_big_endian()` with `TARGET_BIG_ENDIAN` under `COMPILING_PER_TARGET`, + and `exec/tswap.h` drops the `CPUState`-based `cpu_internal_tswap*`. - libutils' `utils/cutils.h`, `utils/osdep.h`, `src/utils/cutils.c`, `src/utils/osdep.c` and `src/utils/oslib-posix.c` are pruned copies: upstream text with whole sections deleted because they need meson configuration, From 3a341eda66999930f4ab80fb4cae6b659bb9f30a Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Mon, 24 Aug 2026 07:51:45 +0000 Subject: [PATCH 22/52] libutils: imported qht, rcu, thread, xxhash and seqlock from QEMU v11.1.0 These are the concurrency utilities section 4.2 of PORTING.md lists as missing for the accel/tcg import: the TB hash table, its RCU machinery, and the thread primitives underneath. The import closure adds futex.h, processor.h, lockable.h, notify.{h,c}, sys_membarrier.h, coroutine-tls.h, event.c (QemuEvent, split out of qemu-thread-posix.c upstream) and qemu-thread-common.h. processor.h, xxhash.h, coroutine-tls.h, thread-posix.h, seqlock.h and event.c are verbatim with the includes and extern "C" guards; the rest are pruned copies: - thread.h drops win32 and the QSP profiler indirection. Its lock macros call the _impl functions directly and the __raw variants are aliases, so qht.c's QHT_MODE_RAW_MUTEXES path stays upstream text. It also declares the QemuMutex and QemuSpin typedefs that upstream keeps in qemu/typedefs.h, which is not vendored. - qht.{h,c} drop qht_statistics, the only user of qdist, which stays out. - rcu.c drops the BQL around callbacks: the BQL stub belongs to libcpu and libutils cannot depend on it. It also keeps the pthread_atfork hooks unconditionally instead of behind CONFIG_POSIX; defining that macro would activate region.c's split-wx memfd section, which needs the unvendored qemu/memfd.h. - lockable.h drops CoMutex, notify.{h,c} drop NotifierWithReturn (Error API), sys_membarrier.h keeps only the non-CONFIG_MEMBARRIER branch, qemu-thread-common.h drops tracing and BQL status tracking, and qemu-thread-posix.c drops the TSAN annotation and trace calls. config-host.h gains CONFIG_LINUX, which futex.h keys HAVE_FUTEX on, and CONFIG_PTHREAD_CONDATTR_SETCLOCK. The pthread_*_np name and affinity configs stay undefined: glibc hides those behind _GNU_SOURCE, and the fallbacks (unnamed threads, -ENOSYS affinity) cost nothing. qqueue.h is now the full upstream include/qemu/queue.h rather than the old v8.1.0-era subset: this brings QLIST_SAFE_REMOVE (notify.c needs it), QSLIST_REMOVE, the RAW macros and the union-based QTAILQ. The deviations for C++ follow compiler.h's precedent: typeof is spelled __typeof__ and QLIST_SWAP's temporary is typed instead of void *. Nothing in the tree touches the queue fields outside the macros, so the QTAILQ representation change is invisible. With the real thread.h in place, the mutex.h stand-in (kept in the last vendoring round because thread.h then dragged in qsp and trace.h) is gone: region.c uses QemuMutex and qemu_mutex_*(), matching upstream region.c, and tcg.c drops its unused include. merge.sh reports zero conflicts for both components at v11.1.0, and libutils, its tests and libs2e build in release and debug. Co-Authored-By: Claude Fable 5 Signed-off-by: Vitaly Chipounov --- libcpu/PORTING.md | 19 +- libtcg/src/region.c | 52 +- libtcg/src/tcg.c | 1 - libutils/include/qqueue.h | 141 +++- libutils/include/utils/config-host.h | 19 + libutils/include/utils/coroutine-tls.h | 178 +++++ libutils/include/utils/futex.h | 70 ++ libutils/include/utils/lockable.h | 172 +++++ libutils/include/utils/mutex.h | 54 -- libutils/include/utils/notify.h | 53 ++ libutils/include/utils/processor.h | 27 + libutils/include/utils/qht.h | 192 +++++ libutils/include/utils/rcu.h | 196 ++++++ libutils/include/utils/seqlock.h | 83 +++ libutils/include/utils/sys_membarrier.h | 28 + libutils/include/utils/thread-posix.h | 39 + libutils/include/utils/thread.h | 236 +++++++ libutils/include/utils/xxhash.h | 223 ++++++ libutils/scripts/upgrade/mapping.tsv | 36 +- libutils/src/CMakeLists.txt | 8 +- libutils/src/utils/event.c | 166 +++++ libutils/src/utils/notify.c | 43 ++ libutils/src/utils/qemu-thread-common.h | 45 ++ libutils/src/utils/qemu-thread-posix.c | 530 ++++++++++++++ libutils/src/utils/qht.c | 900 ++++++++++++++++++++++++ libutils/src/utils/rcu.c | 456 ++++++++++++ scripts/upgrade/README.md | 13 +- 27 files changed, 3854 insertions(+), 126 deletions(-) create mode 100644 libutils/include/utils/coroutine-tls.h create mode 100644 libutils/include/utils/futex.h create mode 100644 libutils/include/utils/lockable.h delete mode 100644 libutils/include/utils/mutex.h create mode 100644 libutils/include/utils/notify.h create mode 100644 libutils/include/utils/processor.h create mode 100644 libutils/include/utils/qht.h create mode 100644 libutils/include/utils/rcu.h create mode 100644 libutils/include/utils/seqlock.h create mode 100644 libutils/include/utils/sys_membarrier.h create mode 100644 libutils/include/utils/thread-posix.h create mode 100644 libutils/include/utils/thread.h create mode 100644 libutils/include/utils/xxhash.h create mode 100644 libutils/src/utils/event.c create mode 100644 libutils/src/utils/notify.c create mode 100644 libutils/src/utils/qemu-thread-common.h create mode 100644 libutils/src/utils/qemu-thread-posix.c create mode 100644 libutils/src/utils/qht.c create mode 100644 libutils/src/utils/rcu.c diff --git a/libcpu/PORTING.md b/libcpu/PORTING.md index 4f1713761..47f3d1428 100644 --- a/libcpu/PORTING.md +++ b/libcpu/PORTING.md @@ -69,8 +69,10 @@ ones. Take the same route libtcg took, so that the second upgrade (11.1 to 2. Rewrite its includes to libcpu/libtcg paths and add `extern "C"` guards. 3. Record the pairing in `libcpu/scripts/upgrade/mapping.tsv`, with `BASELINE` = `v11.1.0`. -4. Confirm normalization by merging the tag onto itself: - `./merge.sh libcpu v11.1.0 v11.1.0` must report zero conflicts. +4. Check that every mapping row resolves by merging the tag onto itself: + `./merge.sh libcpu v11.1.0 v11.1.0`. A same-tag run cannot conflict (base + and theirs are identical), so it validates the mapping and the normalize + pipeline, not the S2E deviations. `scripts/upgrade/{normalize.sh,merge.sh}` at the S2E source root already do steps 1 and 4 for any component that carries `scripts/upgrade/mapping.tsv`, so @@ -291,8 +293,9 @@ Do not reintroduce command-line copies in libtcg or libcpu. The upgrade tooling followed the files: the shared driver now lives in `scripts/upgrade/` at the source root, and libutils has its own `scripts/upgrade/{BASELINE,mapping.tsv}` holding the 28 rows that moved out of -libtcg's mapping. Both components report zero conflicts under -`merge.sh v11.1.0 v11.1.0`. +libtcg's mapping. Both components' mappings resolve under +`merge.sh v11.1.0 v11.1.0` (a same-tag run cannot conflict; it +checks mapping resolution and normalization only). ### 4.2 What 11.1 needs that we do not have @@ -367,6 +370,14 @@ codebase. - Import qht, rcu, thread, xxhash, seqlock into **libutils** per section 4.2; add them to libutils' new `mapping.tsv`. Fold libtcg's `utils/mutex.h` into the real thread header. + Done: 18 files imported (with their closure: futex, processor, lockable, + notify, sys_membarrier, coroutine-tls, event, qemu-thread-common), 19 rows + added to the mapping, qdist compiled out of qht, the BQL pruned out of rcu.c, + and `qqueue.h` replaced by the full upstream `qemu/queue.h` (with + `utils/compiler.h` mapping `typeof` for C++). `utils/mutex.h` is gone; + `region.c` uses `QemuMutex`. `merge.sh libutils v11.1.0 v11.1.0` still + resolves every row; a same-tag run cannot conflict, so the pruned sections + get their first real merge test at the next upgrade. - Write `libcpu/include/cpu/state.h`: slim `CPUState`, `CPUNegativeOffsetState`, `ArchCPU`, `cpu_env()` / `env_cpu()`, and the `TCGCPUOps` pointer that replaces `cpu->cc`. diff --git a/libtcg/src/region.c b/libtcg/src/region.c index f970c6805..c72e1f21d 100644 --- a/libtcg/src/region.c +++ b/libtcg/src/region.c @@ -41,10 +41,10 @@ #include #include #include -#include #include #include #include +#include #include // clang-format off @@ -66,7 +66,7 @@ #endif struct tcg_region_tree { - mutex_t lock; + QemuMutex lock; QTree *tree; /* padding to avoid false sharing is computed at run-time */ }; @@ -78,7 +78,7 @@ struct tcg_region_tree { * more code than others. */ struct tcg_region_state { - mutex_t lock; + QemuMutex lock; /* fields set at init time */ void *start_aligned; @@ -197,7 +197,7 @@ static void tcg_region_trees_init(void) { for (i = 0; i < region.n; i++) { struct tcg_region_tree *rt = region_trees + i * tree_size; - mutex_init(&rt->lock); + qemu_mutex_init(&rt->lock); rt->tree = q_tree_new_full(tb_tc_cmp, NULL, NULL, tb_destroy); } } @@ -234,18 +234,18 @@ void tcg_tb_insert(TranslationBlock *tb) { struct tcg_region_tree *rt = tc_ptr_to_region_tree(tb->tc.ptr); g_assert(rt != NULL); - mutex_lock(&rt->lock); + qemu_mutex_lock(&rt->lock); q_tree_insert(rt->tree, &tb->tc, tb); - mutex_unlock(&rt->lock); + qemu_mutex_unlock(&rt->lock); } void tcg_tb_remove(TranslationBlock *tb) { struct tcg_region_tree *rt = tc_ptr_to_region_tree(tb->tc.ptr); g_assert(rt != NULL); - mutex_lock(&rt->lock); + qemu_mutex_lock(&rt->lock); q_tree_remove(rt->tree, &tb->tc); - mutex_unlock(&rt->lock); + qemu_mutex_unlock(&rt->lock); } /* @@ -262,9 +262,9 @@ TranslationBlock *tcg_tb_lookup(uintptr_t tc_ptr) { return NULL; } - mutex_lock(&rt->lock); + qemu_mutex_lock(&rt->lock); tb = q_tree_lookup(rt->tree, &s); - mutex_unlock(&rt->lock); + qemu_mutex_unlock(&rt->lock); return tb; } @@ -274,7 +274,7 @@ static void tcg_region_tree_lock_all(void) { for (i = 0; i < region.n; i++) { struct tcg_region_tree *rt = region_trees + i * tree_size; - mutex_lock(&rt->lock); + qemu_mutex_lock(&rt->lock); } } @@ -284,7 +284,7 @@ static void tcg_region_tree_unlock_all(void) { for (i = 0; i < region.n; i++) { struct tcg_region_tree *rt = region_trees + i * tree_size; - mutex_unlock(&rt->lock); + qemu_mutex_unlock(&rt->lock); } } @@ -375,12 +375,12 @@ bool tcg_region_alloc(TCGContext *s) { /* read the region size now; alloc__locked will overwrite it on success */ size_t size_full = s->code_gen_buffer_size; - mutex_lock(®ion.lock); + qemu_mutex_lock(®ion.lock); err = tcg_region_alloc__locked(s); if (!err) { region.agg_size_full += size_full - TCG_HIGHWATER; } - mutex_unlock(®ion.lock); + qemu_mutex_unlock(®ion.lock); return err; } @@ -394,9 +394,9 @@ static void tcg_region_initial_alloc__locked(TCGContext *s) { } void tcg_region_initial_alloc(TCGContext *s) { - mutex_lock(®ion.lock); + qemu_mutex_lock(®ion.lock); tcg_region_initial_alloc__locked(s); - mutex_unlock(®ion.lock); + qemu_mutex_unlock(®ion.lock); } /* Call from a safe-work context */ @@ -404,7 +404,7 @@ void tcg_region_reset_all(void) { unsigned int n_ctxs = qatomic_read(&tcg_cur_ctxs); unsigned int i; - mutex_lock(®ion.lock); + qemu_mutex_lock(®ion.lock); region.current = 0; region.agg_size_full = 0; @@ -412,7 +412,7 @@ void tcg_region_reset_all(void) { TCGContext *s = qatomic_read(&tcg_ctxs[i]); tcg_region_initial_alloc__locked(s); } - mutex_unlock(®ion.lock); + qemu_mutex_unlock(®ion.lock); tcg_region_tree_reset_all(); } @@ -544,7 +544,8 @@ static int alloc_code_gen_buffer_anon(size_t size, int prot, int flags, Error ** } #ifndef CONFIG_TCG_INTERPRETER -#ifdef CONFIG_POSIX +/* S2E: upstream keys this on CONFIG_POSIX; qemu/memfd.h is not vendored. */ +#ifdef HAVE_QEMU_MEMFD #include "qemu/memfd.h" static int alloc_code_gen_buffer_splitwx_memfd(size_t size, Error **errp) { @@ -579,7 +580,7 @@ static int alloc_code_gen_buffer_splitwx_memfd(size_t size, Error **errp) { } return -1; } -#endif /* CONFIG_POSIX */ +#endif /* HAVE_QEMU_MEMFD */ #ifdef CONFIG_DARWIN #include @@ -628,7 +629,7 @@ static int alloc_code_gen_buffer_splitwx(size_t size, Error **errp) { #ifdef CONFIG_DARWIN return alloc_code_gen_buffer_splitwx_vmremap(size, errp); #endif -#ifdef CONFIG_POSIX +#ifdef HAVE_QEMU_MEMFD return alloc_code_gen_buffer_splitwx_memfd(size, errp); #endif #endif @@ -754,7 +755,7 @@ void tcg_region_init(size_t tb_size, int splitwx, unsigned max_threads) { region.after_prologue = region.start_aligned; /* init the region struct */ - mutex_init(®ion.lock); + qemu_mutex_init(®ion.lock); /* * Set guard pages in the rw buffer, as that's the one into which @@ -783,7 +784,8 @@ void tcg_region_init(size_t tb_size, int splitwx, unsigned max_threads) { #ifdef CONFIG_POSIX rc = mprotect(start, end - start, need_prot); if (rc) { - error_report("mprotect of jit buffer: %s", strerror(errno)); + /* S2E: error_report is not vendored. */ + fprintf(stderr, "mprotect of jit buffer: %s\n", strerror(errno)); } #else g_assert_not_reached(); @@ -834,7 +836,7 @@ size_t tcg_code_size(void) { unsigned int i; size_t total; - mutex_lock(®ion.lock); + qemu_mutex_lock(®ion.lock); total = region.agg_size_full; for (i = 0; i < n_ctxs; i++) { const TCGContext *s = qatomic_read(&tcg_ctxs[i]); @@ -844,7 +846,7 @@ size_t tcg_code_size(void) { g_assert(size <= s->code_gen_buffer_size); total += size; } - mutex_unlock(®ion.lock); + qemu_mutex_unlock(®ion.lock); return total; } diff --git a/libtcg/src/tcg.c b/libtcg/src/tcg.c index 1174a4846..03a6125e9 100644 --- a/libtcg/src/tcg.c +++ b/libtcg/src/tcg.c @@ -44,7 +44,6 @@ #include #include #include -#include #include #include diff --git a/libutils/include/qqueue.h b/libutils/include/qqueue.h index c9c9147a8..6b6257f05 100644 --- a/libutils/include/qqueue.h +++ b/libutils/include/qqueue.h @@ -6,6 +6,9 @@ * queues, and tail queues. */ +/* S2E: compiler.h maps typeof to __typeof__, and QLIST_SWAP uses a typed temporary, so the macros expand in C++. */ +#include + /* * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. @@ -37,12 +40,8 @@ * @(#)queue.h 8.5 (Berkeley) 8/20/94 */ -#ifndef LIBQ_SYS_QUEUE_H -#define LIBQ_SYS_QUEUE_H - -#ifdef __cplusplus -extern "C" { -#endif +#ifndef QEMU_SYS_QUEUE_H +#define QEMU_SYS_QUEUE_H /* * This file defines four types of data structures: singly-linked lists, @@ -108,7 +107,7 @@ extern "C" { #define QLIST_SWAP(dstlist, srclist, field) \ do { \ - void *tmplist; \ + __typeof__((srclist)->lh_first) tmplist; \ tmplist = (srclist)->lh_first; \ (srclist)->lh_first = (dstlist)->lh_first; \ if ((srclist)->lh_first != NULL) { \ @@ -149,8 +148,27 @@ extern "C" { if ((elm)->field.le_next != NULL) \ (elm)->field.le_next->field.le_prev = (elm)->field.le_prev; \ *(elm)->field.le_prev = (elm)->field.le_next; \ + (elm)->field.le_next = NULL; \ + (elm)->field.le_prev = NULL; \ + } while (/*CONSTCOND*/ 0) + +/* + * Like QLIST_REMOVE() but safe to call when elm is not in a list + */ +#define QLIST_SAFE_REMOVE(elm, field) \ + do { \ + if ((elm)->field.le_prev != NULL) { \ + if ((elm)->field.le_next != NULL) \ + (elm)->field.le_next->field.le_prev = (elm)->field.le_prev; \ + *(elm)->field.le_prev = (elm)->field.le_next; \ + (elm)->field.le_next = NULL; \ + (elm)->field.le_prev = NULL; \ + } \ } while (/*CONSTCOND*/ 0) +/* Is elm in a list? */ +#define QLIST_IS_INSERTED(elm, field) ((elm)->field.le_prev != NULL) + #define QLIST_FOREACH(var, head, field) for ((var) = ((head)->lh_first); (var); (var) = ((var)->field.le_next)) #define QLIST_FOREACH_SAFE(var, head, field, next_var) \ @@ -198,27 +216,44 @@ extern "C" { (head)->slh_first = (elm); \ } while (/*CONSTCOND*/ 0) -#define QSLIST_INSERT_HEAD_ATOMIC(head, elm, field) \ - do { \ - __typeof__(elm) save_sle_next; \ - do { \ - save_sle_next = (elm)->field.sle_next = (head)->slh_first; \ - } while (atomic_cmpxchg(&(head)->slh_first, save_sle_next, (elm)) != save_sle_next); \ +#define QSLIST_INSERT_HEAD_ATOMIC(head, elm, field) \ + do { \ + typeof(elm) save_sle_next; \ + do { \ + save_sle_next = (elm)->field.sle_next = (head)->slh_first; \ + } while (qatomic_cmpxchg(&(head)->slh_first, save_sle_next, (elm)) != save_sle_next); \ } while (/*CONSTCOND*/ 0) -#define QSLIST_MOVE_ATOMIC(dest, src) \ - do { \ - (dest)->slh_first = atomic_xchg(&(src)->slh_first, NULL); \ +#define QSLIST_MOVE_ATOMIC(dest, src) \ + do { \ + (dest)->slh_first = qatomic_xchg(&(src)->slh_first, NULL); \ } while (/*CONSTCOND*/ 0) -#define QSLIST_REMOVE_HEAD(head, field) \ - do { \ - (head)->slh_first = (head)->slh_first->field.sle_next; \ +#define QSLIST_REMOVE_HEAD(head, field) \ + do { \ + typeof((head)->slh_first) elm = (head)->slh_first; \ + (head)->slh_first = elm->field.sle_next; \ + elm->field.sle_next = NULL; \ } while (/*CONSTCOND*/ 0) -#define QSLIST_REMOVE_AFTER(slistelm, field) \ - do { \ - (slistelm)->field.sle_next = QSLIST_NEXT(QSLIST_NEXT((slistelm), field), field); \ +#define QSLIST_REMOVE_AFTER(slistelm, field) \ + do { \ + typeof(slistelm) next = (slistelm)->field.sle_next; \ + (slistelm)->field.sle_next = next->field.sle_next; \ + next->field.sle_next = NULL; \ + } while (/*CONSTCOND*/ 0) + +#define QSLIST_REMOVE(head, elm, type, field) \ + do { \ + if ((head)->slh_first == (elm)) { \ + QSLIST_REMOVE_HEAD((head), field); \ + } else { \ + struct type *curelm = (head)->slh_first; \ + while (curelm->field.sle_next != (elm)) \ + curelm = curelm->field.sle_next; \ + curelm->field.sle_next = curelm->field.sle_next->field.sle_next; \ + (elm)->field.sle_next = NULL; \ + } \ } while (/*CONSTCOND*/ 0) #define QSLIST_FOREACH(var, head, field) for ((var) = (head)->slh_first; (var); (var) = (var)->field.sle_next) @@ -279,10 +314,12 @@ extern "C" { (listelm)->field.sqe_next = (elm); \ } while (/*CONSTCOND*/ 0) -#define QSIMPLEQ_REMOVE_HEAD(head, field) \ - do { \ - if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ - (head)->sqh_last = &(head)->sqh_first; \ +#define QSIMPLEQ_REMOVE_HEAD(head, field) \ + do { \ + typeof((head)->sqh_first) elm = (head)->sqh_first; \ + if (((head)->sqh_first = elm->field.sqe_next) == NULL) \ + (head)->sqh_last = &(head)->sqh_first; \ + elm->field.sqe_next = NULL; \ } while (/*CONSTCOND*/ 0) #define QSIMPLEQ_SPLIT_AFTER(head, elm, field, removed) \ @@ -307,6 +344,7 @@ extern "C" { curelm = curelm->field.sqe_next; \ if ((curelm->field.sqe_next = curelm->field.sqe_next->field.sqe_next) == NULL) \ (head)->sqh_last = &(curelm)->field.sqe_next; \ + (elm)->field.sqe_next = NULL; \ } \ } while (/*CONSTCOND*/ 0) @@ -340,7 +378,7 @@ extern "C" { /* * Simple queue access methods. */ -#define QSIMPLEQ_EMPTY_ATOMIC(head) (atomic_read(&((head)->sqh_first)) == NULL) +#define QSIMPLEQ_EMPTY_ATOMIC(head) (qatomic_read(&((head)->sqh_first)) == NULL) #define QSIMPLEQ_EMPTY(head) ((head)->sqh_first == NULL) #define QSIMPLEQ_FIRST(head) ((head)->sqh_first) #define QSIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) @@ -424,6 +462,18 @@ typedef struct QTailQLink { (head)->tqh_circ.tql_prev = (elm)->field.tqe_circ.tql_prev; \ (elm)->field.tqe_circ.tql_prev->tql_next = (elm)->field.tqe_next; \ (elm)->field.tqe_circ.tql_prev = NULL; \ + (elm)->field.tqe_circ.tql_next = NULL; \ + (elm)->field.tqe_next = NULL; \ + } while (/*CONSTCOND*/ 0) + +/* remove @left, @right and all elements in between from @head */ +#define QTAILQ_REMOVE_SEVERAL(head, left, right, field) \ + do { \ + if (((right)->field.tqe_next) != NULL) \ + (right)->field.tqe_next->field.tqe_circ.tql_prev = (left)->field.tqe_circ.tql_prev; \ + else \ + (head)->tqh_circ.tql_prev = (left)->field.tqe_circ.tql_prev; \ + (left)->field.tqe_circ.tql_prev->tql_next = (right)->field.tqe_next; \ } while (/*CONSTCOND*/ 0) #define QTAILQ_FOREACH(var, head, field) for ((var) = ((head)->tqh_first); (var); (var) = ((var)->field.tqe_next)) @@ -445,8 +495,8 @@ typedef struct QTailQLink { #define QTAILQ_IN_USE(elm, field) ((elm)->field.tqe_circ.tql_prev != NULL) #define QTAILQ_LINK_PREV(link) ((link).tql_prev->tql_prev->tql_next) -#define QTAILQ_LAST(head) ((__typeof__((head)->tqh_first)) QTAILQ_LINK_PREV((head)->tqh_circ)) -#define QTAILQ_PREV(elm, field) ((__typeof__((elm)->field.tqe_next)) QTAILQ_LINK_PREV((elm)->field.tqe_circ)) +#define QTAILQ_LAST(head) ((typeof((head)->tqh_first)) QTAILQ_LINK_PREV((head)->tqh_circ)) +#define QTAILQ_PREV(elm, field) ((typeof((elm)->field.tqe_next)) QTAILQ_LINK_PREV((elm)->field.tqe_circ)) #define field_at_offset(base, offset, type) ((type *) (((char *) (base)) + (offset))) @@ -478,8 +528,33 @@ typedef struct QTailQLink { QTAILQ_RAW_TQH_CIRC(head)->tql_prev = QTAILQ_RAW_TQE_CIRC(elm, entry); \ } while (/*CONSTCOND*/ 0) -#ifdef __cplusplus -} -#endif +#define QLIST_RAW_FIRST(head) field_at_offset(head, 0, void *) + +#define QLIST_RAW_NEXT(elm, entry) field_at_offset(elm, entry, void *) + +#define QLIST_RAW_PREVIOUS(elm, entry) field_at_offset(elm, entry + sizeof(void *), void *) -#endif /* LIBQ_SYS_QUEUE_H */ +#define QLIST_RAW_FOREACH(elm, head, entry) \ + for ((elm) = *QLIST_RAW_FIRST(head); (elm); (elm) = *QLIST_RAW_NEXT(elm, entry)) + +#define QLIST_RAW_INSERT_AFTER(head, prev, elem, entry) \ + do { \ + *QLIST_RAW_NEXT(prev, entry) = elem; \ + *QLIST_RAW_PREVIOUS(elem, entry) = QLIST_RAW_NEXT(prev, entry); \ + *QLIST_RAW_NEXT(elem, entry) = NULL; \ + } while (0) + +#define QLIST_RAW_INSERT_HEAD(head, elm, entry) \ + do { \ + void *first = *QLIST_RAW_FIRST(head); \ + *QLIST_RAW_FIRST(head) = elm; \ + *QLIST_RAW_PREVIOUS(elm, entry) = QLIST_RAW_FIRST(head); \ + if (first) { \ + *QLIST_RAW_NEXT(elm, entry) = first; \ + *QLIST_RAW_PREVIOUS(first, entry) = QLIST_RAW_NEXT(elm, entry); \ + } else { \ + *QLIST_RAW_NEXT(elm, entry) = NULL; \ + } \ + } while (0) + +#endif /* QEMU_SYS_QUEUE_H */ diff --git a/libutils/include/utils/config-host.h b/libutils/include/utils/config-host.h index 824f3c087..2c9308df9 100644 --- a/libutils/include/utils/config-host.h +++ b/libutils/include/utils/config-host.h @@ -37,6 +37,25 @@ #define CONFIG_MADVISE 1 #define CONFIG_POSIX_MEMALIGN 1 +// pthread_condattr_setclock is plain POSIX; glibc always provides it. +#define CONFIG_PTHREAD_CONDATTR_SETCLOCK 1 + +// GNU extensions, in glibc since 2.12. glibc only declares them under +// _GNU_SOURCE, which libutils/src/CMakeLists.txt defines as upstream meson does. +#define CONFIG_PTHREAD_SETNAME_NP_W_TID 1 +#define CONFIG_PTHREAD_GETNAME_NP 1 +#define CONFIG_PTHREAD_AFFINITY_NP 1 + +// malloc_trim is glibc; rcu.c uses it to return freed memory to the OS. +#define CONFIG_MALLOC_TRIM 1 + +// Upstream sets these from meson's host_os; every supported host is POSIX. +// utils/futex.h keys HAVE_FUTEX on CONFIG_LINUX. +#define CONFIG_POSIX 1 +#ifdef __linux__ +#define CONFIG_LINUX 1 +#endif + // Upstream only enables AVX2 when cpuid.h is usable; keep that dependency. #ifdef CONFIG_CPUID_H #define CONFIG_AVX2_OPT 1 diff --git a/libutils/include/utils/coroutine-tls.h b/libutils/include/utils/coroutine-tls.h new file mode 100644 index 000000000..9ff397255 --- /dev/null +++ b/libutils/include/utils/coroutine-tls.h @@ -0,0 +1,178 @@ +/* + * QEMU Thread Local Storage for coroutines + * + * Copyright Red Hat + * + * SPDX-License-Identifier: LGPL-2.1-or-later + * + * This work is licensed under the terms of the GNU LGPL, version 2.1 or later. + * See the COPYING.LIB file in the top-level directory. + * + * It is forbidden to access Thread Local Storage in coroutines because + * compiler optimizations may cause values to be cached across coroutine + * re-entry. Coroutines can run in more than one thread through the course of + * their life, leading bugs when stale TLS values from the wrong thread are + * used as a result of compiler optimization. + * + * An example is: + * + * ..code-block:: c + * :caption: A coroutine that may see the wrong TLS value + * + * static __thread AioContext *current_aio_context; + * ... + * static void coroutine_fn foo(void) + * { + * aio_notify(current_aio_context); + * qemu_coroutine_yield(); + * aio_notify(current_aio_context); // <-- may be stale after yielding! + * } + * + * This header provides macros for safely defining variables in Thread Local + * Storage: + * + * ..code-block:: c + * :caption: A coroutine that safely uses TLS + * + * QEMU_DEFINE_STATIC_CO_TLS(AioContext *, current_aio_context) + * ... + * static void coroutine_fn foo(void) + * { + * aio_notify(get_current_aio_context()); + * qemu_coroutine_yield(); + * aio_notify(get_current_aio_context()); // <-- safe + * } + */ + +#ifndef QEMU_COROUTINE_TLS_H +#define QEMU_COROUTINE_TLS_H + +/* + * To stop the compiler from caching TLS values we define accessor functions + * with __attribute__((noinline)) plus asm volatile("") to prevent + * optimizations that override noinline. + * + * The compiler can still analyze noinline code and make optimizations based on + * that knowledge, so an inline asm output operand is used to prevent + * optimizations that make assumptions about the address of the TLS variable. + * + * This is fragile and ultimately needs to be solved by a mechanism that is + * guaranteed to work by the compiler (e.g. stackless coroutines), but for now + * we use this approach to prevent issues. + */ + +/** + * QEMU_DECLARE_CO_TLS: + * @type: the variable's C type + * @var: the variable name + * + * Declare an extern variable in Thread Local Storage from a header file: + * + * .. code-block:: c + * :caption: Declaring an extern variable in Thread Local Storage + * + * QEMU_DECLARE_CO_TLS(int, my_count) + * ... + * int c = get_my_count(); + * set_my_count(c + 1); + * *get_ptr_my_count() = 0; + * + * This is a coroutine-safe replacement for the __thread keyword and is + * equivalent to the following code: + * + * .. code-block:: c + * :caption: Declaring a TLS variable using __thread + * + * extern __thread int my_count; + * ... + * int c = my_count; + * my_count = c + 1; + * *(&my_count) = 0; + */ +#define QEMU_DECLARE_CO_TLS(type, var) \ + __attribute__((noinline)) type get_##var(void); \ + __attribute__((noinline)) void set_##var(type v); \ + __attribute__((noinline)) type *get_ptr_##var(void); + +/** + * QEMU_DEFINE_CO_TLS: + * @type: the variable's C type + * @var: the variable name + * + * Define a variable in Thread Local Storage that was previously declared from + * a header file with QEMU_DECLARE_CO_TLS(): + * + * .. code-block:: c + * :caption: Defining a variable in Thread Local Storage + * + * QEMU_DEFINE_CO_TLS(int, my_count) + * + * This is a coroutine-safe replacement for the __thread keyword and is + * equivalent to the following code: + * + * .. code-block:: c + * :caption: Defining a TLS variable using __thread + * + * __thread int my_count; + */ +#define QEMU_DEFINE_CO_TLS(type, var) \ + static __thread type co_tls_##var; \ + type get_##var(void) { \ + asm volatile(""); \ + return co_tls_##var; \ + } \ + void set_##var(type v) { \ + asm volatile(""); \ + co_tls_##var = v; \ + } \ + type *get_ptr_##var(void) { \ + type *ptr = &co_tls_##var; \ + asm volatile("" : "+rm"(ptr)); \ + return ptr; \ + } + +/** + * QEMU_DEFINE_STATIC_CO_TLS: + * @type: the variable's C type + * @var: the variable name + * + * Define a static variable in Thread Local Storage: + * + * .. code-block:: c + * :caption: Defining a static variable in Thread Local Storage + * + * QEMU_DEFINE_STATIC_CO_TLS(int, my_count) + * ... + * int c = get_my_count(); + * set_my_count(c + 1); + * *get_ptr_my_count() = 0; + * + * This is a coroutine-safe replacement for the __thread keyword and is + * equivalent to the following code: + * + * .. code-block:: c + * :caption: Defining a static TLS variable using __thread + * + * static __thread int my_count; + * ... + * int c = my_count; + * my_count = c + 1; + * *(&my_count) = 0; + */ +#define QEMU_DEFINE_STATIC_CO_TLS(type, var) \ + static __thread type co_tls_##var; \ + static __attribute__((noinline, unused)) type get_##var(void) { \ + asm volatile(""); \ + return co_tls_##var; \ + } \ + static __attribute__((noinline, unused)) void set_##var(type v) { \ + asm volatile(""); \ + co_tls_##var = v; \ + } \ + static __attribute__((noinline, unused)) type *get_ptr_##var(void) { \ + type *ptr = &co_tls_##var; \ + asm volatile("" : "+rm"(ptr)); \ + return ptr; \ + } + +#endif /* QEMU_COROUTINE_TLS_H */ diff --git a/libutils/include/utils/futex.h b/libutils/include/utils/futex.h new file mode 100644 index 000000000..02a34f7f1 --- /dev/null +++ b/libutils/include/utils/futex.h @@ -0,0 +1,70 @@ +/* + * Wrappers around Linux futex syscall and similar + * + * Copyright Red Hat, Inc. 2017 + * + * Author: + * Paolo Bonzini + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + */ + +/* + * Note that a wake-up can also be caused by common futex usage patterns in + * unrelated code that happened to have previously used the futex word's + * memory location (e.g., typical futex-based implementations of Pthreads + * mutexes can cause this under some conditions). Therefore, qemu_futex_wait() + * callers should always conservatively assume that it is a spurious wake-up, + * and use the futex word's value (i.e., the user-space synchronization scheme) + * to decide whether to continue to block or not. + */ + +#ifndef QEMU_FUTEX_H +#define QEMU_FUTEX_H + +#include + +#define HAVE_FUTEX + +#ifdef CONFIG_LINUX +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define qemu_futex(...) syscall(__NR_futex, __VA_ARGS__) + +static inline void qemu_futex_wake_all(void *f) { + qemu_futex(f, FUTEX_WAKE, INT_MAX, NULL, NULL, 0); +} + +static inline void qemu_futex_wake_single(void *f) { + qemu_futex(f, FUTEX_WAKE, 1, NULL, NULL, 0); +} + +static inline void qemu_futex_wait(void *f, unsigned val) { + while (qemu_futex(f, FUTEX_WAIT, (int) val, NULL, NULL, 0)) { + switch (errno) { + case EWOULDBLOCK: + return; + case EINTR: + break; /* get out of switch and retry */ + default: + abort(); + } + } +} + +#ifdef __cplusplus +} +#endif + +#else +#undef HAVE_FUTEX +#endif + +#endif /* QEMU_FUTEX_H */ diff --git a/libutils/include/utils/lockable.h b/libutils/include/utils/lockable.h new file mode 100644 index 000000000..d5801ba70 --- /dev/null +++ b/libutils/include/utils/lockable.h @@ -0,0 +1,172 @@ +/* + * Polymorphic locking functions (aka poor man templates) + * + * Copyright Red Hat, Inc. 2017, 2018 + * + * Author: Paolo Bonzini + * + * This work is licensed under the terms of the GNU LGPL, version 2 or later. + * See the COPYING.LIB file in the top-level directory. + * + */ + +#ifndef QEMU_LOCKABLE_H +#define QEMU_LOCKABLE_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void QemuLockUnlockFunc(void *); + +typedef struct QemuLockable { + void *object; + QemuLockUnlockFunc *lock; + QemuLockUnlockFunc *unlock; +} QemuLockable; + +static inline __attribute__((__always_inline__)) QemuLockable *qemu_make_lockable(void *x, QemuLockable *lockable) { + /* + * We cannot test this in a macro, otherwise we get compiler + * warnings like "the address of 'm' will always evaluate as 'true'". + */ + return x ? lockable : NULL; +} + +static inline __attribute__((__always_inline__)) QemuLockable *qemu_null_lockable(void *x) { + if (x != NULL) { + qemu_build_not_reached(); + } + return NULL; +} + +#define QML_FUNC_(name) \ + static inline void qemu_lockable_##name##_lock(void *x) { \ + qemu_##name##_lock(x); \ + } \ + static inline void qemu_lockable_##name##_unlock(void *x) { \ + qemu_##name##_unlock(x); \ + } + +/* Upstream also instantiates co_mutex; coroutine locks are not vendored. */ +QML_FUNC_(mutex) +QML_FUNC_(rec_mutex) +QML_FUNC_(spin) + +/* + * In C, compound literals have the lifetime of an automatic variable. + * In C++ it would be different, but then C++ wouldn't need QemuLockable + * either... + */ +#define QML_OBJ_(x, name) \ + (&(QemuLockable) {.object = (x), .lock = qemu_lockable_##name##_lock, .unlock = qemu_lockable_##name##_unlock}) + +/** + * QEMU_MAKE_LOCKABLE - Make a polymorphic QemuLockable + * + * @x: a lock object (currently one of QemuMutex, QemuRecMutex, QemuSpin). + * + * Returns a QemuLockable object that can be passed around + * to a function that can operate with locks of any kind, or + * NULL if @x is %NULL. + * + * Note the special case for void *, so that we may pass "NULL". + */ +#define QEMU_MAKE_LOCKABLE(x) \ + _Generic((x), \ + QemuLockable *: (x), \ + void *: qemu_null_lockable(x), \ + QemuMutex *: qemu_make_lockable(x, QML_OBJ_(x, mutex)), \ + QemuRecMutex *: qemu_make_lockable(x, QML_OBJ_(x, rec_mutex)), \ + QemuSpin *: qemu_make_lockable(x, QML_OBJ_(x, spin))) + +/** + * QEMU_MAKE_LOCKABLE_NONNULL - Make a polymorphic QemuLockable + * + * @x: a lock object (currently one of QemuMutex, QemuRecMutex, QemuSpin). + * + * Returns a QemuLockable object that can be passed around + * to a function that can operate with locks of any kind. + */ +#define QEMU_MAKE_LOCKABLE_NONNULL(x) \ + _Generic((x), \ + QemuLockable *: (x), \ + QemuMutex *: QML_OBJ_(x, mutex), \ + QemuRecMutex *: QML_OBJ_(x, rec_mutex), \ + QemuSpin *: QML_OBJ_(x, spin)) + +static inline void qemu_lockable_lock(QemuLockable *x) { + x->lock(x->object); +} + +static inline void qemu_lockable_unlock(QemuLockable *x) { + x->unlock(x->object); +} + +static inline QemuLockable *qemu_lockable_auto_lock(QemuLockable *x) { + qemu_lockable_lock(x); + return x; +} + +static inline void qemu_lockable_auto_unlock(QemuLockable *x) { + if (x) { + qemu_lockable_unlock(x); + } +} + +G_DEFINE_AUTOPTR_CLEANUP_FUNC(QemuLockable, qemu_lockable_auto_unlock) + +#define WITH_QEMU_LOCK_GUARD_(x, var) \ + for (g_autoptr(QemuLockable) var = qemu_lockable_auto_lock(QEMU_MAKE_LOCKABLE_NONNULL((x))); var; \ + qemu_lockable_auto_unlock(var), var = NULL) + +/** + * WITH_QEMU_LOCK_GUARD - Lock a lock object for scope + * + * @x: a lock object (currently one of QemuMutex, QemuSpin). + * + * This macro defines a lock scope such that entering the scope takes the lock + * and leaving the scope releases the lock. Return statements are allowed + * within the scope and release the lock. Break and continue statements leave + * the scope early and release the lock. + * + * WITH_QEMU_LOCK_GUARD(&mutex) { + * ... + * if (error) { + * return; <-- mutex is automatically unlocked + * } + * + * if (early_exit) { + * break; <-- leave this scope early + * } + * ... + * } + */ +#define WITH_QEMU_LOCK_GUARD(x) WITH_QEMU_LOCK_GUARD_((x), glue(qemu_lockable_auto, __COUNTER__)) + +/** + * QEMU_LOCK_GUARD - Lock an object until the end of the scope + * + * @x: a lock object (currently one of QemuMutex, QemuSpin). + * + * This macro takes a lock until the end of the scope. Return statements + * release the lock. + * + * ... <-- mutex not locked + * QEMU_LOCK_GUARD(&mutex); <-- mutex locked from here onwards + * ... + * if (error) { + * return; <-- mutex is automatically unlocked + * } + */ +#define QEMU_LOCK_GUARD(x) \ + g_autoptr(QemuLockable) glue(qemu_lockable_auto, __COUNTER__) G_GNUC_UNUSED = \ + qemu_lockable_auto_lock(QEMU_MAKE_LOCKABLE((x))) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libutils/include/utils/mutex.h b/libutils/include/utils/mutex.h deleted file mode 100644 index 04a7e6fbb..000000000 --- a/libutils/include/utils/mutex.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2019 Cyberhaven -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#ifndef _TCG_MUTEX_H_ - -#define _TCG_MUTEX_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct _mutex_t { - pthread_mutex_t mutex; -} mutex_t; - -static inline void mutex_init(mutex_t *m) { - int ret = pthread_mutex_init(&m->mutex, NULL); - if (ret < 0) { - abort(); - } -} - -static inline void mutex_lock(mutex_t *m) { - pthread_mutex_lock(&m->mutex); -} - -static inline void mutex_unlock(mutex_t *m) { - pthread_mutex_unlock(&m->mutex); -} - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libutils/include/utils/notify.h b/libutils/include/utils/notify.h new file mode 100644 index 000000000..244d33c13 --- /dev/null +++ b/libutils/include/utils/notify.h @@ -0,0 +1,53 @@ +/* + * Notifier lists + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Anthony Liguori + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +#ifndef QEMU_NOTIFY_H +#define QEMU_NOTIFY_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Notifier Notifier; + +struct Notifier { + void (*notify)(Notifier *notifier, void *data); + QLIST_ENTRY(Notifier) node; +}; + +typedef struct NotifierList { + QLIST_HEAD(, Notifier) notifiers; +} NotifierList; + +#define NOTIFIER_LIST_INITIALIZER(head) {QLIST_HEAD_INITIALIZER((head).notifiers)} + +void notifier_list_init(NotifierList *list); + +void notifier_list_add(NotifierList *list, Notifier *notifier); + +void notifier_remove(Notifier *notifier); + +void notifier_list_notify(NotifierList *list, void *data); + +bool notifier_list_empty(NotifierList *list); + +/* Upstream also provides NotifierWithReturn, which depends on the Error API. */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libutils/include/utils/processor.h b/libutils/include/utils/processor.h new file mode 100644 index 000000000..048f0125d --- /dev/null +++ b/libutils/include/utils/processor.h @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2016, Emilio G. Cota + * + * License: GNU GPL, version 2. + * See the COPYING file in the top-level directory. + */ +#ifndef QEMU_PROCESSOR_H +#define QEMU_PROCESSOR_H + +#if defined(__x86_64__) +#define cpu_relax() asm volatile("rep; nop" ::: "memory") + +#elif defined(__aarch64__) +#define cpu_relax() asm volatile("yield" ::: "memory") + +#elif defined(__powerpc64__) +/* set Hardware Multi-Threading (HMT) priority to low; then back to medium */ +#define cpu_relax() \ + asm volatile("or 1, 1, 1;" \ + "or 2, 2, 2;" :: \ + : "memory") + +#else +#define cpu_relax() barrier() +#endif + +#endif /* QEMU_PROCESSOR_H */ diff --git a/libutils/include/utils/qht.h b/libutils/include/utils/qht.h new file mode 100644 index 000000000..1703a21d6 --- /dev/null +++ b/libutils/include/utils/qht.h @@ -0,0 +1,192 @@ +/* + * Copyright (C) 2016, Emilio G. Cota + * + * License: GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ +#ifndef QEMU_QHT_H +#define QEMU_QHT_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef bool (*qht_cmp_func_t)(const void *a, const void *b); + +struct qht { + struct qht_map *map; + qht_cmp_func_t cmp; + QemuMutex lock; /* serializes setters of ht->map */ + unsigned int mode; +}; + +/* + * Upstream also provides qht_statistics_init/destroy and struct qht_stats. + * They are the only users of qdist, which is not vendored, so they are + * removed together with it. + */ + +typedef bool (*qht_lookup_func_t)(const void *obj, const void *userp); +typedef void (*qht_iter_func_t)(void *p, uint32_t h, void *up); +typedef bool (*qht_iter_bool_func_t)(void *p, uint32_t h, void *up); + +#define QHT_MODE_AUTO_RESIZE 0x1 /* auto-resize when heavily loaded */ +#define QHT_MODE_RAW_MUTEXES 0x2 /* bypass the profiler (QSP) */ + +/** + * qht_init - Initialize a QHT + * @ht: QHT to be initialized + * @cmp: default comparison function. Cannot be NULL. + * @n_elems: number of entries the hash table should be optimized for. + * @mode: bitmask with OR'ed QHT_MODE_* + */ +void qht_init(struct qht *ht, qht_cmp_func_t cmp, size_t n_elems, unsigned int mode); + +/** + * qht_destroy - destroy a previously initialized QHT + * @ht: QHT to be destroyed + * + * Call only when there are no readers/writers left. + */ +void qht_destroy(struct qht *ht); + +/** + * qht_insert - Insert a pointer into the hash table + * @ht: QHT to insert to + * @p: pointer to be inserted + * @hash: hash corresponding to @p + * @existing: address where the pointer to an existing entry can be copied to + * + * Attempting to insert a NULL @p is a bug. + * Inserting the same pointer @p with different @hash values is a bug. + * + * In case of successful operation, smp_wmb() is implied before the pointer is + * inserted into the hash table. + * + * Returns true on success. + * Returns false if there is an existing entry in the table that is equivalent + * (i.e. ht->cmp matches and the hash is the same) to @p-@h. If @existing + * is !NULL, a pointer to this existing entry is copied to it. + */ +bool qht_insert(struct qht *ht, void *p, uint32_t hash, void **existing); + +/** + * qht_lookup_custom - Look up a pointer using a custom comparison function. + * @ht: QHT to be looked up + * @userp: pointer to pass to @func + * @hash: hash of the pointer to be looked up + * @func: function to compare existing pointers against @userp + * + * Needs to be called under an RCU read-critical section. + * + * smp_read_barrier_depends() is implied before the call to @func. + * + * The user-provided @func compares pointers in QHT against @userp. + * If the function returns true, a match has been found. + * + * Returns the corresponding pointer when a match is found. + * Returns NULL otherwise. + */ +void *qht_lookup_custom(const struct qht *ht, const void *userp, uint32_t hash, qht_lookup_func_t func); + +/** + * qht_lookup - Look up a pointer in a QHT + * @ht: QHT to be looked up + * @userp: pointer to pass to the comparison function + * @hash: hash of the pointer to be looked up + * + * Calls qht_lookup_custom() using @ht's default comparison function. + */ +void *qht_lookup(const struct qht *ht, const void *userp, uint32_t hash); + +/** + * qht_remove - remove a pointer from the hash table + * @ht: QHT to remove from + * @p: pointer to be removed + * @hash: hash corresponding to @p + * + * Attempting to remove a NULL @p is a bug. + * + * Just-removed @p pointers cannot be immediately freed; they need to remain + * valid until the end of the RCU grace period in which qht_remove() is called. + * This guarantees that concurrent lookups will always compare against valid + * data. + * + * Returns true on success. + * Returns false if the @p-@hash pair was not found. + */ +bool qht_remove(struct qht *ht, const void *p, uint32_t hash); + +/** + * qht_reset - reset a QHT + * @ht: QHT to be reset + * + * All entries in the hash table are reset. No resizing is performed. + * + * If concurrent readers may exist, the objects pointed to by the hash table + * must remain valid for the existing RCU grace period -- see qht_remove(). + * See also: qht_reset_size() + */ +void qht_reset(struct qht *ht); + +/** + * qht_reset_size - reset and resize a QHT + * @ht: QHT to be reset and resized + * @n_elems: number of entries the resized hash table should be optimized for. + * + * Returns true if the resize was necessary and therefore performed. + * Returns false otherwise. + * + * If concurrent readers may exist, the objects pointed to by the hash table + * must remain valid for the existing RCU grace period -- see qht_remove(). + * See also: qht_reset(), qht_resize(). + */ +bool qht_reset_size(struct qht *ht, size_t n_elems); + +/** + * qht_resize - resize a QHT + * @ht: QHT to be resized + * @n_elems: number of entries the resized hash table should be optimized for + * + * Returns true on success. + * Returns false if the resize was not necessary and therefore not performed. + * See also: qht_reset_size(). + */ +bool qht_resize(struct qht *ht, size_t n_elems); + +/** + * qht_iter - Iterate over a QHT + * @ht: QHT to be iterated over + * @func: function to be called for each entry in QHT + * @userp: additional pointer to be passed to @func + * + * Each time it is called, user-provided @func is passed a pointer-hash pair, + * plus @userp. + * + * Note: @ht cannot be accessed from @func + * See also: qht_iter_remove() + */ +void qht_iter(struct qht *ht, qht_iter_func_t func, void *userp); + +/** + * qht_iter_remove - Iterate over a QHT, optionally removing entries + * @ht: QHT to be iterated over + * @func: function to be called for each entry in QHT + * @userp: additional pointer to be passed to @func + * + * Each time it is called, user-provided @func is passed a pointer-hash pair, + * plus @userp. If @func returns true, the pointer-hash pair is removed. + * + * Note: @ht cannot be accessed from @func + * See also: qht_iter() + */ +void qht_iter_remove(struct qht *ht, qht_iter_bool_func_t func, void *userp); + +#ifdef __cplusplus +} +#endif + +#endif /* QEMU_QHT_H */ diff --git a/libutils/include/utils/rcu.h b/libutils/include/utils/rcu.h new file mode 100644 index 000000000..ddf054cb4 --- /dev/null +++ b/libutils/include/utils/rcu.h @@ -0,0 +1,196 @@ +#ifndef QEMU_RCU_H +#define QEMU_RCU_H + +/* + * urcu-mb.h + * + * Userspace RCU header with explicit memory barrier. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see + * . + * + * IBM's contributions to this file may be relicensed under LGPLv2 or later. + */ + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Important ! + * + * Each thread containing read-side critical sections must be registered + * with rcu_register_thread() before calling rcu_read_lock(). + * rcu_unregister_thread() should be called before the thread exits. + */ + +#ifdef DEBUG_RCU +#define rcu_assert(args...) assert(args) +#else +#define rcu_assert(args...) +#endif + +/* + * Global quiescent period counter with low-order bits unused. + * Using a int rather than a char to eliminate false register dependencies + * causing stalls on some architectures. + */ +extern unsigned long rcu_gp_ctr; + +extern QemuEvent rcu_gp_event; + +struct rcu_reader_data { + /* Data used by both reader and synchronize_rcu() */ + unsigned long ctr; + bool waiting; + + /* Data used by reader only */ + unsigned depth; + + /* Data used for registry, protected by rcu_registry_lock */ + QLIST_ENTRY(rcu_reader_data) node; + + /* + * NotifierList used to force an RCU grace period. Accessed under + * rcu_registry_lock. Note that the notifier is called _outside_ + * the thread! + */ + NotifierList force_rcu; +}; + +QEMU_DECLARE_CO_TLS(struct rcu_reader_data, rcu_reader) + +static inline void rcu_read_lock(void) { + struct rcu_reader_data *p_rcu_reader = get_ptr_rcu_reader(); + unsigned ctr; + + if (p_rcu_reader->depth++ > 0) { + return; + } + + ctr = qatomic_read(&rcu_gp_ctr); + qatomic_set(&p_rcu_reader->ctr, ctr); + + /* + * Read rcu_gp_ptr and write p_rcu_reader->ctr before reading + * RCU-protected pointers. + */ + smp_mb_placeholder(); +} + +static inline void rcu_read_unlock(void) { + struct rcu_reader_data *p_rcu_reader = get_ptr_rcu_reader(); + + assert(p_rcu_reader->depth != 0); + if (--p_rcu_reader->depth > 0) { + return; + } + + /* Ensure that the critical section is seen to precede the + * store to p_rcu_reader->ctr. Together with the following + * smp_mb_placeholder(), this ensures writes to p_rcu_reader->ctr + * are sequentially consistent. + */ + qatomic_store_release(&p_rcu_reader->ctr, 0); + + /* Write p_rcu_reader->ctr before reading p_rcu_reader->waiting. */ + smp_mb_placeholder(); + if (unlikely(qatomic_read(&p_rcu_reader->waiting))) { + qatomic_set(&p_rcu_reader->waiting, false); + qemu_event_set(&rcu_gp_event); + } +} + +void synchronize_rcu(void); + +/* + * Reader thread registration. + */ +void rcu_register_thread(void); +void rcu_unregister_thread(void); + +/* + * Support for fork(). fork() support is enabled at startup. + */ +void rcu_enable_atfork(void); +void rcu_disable_atfork(void); + +struct rcu_head; +typedef void RCUCBFunc(struct rcu_head *head); + +struct rcu_head { + struct rcu_head *next; + RCUCBFunc *func; +}; + +void call_rcu1(struct rcu_head *head, RCUCBFunc *func); +void drain_call_rcu(void); + +/* The operands of the minus operator must have the same type, + * which must be the one that we specify in the cast. + */ +#define call_rcu(head, func, field) \ + call_rcu1(({ \ + char __attribute__((unused)) offset_must_be_zero[-offsetof(typeof(*(head)), field)], \ + func_type_invalid = (func) - (void (*)(typeof(head)))(func); \ + &(head)->field; \ + }), \ + (RCUCBFunc *) (func)) + +#define g_free_rcu(obj, field) \ + call_rcu1(({ \ + char __attribute__((unused)) offset_must_be_zero[-offsetof(typeof(*(obj)), field)]; \ + &(obj)->field; \ + }), \ + (RCUCBFunc *) g_free); + +typedef void RCUReadAuto; +static inline RCUReadAuto *rcu_read_auto_lock(void) { + rcu_read_lock(); + /* Anything non-NULL causes the cleanup function to be called */ + return (void *) (uintptr_t) 0x1; +} + +static inline void rcu_read_auto_unlock(RCUReadAuto *r) { + rcu_read_unlock(); +} + +G_DEFINE_AUTOPTR_CLEANUP_FUNC(RCUReadAuto, rcu_read_auto_unlock) + +#define WITH_RCU_READ_LOCK_GUARD() WITH_RCU_READ_LOCK_GUARD_(glue(_rcu_read_auto, __COUNTER__)) + +#define WITH_RCU_READ_LOCK_GUARD_(var) \ + for (g_autoptr(RCUReadAuto) var = rcu_read_auto_lock(); (var); rcu_read_auto_unlock(var), (var) = NULL) + +#define RCU_READ_LOCK_GUARD() g_autoptr(RCUReadAuto) _rcu_read_auto __attribute__((unused)) = rcu_read_auto_lock() + +/* + * Force-RCU notifiers tell readers that they should exit their + * read-side critical section. + */ +void rcu_add_force_rcu_notifier(Notifier *n); +void rcu_remove_force_rcu_notifier(Notifier *n); + +#ifdef __cplusplus +} +#endif + +#endif /* QEMU_RCU_H */ diff --git a/libutils/include/utils/seqlock.h b/libutils/include/utils/seqlock.h new file mode 100644 index 000000000..c04a9aef7 --- /dev/null +++ b/libutils/include/utils/seqlock.h @@ -0,0 +1,83 @@ +/* + * Seqlock implementation for QEMU + * + * Copyright Red Hat, Inc. 2013 + * + * Author: + * Paolo Bonzini + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + */ + +#ifndef QEMU_SEQLOCK_H +#define QEMU_SEQLOCK_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct QemuSeqLock QemuSeqLock; + +struct QemuSeqLock { + unsigned sequence; +}; + +static inline void seqlock_init(QemuSeqLock *sl) { + sl->sequence = 0; +} + +/* Lock out other writers and update the count. */ +static inline void seqlock_write_begin(QemuSeqLock *sl) { + qatomic_set(&sl->sequence, sl->sequence + 1); + + /* Write sequence before updating other fields. */ + smp_wmb(); +} + +static inline void seqlock_write_end(QemuSeqLock *sl) { + /* Write other fields before finalizing sequence. */ + smp_wmb(); + + qatomic_set(&sl->sequence, sl->sequence + 1); +} + +/* Lock out other writers and update the count. */ +static inline void seqlock_write_lock_impl(QemuSeqLock *sl, QemuLockable *lock) { + qemu_lockable_lock(lock); + seqlock_write_begin(sl); +} +#define seqlock_write_lock(sl, lock) seqlock_write_lock_impl(sl, QEMU_MAKE_LOCKABLE(lock)) + +/* Update the count and release the lock. */ +static inline void seqlock_write_unlock_impl(QemuSeqLock *sl, QemuLockable *lock) { + seqlock_write_end(sl); + qemu_lockable_unlock(lock); +} +#define seqlock_write_unlock(sl, lock) seqlock_write_unlock_impl(sl, QEMU_MAKE_LOCKABLE(lock)) + +static inline unsigned seqlock_read_begin(const QemuSeqLock *sl) { + /* Always fail if a write is in progress. */ + unsigned ret = qatomic_read(&sl->sequence); + + /* Read sequence before reading other fields. */ + smp_rmb(); + return ret & ~1; +} + +static inline int seqlock_read_retry(const QemuSeqLock *sl, unsigned start) { + /* Read other fields before reading final sequence. */ + smp_rmb(); + return unlikely(qatomic_read(&sl->sequence) != start); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libutils/include/utils/sys_membarrier.h b/libutils/include/utils/sys_membarrier.h new file mode 100644 index 000000000..c38d7fb83 --- /dev/null +++ b/libutils/include/utils/sys_membarrier.h @@ -0,0 +1,28 @@ +/* + * Process-global memory barriers + * + * Copyright (c) 2018 Red Hat, Inc. + * + * Author: Paolo Bonzini + */ + +#ifndef QEMU_SYS_MEMBARRIER_H +#define QEMU_SYS_MEMBARRIER_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Keep it simple, execute a real memory barrier on both sides. */ +static inline void smp_mb_global_init(void) { +} +#define smp_mb_global() smp_mb() +#define smp_mb_placeholder() smp_mb() + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libutils/include/utils/thread-posix.h b/libutils/include/utils/thread-posix.h new file mode 100644 index 000000000..758808b70 --- /dev/null +++ b/libutils/include/utils/thread-posix.h @@ -0,0 +1,39 @@ +#ifndef QEMU_THREAD_POSIX_H +#define QEMU_THREAD_POSIX_H + +#include +#include + +struct QemuMutex { + pthread_mutex_t lock; +#ifdef CONFIG_DEBUG_MUTEX + const char *file; + int line; +#endif + bool initialized; +}; + +/* + * QemuRecMutex cannot be a typedef of QemuMutex lest we have two + * compatible cases in _Generic. See qemu/lockable.h. + */ +typedef struct QemuRecMutex { + QemuMutex m; +} QemuRecMutex; + +struct QemuCond { + pthread_cond_t cond; + bool initialized; +}; + +struct QemuSemaphore { + QemuMutex mutex; + QemuCond cond; + unsigned int count; +}; + +struct QemuThread { + pthread_t thread; +}; + +#endif diff --git a/libutils/include/utils/thread.h b/libutils/include/utils/thread.h new file mode 100644 index 000000000..5c2203afa --- /dev/null +++ b/libutils/include/utils/thread.h @@ -0,0 +1,236 @@ +#ifndef QEMU_THREAD_H +#define QEMU_THREAD_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Upstream declares these in qemu/typedefs.h, which is not vendored. */ +typedef struct QemuMutex QemuMutex; +typedef struct QemuSpin QemuSpin; + +typedef struct QemuCond QemuCond; +typedef struct QemuSemaphore QemuSemaphore; +typedef struct QemuLockCnt QemuLockCnt; +typedef struct QemuThread QemuThread; + +/* + * QemuEvent + * ========= + * + * QemuEvent is an implementation of Win32 manual-reset event object. + * For details, refer to: + * https://learn.microsoft.com/en-us/windows/win32/sync/using-event-objects + * + * QemuEvent is more lightweight than QemuSemaphore when HAVE_FUTEX is defined. + */ +typedef struct QemuEvent { +#ifndef HAVE_FUTEX + pthread_mutex_t lock; + pthread_cond_t cond; +#endif + unsigned value; + bool initialized; +} QemuEvent; + +#include + +#define QEMU_THREAD_JOINABLE 0 +#define QEMU_THREAD_DETACHED 1 + +void qemu_mutex_init(QemuMutex *mutex); +void qemu_mutex_destroy(QemuMutex *mutex); +int TSA_NO_TSA qemu_mutex_trylock_impl(QemuMutex *mutex, const char *file, const int line); +void TSA_NO_TSA qemu_mutex_lock_impl(QemuMutex *mutex, const char *file, const int line); +void TSA_NO_TSA qemu_mutex_unlock_impl(QemuMutex *mutex, const char *file, const int line); + +void qemu_rec_mutex_init(QemuRecMutex *mutex); +void qemu_rec_mutex_destroy(QemuRecMutex *mutex); +void qemu_rec_mutex_lock_impl(QemuRecMutex *mutex, const char *file, int line); +int qemu_rec_mutex_trylock_impl(QemuRecMutex *mutex, const char *file, int line); +void qemu_rec_mutex_unlock_impl(QemuRecMutex *mutex, const char *file, int line); + +/* + * Upstream routes these macros through function pointers so that the QSP + * profiler can interpose them; the profiler is not vendored, so they call + * the implementations directly and the __raw variants are aliases. + */ +#define qemu_mutex_lock__raw(m) qemu_mutex_lock_impl(m, __FILE__, __LINE__) +#define qemu_mutex_trylock__raw(m) qemu_mutex_trylock_impl(m, __FILE__, __LINE__) + +#define qemu_mutex_lock(m) qemu_mutex_lock_impl(m, __FILE__, __LINE__) +#define qemu_mutex_trylock(m) qemu_mutex_trylock_impl(m, __FILE__, __LINE__) +#define qemu_rec_mutex_lock(m) qemu_rec_mutex_lock_impl(m, __FILE__, __LINE__) +#define qemu_rec_mutex_trylock(m) qemu_rec_mutex_trylock_impl(m, __FILE__, __LINE__) +#define qemu_cond_wait(c, m) qemu_cond_wait_impl(c, m, __FILE__, __LINE__) +#define qemu_cond_timedwait(c, m, ms) qemu_cond_timedwait_impl(c, m, ms, __FILE__, __LINE__) + +#define qemu_mutex_unlock(mutex) qemu_mutex_unlock_impl(mutex, __FILE__, __LINE__) + +#define qemu_rec_mutex_unlock(mutex) qemu_rec_mutex_unlock_impl(mutex, __FILE__, __LINE__) + +static inline void(qemu_mutex_lock)(QemuMutex *mutex) { + qemu_mutex_lock(mutex); +} + +static inline int(qemu_mutex_trylock)(QemuMutex *mutex) { + return qemu_mutex_trylock(mutex); +} + +static inline void(qemu_mutex_unlock)(QemuMutex *mutex) { + qemu_mutex_unlock(mutex); +} + +static inline void(qemu_rec_mutex_lock)(QemuRecMutex *mutex) { + qemu_rec_mutex_lock(mutex); +} + +static inline int(qemu_rec_mutex_trylock)(QemuRecMutex *mutex) { + return qemu_rec_mutex_trylock(mutex); +} + +static inline void(qemu_rec_mutex_unlock)(QemuRecMutex *mutex) { + qemu_rec_mutex_unlock(mutex); +} + +void qemu_cond_init(QemuCond *cond); +void qemu_cond_destroy(QemuCond *cond); + +/* + * IMPORTANT: The implementation does not guarantee that pthread_cond_signal + * and pthread_cond_broadcast can be called except while the same mutex is + * held as in the corresponding pthread_cond_wait calls! + */ +void qemu_cond_signal(QemuCond *cond); +void qemu_cond_broadcast(QemuCond *cond); +void TSA_NO_TSA qemu_cond_wait_impl(QemuCond *cond, QemuMutex *mutex, const char *file, const int line); +bool qemu_cond_timedwait_impl(QemuCond *cond, QemuMutex *mutex, int ms, const char *file, const int line); + +static inline void(qemu_cond_wait)(QemuCond *cond, QemuMutex *mutex) { + qemu_cond_wait(cond, mutex); +} + +/* Returns true if timeout has not expired, and false otherwise */ +static inline bool(qemu_cond_timedwait)(QemuCond *cond, QemuMutex *mutex, int ms) { + return qemu_cond_timedwait(cond, mutex, ms); +} + +void qemu_sem_init(QemuSemaphore *sem, int init); +void qemu_sem_post(QemuSemaphore *sem); +void qemu_sem_wait(QemuSemaphore *sem); +int qemu_sem_timedwait(QemuSemaphore *sem, int ms); +void qemu_sem_destroy(QemuSemaphore *sem); + +void qemu_event_init(QemuEvent *ev, bool init); +void qemu_event_set(QemuEvent *ev); +void qemu_event_reset(QemuEvent *ev); +void qemu_event_wait(QemuEvent *ev); +void qemu_event_destroy(QemuEvent *ev); + +void qemu_thread_create(QemuThread *thread, const char *name, void *(*start_routine)(void *), void *arg, int mode); +int qemu_thread_set_affinity(QemuThread *thread, unsigned long *host_cpus, unsigned long nbits); +int qemu_thread_get_affinity(QemuThread *thread, unsigned long **host_cpus, unsigned long *nbits); +void *qemu_thread_join(QemuThread *thread); +void qemu_thread_get_self(QemuThread *thread); +bool qemu_thread_is_self(QemuThread *thread); +G_NORETURN void qemu_thread_exit(void *retval); +void qemu_thread_set_name(const char *name); +const char *qemu_thread_get_name(void); + +struct Notifier; +/** + * qemu_thread_atexit_add: + * @notifier: Notifier to add + * + * Add the specified notifier to a list which will be run via + * notifier_list_notify() when this thread exits (either by calling + * qemu_thread_exit() or by returning from its start_routine). + * The usual usage is that the caller passes a Notifier which is + * a per-thread variable; it can then use the callback to free + * other per-thread data. + * + * If the thread exits as part of the entire process exiting, + * it is unspecified whether notifiers are called or not. + */ +void qemu_thread_atexit_add(struct Notifier *notifier); +/** + * qemu_thread_atexit_remove: + * @notifier: Notifier to remove + * + * Remove the specified notifier from the thread-exit notification + * list. It is not valid to try to remove a notifier which is not + * on the list. + */ +void qemu_thread_atexit_remove(struct Notifier *notifier); + +#ifdef CONFIG_TSAN +#include +#endif + +struct QemuSpin { + int value; +}; + +static inline void qemu_spin_init(QemuSpin *spin) { + qatomic_set(&spin->value, 0); +#ifdef CONFIG_TSAN + __tsan_mutex_create(spin, __tsan_mutex_not_static); +#endif +} + +static inline void qemu_spin_destroy(QemuSpin *spin) { +#ifdef CONFIG_TSAN + __tsan_mutex_destroy(spin, __tsan_mutex_not_static); +#endif +} + +static inline void qemu_spin_lock(QemuSpin *spin) { +#ifdef CONFIG_TSAN + __tsan_mutex_pre_lock(spin, 0); +#endif + while (unlikely(qatomic_xchg(&spin->value, 1))) { + while (qatomic_read(&spin->value)) { + cpu_relax(); + } + } +#ifdef CONFIG_TSAN + __tsan_mutex_post_lock(spin, 0, 0); +#endif +} + +static inline bool qemu_spin_trylock(QemuSpin *spin) { +#ifdef CONFIG_TSAN + __tsan_mutex_pre_lock(spin, __tsan_mutex_try_lock); +#endif + bool busy = qatomic_xchg(&spin->value, true); +#ifdef CONFIG_TSAN + unsigned flags = __tsan_mutex_try_lock; + flags |= busy ? __tsan_mutex_try_lock_failed : 0; + __tsan_mutex_post_lock(spin, flags, 0); +#endif + return busy; +} + +static inline bool qemu_spin_locked(QemuSpin *spin) { + return qatomic_read(&spin->value); +} + +static inline void qemu_spin_unlock(QemuSpin *spin) { +#ifdef CONFIG_TSAN + __tsan_mutex_pre_unlock(spin, 0); +#endif + qatomic_store_release(&spin->value, 0); +#ifdef CONFIG_TSAN + __tsan_mutex_post_unlock(spin, 0); +#endif +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libutils/include/utils/xxhash.h b/libutils/include/utils/xxhash.h new file mode 100644 index 000000000..b149e59f2 --- /dev/null +++ b/libutils/include/utils/xxhash.h @@ -0,0 +1,223 @@ +/* + * xxHash - Fast Hash algorithm + * Copyright (C) 2012-2016, Yann Collet + * + * BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * + Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * You can contact the author at : + * - xxHash source repository : https://github.com/Cyan4973/xxHash + */ + +#ifndef QEMU_XXHASH_H +#define QEMU_XXHASH_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define PRIME32_1 2654435761U +#define PRIME32_2 2246822519U +#define PRIME32_3 3266489917U +#define PRIME32_4 668265263U +#define PRIME32_5 374761393U + +#define QEMU_XXHASH_SEED 1 + +/* + * xxhash32, customized for input variables that are not guaranteed to be + * contiguous in memory. + */ +static inline uint32_t qemu_xxhash8(uint64_t ab, uint64_t cd, uint64_t ef, uint32_t g, uint32_t h) { + uint32_t v1 = QEMU_XXHASH_SEED + PRIME32_1 + PRIME32_2; + uint32_t v2 = QEMU_XXHASH_SEED + PRIME32_2; + uint32_t v3 = QEMU_XXHASH_SEED + 0; + uint32_t v4 = QEMU_XXHASH_SEED - PRIME32_1; + uint32_t a = ab; + uint32_t b = ab >> 32; + uint32_t c = cd; + uint32_t d = cd >> 32; + uint32_t e = ef; + uint32_t f = ef >> 32; + uint32_t h32; + + v1 += a * PRIME32_2; + v1 = rol32(v1, 13); + v1 *= PRIME32_1; + + v2 += b * PRIME32_2; + v2 = rol32(v2, 13); + v2 *= PRIME32_1; + + v3 += c * PRIME32_2; + v3 = rol32(v3, 13); + v3 *= PRIME32_1; + + v4 += d * PRIME32_2; + v4 = rol32(v4, 13); + v4 *= PRIME32_1; + + h32 = rol32(v1, 1) + rol32(v2, 7) + rol32(v3, 12) + rol32(v4, 18); + h32 += 28; + + h32 += e * PRIME32_3; + h32 = rol32(h32, 17) * PRIME32_4; + + h32 += f * PRIME32_3; + h32 = rol32(h32, 17) * PRIME32_4; + + h32 += g * PRIME32_3; + h32 = rol32(h32, 17) * PRIME32_4; + + h32 += h * PRIME32_3; + h32 = rol32(h32, 17) * PRIME32_4; + + h32 ^= h32 >> 15; + h32 *= PRIME32_2; + h32 ^= h32 >> 13; + h32 *= PRIME32_3; + h32 ^= h32 >> 16; + + return h32; +} + +static inline uint32_t qemu_xxhash2(uint64_t ab) { + return qemu_xxhash8(ab, 0, 0, 0, 0); +} + +static inline uint32_t qemu_xxhash4(uint64_t ab, uint64_t cd) { + return qemu_xxhash8(ab, cd, 0, 0, 0); +} + +static inline uint32_t qemu_xxhash5(uint64_t ab, uint64_t cd, uint32_t e) { + return qemu_xxhash8(ab, cd, 0, e, 0); +} + +static inline uint32_t qemu_xxhash6(uint64_t ab, uint64_t cd, uint32_t e, uint32_t f) { + return qemu_xxhash8(ab, cd, 0, e, f); +} + +static inline uint32_t qemu_xxhash7(uint64_t ab, uint64_t cd, uint64_t ef, uint32_t g) { + return qemu_xxhash8(ab, cd, ef, g, 0); +} + +/* + * Component parts of the XXH64 algorithm from + * https://github.com/Cyan4973/xxHash/blob/v0.8.0/xxhash.h + * + * The complete algorithm looks like + * + * i = 0; + * if (len >= 32) { + * v1 = seed + XXH_PRIME64_1 + XXH_PRIME64_2; + * v2 = seed + XXH_PRIME64_2; + * v3 = seed + 0; + * v4 = seed - XXH_PRIME64_1; + * do { + * v1 = XXH64_round(v1, get64bits(input + i)); + * v2 = XXH64_round(v2, get64bits(input + i + 8)); + * v3 = XXH64_round(v3, get64bits(input + i + 16)); + * v4 = XXH64_round(v4, get64bits(input + i + 24)); + * } while ((i += 32) <= len); + * h64 = XXH64_mergerounds(v1, v2, v3, v4); + * } else { + * h64 = seed + XXH_PRIME64_5; + * } + * h64 += len; + * + * for (; i + 8 <= len; i += 8) { + * h64 ^= XXH64_round(0, get64bits(input + i)); + * h64 = rol64(h64, 27) * XXH_PRIME64_1 + XXH_PRIME64_4; + * } + * for (; i + 4 <= len; i += 4) { + * h64 ^= get32bits(input + i) * PRIME64_1; + * h64 = rol64(h64, 23) * XXH_PRIME64_2 + XXH_PRIME64_3; + * } + * for (; i < len; i += 1) { + * h64 ^= get8bits(input + i) * XXH_PRIME64_5; + * h64 = rol64(h64, 11) * XXH_PRIME64_1; + * } + * + * return XXH64_avalanche(h64) + * + * Exposing the pieces instead allows for simplified usage when + * the length is a known constant and the inputs are in registers. + */ +#define XXH_PRIME64_1 0x9E3779B185EBCA87ULL +#define XXH_PRIME64_2 0xC2B2AE3D27D4EB4FULL +#define XXH_PRIME64_3 0x165667B19E3779F9ULL +#define XXH_PRIME64_4 0x85EBCA77C2B2AE63ULL +#define XXH_PRIME64_5 0x27D4EB2F165667C5ULL + +static inline uint64_t XXH64_round(uint64_t acc, uint64_t input) { + return rol64(acc + input * XXH_PRIME64_2, 31) * XXH_PRIME64_1; +} + +static inline uint64_t XXH64_mergeround(uint64_t acc, uint64_t val) { + return (acc ^ XXH64_round(0, val)) * XXH_PRIME64_1 + XXH_PRIME64_4; +} + +static inline uint64_t XXH64_mergerounds(uint64_t v1, uint64_t v2, uint64_t v3, uint64_t v4) { + uint64_t h64; + + h64 = rol64(v1, 1) + rol64(v2, 7) + rol64(v3, 12) + rol64(v4, 18); + h64 = XXH64_mergeround(h64, v1); + h64 = XXH64_mergeround(h64, v2); + h64 = XXH64_mergeround(h64, v3); + h64 = XXH64_mergeround(h64, v4); + + return h64; +} + +static inline uint64_t XXH64_avalanche(uint64_t h64) { + h64 ^= h64 >> 33; + h64 *= XXH_PRIME64_2; + h64 ^= h64 >> 29; + h64 *= XXH_PRIME64_3; + h64 ^= h64 >> 32; + return h64; +} + +static inline uint64_t qemu_xxhash64_4(uint64_t a, uint64_t b, uint64_t c, uint64_t d) { + uint64_t v1 = QEMU_XXHASH_SEED + XXH_PRIME64_1 + XXH_PRIME64_2; + uint64_t v2 = QEMU_XXHASH_SEED + XXH_PRIME64_2; + uint64_t v3 = QEMU_XXHASH_SEED + 0; + uint64_t v4 = QEMU_XXHASH_SEED - XXH_PRIME64_1; + + v1 = XXH64_round(v1, a); + v2 = XXH64_round(v2, b); + v3 = XXH64_round(v3, c); + v4 = XXH64_round(v4, d); + + return XXH64_avalanche(XXH64_mergerounds(v1, v2, v3, v4)); +} + +#ifdef __cplusplus +} +#endif + +#endif /* QEMU_XXHASH_H */ diff --git a/libutils/scripts/upgrade/mapping.tsv b/libutils/scripts/upgrade/mapping.tsv index 9fbb0d6eb..1b50bd6ef 100644 --- a/libutils/scripts/upgrade/mapping.tsv +++ b/libutils/scripts/upgrade/mapping.tsv @@ -1,11 +1,12 @@ # libutils path upstream QEMU path, as of the tag recorded in BASELINE. # -# Only the vendored QEMU utilities below include/utils/ and src/utils/ appear -# here. The rest of libutils (QAPI, QObject, the visitors, coroutines, +# Only the vendored QEMU utilities appear here: the files below include/utils/ +# and src/utils/, plus include/qqueue.h (upstream include/qemu/queue.h). +# The rest of libutils (QAPI, QObject, the visitors, coroutines, # fsigc++) is S2E-original or diverged far enough that it is not merged # mechanically, and the S2E-original utilities (utils/config-host.h, -# utils/mutex.h, utils/spinlock.h) have no upstream counterpart at all. The -# merge driver is scripts/upgrade/merge.sh at the S2E source root. +# utils/spinlock.h) have no upstream counterpart at all. The merge driver +# is scripts/upgrade/merge.sh at the S2E source root. # # upstream-dirs: util/ include/qemu/ host/include/ # @@ -33,14 +34,21 @@ include/utils/ctype.h include/qemu/ctype.h include/utils/debug-assert.h include/tcg/debug-assert.h include/utils/host-utils.h include/qemu/host-utils.h include/utils/int128.h include/qemu/int128.h +include/qqueue.h include/qemu/queue.h +include/utils/coroutine-tls.h include/qemu/coroutine-tls.h include/utils/interval-tree.h include/qemu/interval-tree.h include/utils/madvise.h include/qemu/madvise.h include/utils/memalign.h include/qemu/memalign.h include/utils/mprotect.h include/qemu/mprotect.h +include/utils/processor.h include/qemu/processor.h include/utils/qtree.h include/qemu/qtree.h +include/utils/seqlock.h include/qemu/seqlock.h +include/utils/thread-posix.h include/qemu/thread-posix.h include/utils/units.h include/qemu/units.h +include/utils/xxhash.h include/qemu/xxhash.h include/utils/registerfields.h include/hw/core/registerfields.h src/utils/bitmap.c util/bitmap.c +src/utils/event.c util/event.c src/utils/bufferiszero.c util/bufferiszero.c src/utils/cacheflush.c util/cacheflush.c src/utils/hexdump.c util/hexdump.c @@ -60,3 +68,23 @@ include/utils/osdep.h include/qemu/osdep.h src/utils/cutils.c util/cutils.c src/utils/osdep.c util/osdep.c src/utils/oslib-posix.c util/oslib-posix.c +# More pruned copies, from the qht/rcu/thread import. thread.h drops win32 +# and the QSP profiler indirection (its macros call the _impl functions +# directly); futex.h drops win32; lockable.h drops CoMutex; notify.{h,c} +# drop NotifierWithReturn (Error API); qht.{h,c} drop qht_statistics +# (qdist is not vendored); rcu.c drops the BQL around callbacks and keeps +# the atfork hooks unconditionally; sys_membarrier.h keeps only the +# non-CONFIG_MEMBARRIER branch; qemu-thread-common.h drops tracing and BQL +# status tracking; qemu-thread-posix.c drops the TSAN annotation and traces. +include/utils/futex.h include/qemu/futex.h +include/utils/lockable.h include/qemu/lockable.h +include/utils/notify.h include/qemu/notify.h +include/utils/qht.h include/qemu/qht.h +include/utils/rcu.h include/qemu/rcu.h +include/utils/sys_membarrier.h include/qemu/sys_membarrier.h +include/utils/thread.h include/qemu/thread.h +src/utils/notify.c util/notify.c +src/utils/qemu-thread-common.h util/qemu-thread-common.h +src/utils/qemu-thread-posix.c util/qemu-thread-posix.c +src/utils/qht.c util/qht.c +src/utils/rcu.c util/rcu.c diff --git a/libutils/src/CMakeLists.txt b/libutils/src/CMakeLists.txt index b8c160383..aaff511b3 100644 --- a/libutils/src/CMakeLists.txt +++ b/libutils/src/CMakeLists.txt @@ -18,7 +18,8 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror -Wno-initializer-overrides -fPIC") +# _GNU_SOURCE: glibc only declares pthread_setname_np and friends with it (see utils/config-host.h). +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror -Wno-initializer-overrides -fPIC -D_GNU_SOURCE") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -fPIC -std=c++20") add_library ( @@ -56,13 +57,18 @@ add_library ( utils/cacheflush.c utils/cpuinfo-i386.c utils/cutils.c + utils/event.c utils/hexdump.c utils/host-utils.c utils/interval-tree.c utils/memalign.c + utils/notify.c utils/osdep.c utils/oslib-posix.c + utils/qemu-thread-posix.c + utils/qht.c utils/qtree.c + utils/rcu.c ) ########## diff --git a/libutils/src/utils/event.c b/libutils/src/utils/event.c new file mode 100644 index 000000000..866c74799 --- /dev/null +++ b/libutils/src/utils/event.c @@ -0,0 +1,166 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +#include +#include + +/* + * Valid transitions: + * - FREE -> SET (qemu_event_set) + * - BUSY -> SET (qemu_event_set) + * - SET -> FREE (qemu_event_reset) + * - FREE -> BUSY (qemu_event_wait) + * + * With futex, the waking and blocking operations follow + * BUSY -> SET and FREE -> BUSY, respectively. + * + * Without futex, BUSY -> SET and FREE -> BUSY never happen. Instead, the waking + * operation follows FREE -> SET and the blocking operation will happen in + * qemu_event_wait() if the event is not SET. + * + * SET->BUSY does not happen (it can be observed from the outside but + * it really is SET->FREE->BUSY). + * + * busy->free provably cannot happen; to enforce it, the set->free transition + * is done with an OR, which becomes a no-op if the event has concurrently + * transitioned to free or busy. + */ + +#define EV_SET 0 +#define EV_FREE 1 +#define EV_BUSY -1 + +void qemu_event_init(QemuEvent *ev, bool init) { +#ifndef HAVE_FUTEX + pthread_mutex_init(&ev->lock, NULL); + pthread_cond_init(&ev->cond, NULL); +#endif + + ev->value = (init ? EV_SET : EV_FREE); + ev->initialized = true; +} + +void qemu_event_destroy(QemuEvent *ev) { + assert(ev->initialized); + ev->initialized = false; +#ifndef HAVE_FUTEX + pthread_mutex_destroy(&ev->lock); + pthread_cond_destroy(&ev->cond); +#endif +} + +void qemu_event_set(QemuEvent *ev) { + assert(ev->initialized); + +#ifdef HAVE_FUTEX + /* + * Pairs with both qemu_event_reset() and qemu_event_wait(). + * + * qemu_event_set has release semantics, but because it *loads* + * ev->value we need a full memory barrier here. + */ + smp_mb(); + if (qatomic_read(&ev->value) != EV_SET) { + int old = qatomic_xchg(&ev->value, EV_SET); + + /* Pairs with memory barrier in kernel futex_wait system call. */ + smp_mb__after_rmw(); + if (old == EV_BUSY) { + /* There were waiters, wake them up. */ + qemu_futex_wake_all(ev); + } + } +#else + pthread_mutex_lock(&ev->lock); + /* Pairs with qemu_event_reset()'s load acquire. */ + qatomic_store_release(&ev->value, EV_SET); + pthread_cond_broadcast(&ev->cond); + pthread_mutex_unlock(&ev->lock); +#endif +} + +void qemu_event_reset(QemuEvent *ev) { + assert(ev->initialized); + +#ifdef HAVE_FUTEX + /* + * If there was a concurrent reset (or even reset+wait), + * do nothing. Otherwise change EV_SET->EV_FREE. + */ + qatomic_or(&ev->value, EV_FREE); + + /* + * Order reset before checking the condition in the caller. + * Pairs with the first memory barrier in qemu_event_set(). + */ + smp_mb__after_rmw(); +#else + /* + * If futexes are not available, there are no EV_FREE->EV_BUSY + * transitions because wakeups are done entirely through the + * condition variable. Since qatomic_set() only writes EV_FREE, + * the load seems useless but in reality, the acquire synchronizes + * with qemu_event_set()'s store release: if qemu_event_reset() + * sees EV_SET here, then the caller will certainly see a + * successful condition and skip qemu_event_wait(): + * + * done = 1; if (done == 0) + * qemu_event_set() { qemu_event_reset() { + * lock(); + * ev->value = EV_SET -----> load ev->value + * ev->value = old value | EV_FREE + * cond_broadcast() + * unlock(); } + * } if (done == 0) + * // qemu_event_wait() not called + */ + qatomic_set(&ev->value, qatomic_load_acquire(&ev->value) | EV_FREE); +#endif +} + +void qemu_event_wait(QemuEvent *ev) { + assert(ev->initialized); + +#ifdef HAVE_FUTEX + while (true) { + /* + * qemu_event_wait must synchronize with qemu_event_set even if it does + * not go down the slow path, so this load-acquire is needed that + * synchronizes with the first memory barrier in qemu_event_set(). + */ + unsigned value = qatomic_load_acquire(&ev->value); + if (value == EV_SET) { + break; + } + + if (value == EV_FREE) { + /* + * Leave the event reset and tell qemu_event_set that there are + * waiters. No need to retry, because there cannot be a concurrent + * busy->free transition. After the CAS, the event will be either + * set or busy. + * + * This cmpxchg doesn't have particular ordering requirements if it + * succeeds (moving the store earlier can only cause + * qemu_event_set() to issue _more_ wakeups), the failing case needs + * acquire semantics like the load above. + */ + if (qatomic_cmpxchg(&ev->value, EV_FREE, EV_BUSY) == EV_SET) { + break; + } + } + + /* + * This is the final check for a concurrent set, so it does need + * a smp_mb() pairing with the second barrier of qemu_event_set(). + * The barrier is inside the FUTEX_WAIT system call. + */ + qemu_futex_wait(ev, EV_BUSY); + } +#else + pthread_mutex_lock(&ev->lock); + while (qatomic_read(&ev->value) != EV_SET) { + pthread_cond_wait(&ev->cond, &ev->lock); + } + pthread_mutex_unlock(&ev->lock); +#endif +} diff --git a/libutils/src/utils/notify.c b/libutils/src/utils/notify.c new file mode 100644 index 000000000..066fdb2c9 --- /dev/null +++ b/libutils/src/utils/notify.c @@ -0,0 +1,43 @@ +/* + * Notifier lists + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Anthony Liguori + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + * Contributions after 2012-01-13 are licensed under the terms of the + * GNU GPL, version 2 or (at your option) any later version. + */ + +#include +#include + +void notifier_list_init(NotifierList *list) { + QLIST_INIT(&list->notifiers); +} + +void notifier_list_add(NotifierList *list, Notifier *notifier) { + QLIST_INSERT_HEAD(&list->notifiers, notifier, node); +} + +void notifier_remove(Notifier *notifier) { + QLIST_SAFE_REMOVE(notifier, node); +} + +void notifier_list_notify(NotifierList *list, void *data) { + Notifier *notifier, *next; + + QLIST_FOREACH_SAFE(notifier, &list->notifiers, node, next) { + notifier->notify(notifier, data); + } +} + +bool notifier_list_empty(NotifierList *list) { + return QLIST_EMPTY(&list->notifiers); +} + +/* Upstream NotifierWithReturn is removed together with its declaration; see notify.h. */ diff --git a/libutils/src/utils/qemu-thread-common.h b/libutils/src/utils/qemu-thread-common.h new file mode 100644 index 000000000..ad9491108 --- /dev/null +++ b/libutils/src/utils/qemu-thread-common.h @@ -0,0 +1,45 @@ +/* + * Common qemu-thread implementation header file. + * + * Copyright Red Hat, Inc. 2018 + * + * Authors: + * Peter Xu , + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#ifndef QEMU_THREAD_COMMON_H +#define QEMU_THREAD_COMMON_H + +#include + +/* Upstream also traces lock operations and tracks the BQL status here. */ + +static inline void qemu_mutex_post_init(QemuMutex *mutex) { +#ifdef CONFIG_DEBUG_MUTEX + mutex->file = NULL; + mutex->line = 0; +#endif + mutex->initialized = true; +} + +static inline void qemu_mutex_pre_lock(QemuMutex *mutex, const char *file, int line) { +} + +static inline void qemu_mutex_post_lock(QemuMutex *mutex, const char *file, int line) { +#ifdef CONFIG_DEBUG_MUTEX + mutex->file = file; + mutex->line = line; +#endif +} + +static inline void qemu_mutex_pre_unlock(QemuMutex *mutex, const char *file, int line) { +#ifdef CONFIG_DEBUG_MUTEX + mutex->file = NULL; + mutex->line = 0; +#endif +} + +#endif diff --git a/libutils/src/utils/qemu-thread-posix.c b/libutils/src/utils/qemu-thread-posix.c new file mode 100644 index 000000000..c4113a181 --- /dev/null +++ b/libutils/src/utils/qemu-thread-posix.c @@ -0,0 +1,530 @@ +/* + * Wrappers around mutex/cond/thread functions + * + * Copyright Red Hat, Inc. 2009 + * + * Author: + * Marcelo Tosatti + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + */ +#include +#include +#include +#include +#include +#include "qemu-thread-common.h" + +#if defined(CONFIG_PTHREAD_SET_NAME_NP) || defined(CONFIG_PTHREAD_GET_NAME_NP) +#include +#endif + +/* + * This is not defined on Linux, but the man page indicates + * the buffer must be at least 16 bytes, including the NUL + * terminator + */ +#ifndef PTHREAD_MAX_NAMELEN_NP +#define PTHREAD_MAX_NAMELEN_NP 16 +#endif + +static __thread char namebuf[PTHREAD_MAX_NAMELEN_NP]; + +static void __attribute__((__constructor__(QEMU_CONSTRUCTOR_EARLY))) qemu_thread_init(void) { + /* + * Initialize the main thread name. We must not use + * qemu_thread_setname(), since on some platforms (at least Linux) + * this can change the process name that is reported by tools like + * 'ps'. + * + * This workaround suffices to ensure QEMU log/error messages + * get the main thread name, but at the cost of external tools + * like GDB not seeing it. + * + * NB using a constructor instead of static initializing namebuf, + * to ensure it only initializes the thread-local in the main + * thread + */ + g_strlcpy(namebuf, "main", sizeof(namebuf)); +} + +static void error_exit(int err, const char *msg) { + fprintf(stderr, "qemu: %s: %s\n", msg, strerror(err)); + abort(); +} + +static inline clockid_t qemu_timedwait_clockid(void) { +#ifdef CONFIG_PTHREAD_CONDATTR_SETCLOCK + return CLOCK_MONOTONIC; +#else + return CLOCK_REALTIME; +#endif +} + +static void compute_abs_deadline(struct timespec *ts, int ms) { + clock_gettime(qemu_timedwait_clockid(), ts); + ts->tv_nsec += (ms % 1000) * 1000000; + ts->tv_sec += ms / 1000; + if (ts->tv_nsec >= 1000000000) { + ts->tv_sec++; + ts->tv_nsec -= 1000000000; + } +} + +void qemu_mutex_init(QemuMutex *mutex) { + int err; + + err = pthread_mutex_init(&mutex->lock, NULL); + if (err) + error_exit(err, __func__); + qemu_mutex_post_init(mutex); +} + +void qemu_mutex_destroy(QemuMutex *mutex) { + int err; + + assert(mutex->initialized); + mutex->initialized = false; + err = pthread_mutex_destroy(&mutex->lock); + if (err) + error_exit(err, __func__); +} + +void qemu_mutex_lock_impl(QemuMutex *mutex, const char *file, const int line) { + int err; + + assert(mutex->initialized); + qemu_mutex_pre_lock(mutex, file, line); + err = pthread_mutex_lock(&mutex->lock); + if (err) + error_exit(err, __func__); + qemu_mutex_post_lock(mutex, file, line); +} + +int qemu_mutex_trylock_impl(QemuMutex *mutex, const char *file, const int line) { + int err; + + assert(mutex->initialized); + err = pthread_mutex_trylock(&mutex->lock); + if (err == 0) { + qemu_mutex_post_lock(mutex, file, line); + return 0; + } + if (err != EBUSY) { + error_exit(err, __func__); + } + return -EBUSY; +} + +void qemu_mutex_unlock_impl(QemuMutex *mutex, const char *file, const int line) { + int err; + + assert(mutex->initialized); + qemu_mutex_pre_unlock(mutex, file, line); + err = pthread_mutex_unlock(&mutex->lock); + if (err) + error_exit(err, __func__); +} + +void qemu_rec_mutex_init(QemuRecMutex *mutex) { + int err; + pthread_mutexattr_t attr; + + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + err = pthread_mutex_init(&mutex->m.lock, &attr); + pthread_mutexattr_destroy(&attr); + if (err) { + error_exit(err, __func__); + } + mutex->m.initialized = true; +} + +void qemu_rec_mutex_destroy(QemuRecMutex *mutex) { + qemu_mutex_destroy(&mutex->m); +} + +void qemu_rec_mutex_lock_impl(QemuRecMutex *mutex, const char *file, int line) { + qemu_mutex_lock_impl(&mutex->m, file, line); +} + +int qemu_rec_mutex_trylock_impl(QemuRecMutex *mutex, const char *file, int line) { + return qemu_mutex_trylock_impl(&mutex->m, file, line); +} + +void qemu_rec_mutex_unlock_impl(QemuRecMutex *mutex, const char *file, int line) { + qemu_mutex_unlock_impl(&mutex->m, file, line); +} + +void qemu_cond_init(QemuCond *cond) { + pthread_condattr_t attr; + int err; + + err = pthread_condattr_init(&attr); + if (err) { + error_exit(err, __func__); + } +#ifdef CONFIG_PTHREAD_CONDATTR_SETCLOCK + err = pthread_condattr_setclock(&attr, qemu_timedwait_clockid()); + if (err) { + error_exit(err, __func__); + } +#endif + err = pthread_cond_init(&cond->cond, &attr); + if (err) { + error_exit(err, __func__); + } + err = pthread_condattr_destroy(&attr); + if (err) { + error_exit(err, __func__); + } + cond->initialized = true; +} + +void qemu_cond_destroy(QemuCond *cond) { + int err; + + assert(cond->initialized); + cond->initialized = false; + err = pthread_cond_destroy(&cond->cond); + if (err) + error_exit(err, __func__); +} + +void qemu_cond_signal(QemuCond *cond) { + int err; + + assert(cond->initialized); + err = pthread_cond_signal(&cond->cond); + if (err) + error_exit(err, __func__); +} + +void qemu_cond_broadcast(QemuCond *cond) { + int err; + + assert(cond->initialized); + err = pthread_cond_broadcast(&cond->cond); + if (err) + error_exit(err, __func__); +} + +void qemu_cond_wait_impl(QemuCond *cond, QemuMutex *mutex, const char *file, const int line) { + int err; + + assert(cond->initialized); + qemu_mutex_pre_unlock(mutex, file, line); + err = pthread_cond_wait(&cond->cond, &mutex->lock); + qemu_mutex_post_lock(mutex, file, line); + if (err) + error_exit(err, __func__); +} + +static bool TSA_NO_TSA qemu_cond_timedwait_ts(QemuCond *cond, QemuMutex *mutex, struct timespec *ts, const char *file, + const int line) { + int err; + + assert(cond->initialized); + qemu_mutex_pre_unlock(mutex, file, line); + err = pthread_cond_timedwait(&cond->cond, &mutex->lock, ts); + qemu_mutex_post_lock(mutex, file, line); + if (err && err != ETIMEDOUT) { + error_exit(err, __func__); + } + return err != ETIMEDOUT; +} + +bool qemu_cond_timedwait_impl(QemuCond *cond, QemuMutex *mutex, int ms, const char *file, const int line) { + struct timespec ts; + + compute_abs_deadline(&ts, ms); + return qemu_cond_timedwait_ts(cond, mutex, &ts, file, line); +} + +void qemu_sem_init(QemuSemaphore *sem, int init) { + qemu_mutex_init(&sem->mutex); + qemu_cond_init(&sem->cond); + + if (init < 0) { + error_exit(EINVAL, __func__); + } + sem->count = init; +} + +void qemu_sem_destroy(QemuSemaphore *sem) { + qemu_cond_destroy(&sem->cond); + qemu_mutex_destroy(&sem->mutex); +} + +void qemu_sem_post(QemuSemaphore *sem) { + qemu_mutex_lock(&sem->mutex); + if (sem->count == UINT_MAX) { + error_exit(EINVAL, __func__); + } else { + sem->count++; + qemu_cond_signal(&sem->cond); + } + qemu_mutex_unlock(&sem->mutex); +} + +int qemu_sem_timedwait(QemuSemaphore *sem, int ms) { + bool rc = true; + struct timespec ts; + + compute_abs_deadline(&ts, ms); + qemu_mutex_lock(&sem->mutex); + while (sem->count == 0) { + if (ms == 0) { + rc = false; + } else { + rc = qemu_cond_timedwait_ts(&sem->cond, &sem->mutex, &ts, __FILE__, __LINE__); + } + if (!rc) { /* timeout */ + break; + } + } + if (rc) { + --sem->count; + } + qemu_mutex_unlock(&sem->mutex); + return (rc ? 0 : -1); +} + +void qemu_sem_wait(QemuSemaphore *sem) { + qemu_mutex_lock(&sem->mutex); + while (sem->count == 0) { + qemu_cond_wait(&sem->cond, &sem->mutex); + } + --sem->count; + qemu_mutex_unlock(&sem->mutex); +} + +static __thread NotifierList thread_exit; + +/* + * Note that in this implementation you can register a thread-exit + * notifier for the main thread, but it will never be called. + * This is OK because main thread exit can only happen when the + * entire process is exiting, and the API allows notifiers to not + * be called on process exit. + */ +void qemu_thread_atexit_add(Notifier *notifier) { + notifier_list_add(&thread_exit, notifier); +} + +void qemu_thread_atexit_remove(Notifier *notifier) { + notifier_remove(notifier); +} + +static void qemu_thread_atexit_notify(void *arg) { + /* + * Called when non-main thread exits (via qemu_thread_exit() + * or by returning from its start routine.) + */ + notifier_list_notify(&thread_exit, NULL); +} + +void qemu_thread_set_name(const char *name) { + /* + * Attempt to set the thread name; note that this is for debug, so + * we're not going to fail if we can't set it. + */ +#if defined(CONFIG_PTHREAD_SETNAME_NP_W_TID) + pthread_setname_np(pthread_self(), name); +#elif defined(CONFIG_PTHREAD_SETNAME_NP_WO_TID) + pthread_setname_np(name); +#elif defined(CONFIG_PTHREAD_SET_NAME_NP) + pthread_set_name_np(pthread_self(), name); +#endif +} + +typedef struct { + void *(*start_routine)(void *); + void *arg; + char *name; +} QemuThreadArgs; + +static void *qemu_thread_start(void *args) { + QemuThreadArgs *qemu_thread_args = args; + void *(*start_routine)(void *) = qemu_thread_args->start_routine; + void *arg = qemu_thread_args->arg; + void *r; + + if (qemu_thread_args->name) { + qemu_thread_set_name(qemu_thread_args->name); + } + g_free(qemu_thread_args->name); + g_free(qemu_thread_args); + + /* + * GCC 11 with glibc 2.17 on PowerPC reports + * + * qemu-thread-posix.c:540:5: error: ‘__sigsetjmp’ accessing 656 bytes + * in a region of size 528 [-Werror=stringop-overflow=] + * 540 | pthread_cleanup_push(qemu_thread_atexit_notify, NULL); + * | ^~~~~~~~~~~~~~~~~~~~ + * + * which is clearly nonsense. + */ +#pragma GCC diagnostic push +#ifndef __clang__ +#pragma GCC diagnostic ignored "-Wstringop-overflow" +#endif + + pthread_cleanup_push(qemu_thread_atexit_notify, NULL); + r = start_routine(arg); + pthread_cleanup_pop(1); + +#pragma GCC diagnostic pop + + return r; +} + +void qemu_thread_create(QemuThread *thread, const char *name, void *(*start_routine)(void *), void *arg, int mode) { + sigset_t set, oldset; + int err; + pthread_attr_t attr; + QemuThreadArgs *qemu_thread_args; + + err = pthread_attr_init(&attr); + if (err) { + error_exit(err, __func__); + } + + if (mode == QEMU_THREAD_DETACHED) { + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + } + + /* Leave signal handling to the iothread. */ + sigfillset(&set); + /* Blocking the signals can result in undefined behaviour. */ + sigdelset(&set, SIGSEGV); + sigdelset(&set, SIGFPE); + sigdelset(&set, SIGILL); + /* TODO avoid SIGBUS loss on macOS */ + pthread_sigmask(SIG_SETMASK, &set, &oldset); + + qemu_thread_args = g_new0(QemuThreadArgs, 1); + qemu_thread_args->name = g_strdup(name); + qemu_thread_args->start_routine = start_routine; + qemu_thread_args->arg = arg; + + err = pthread_create(&thread->thread, &attr, qemu_thread_start, qemu_thread_args); + + if (err) + error_exit(err, __func__); + + pthread_sigmask(SIG_SETMASK, &oldset, NULL); + + pthread_attr_destroy(&attr); +} + +int qemu_thread_set_affinity(QemuThread *thread, unsigned long *host_cpus, unsigned long nbits) { +#if defined(CONFIG_PTHREAD_AFFINITY_NP) + const size_t setsize = CPU_ALLOC_SIZE(nbits); + unsigned long value; + cpu_set_t *cpuset; + int err; + + cpuset = CPU_ALLOC(nbits); + g_assert(cpuset); + + CPU_ZERO_S(setsize, cpuset); + value = find_first_bit(host_cpus, nbits); + while (value < nbits) { + CPU_SET_S(value, setsize, cpuset); + value = find_next_bit(host_cpus, nbits, value + 1); + } + + err = pthread_setaffinity_np(thread->thread, setsize, cpuset); + CPU_FREE(cpuset); + return err; +#else + return -ENOSYS; +#endif +} + +int qemu_thread_get_affinity(QemuThread *thread, unsigned long **host_cpus, unsigned long *nbits) { +#if defined(CONFIG_PTHREAD_AFFINITY_NP) + unsigned long tmpbits; + cpu_set_t *cpuset; + size_t setsize; + int i, err; + + tmpbits = CPU_SETSIZE; + while (true) { + setsize = CPU_ALLOC_SIZE(tmpbits); + cpuset = CPU_ALLOC(tmpbits); + g_assert(cpuset); + + err = pthread_getaffinity_np(thread->thread, setsize, cpuset); + if (err) { + CPU_FREE(cpuset); + if (err != -EINVAL) { + return err; + } + tmpbits *= 2; + } else { + break; + } + } + + /* Convert the result into a proper bitmap. */ + *nbits = tmpbits; + *host_cpus = bitmap_new(tmpbits); + for (i = 0; i < tmpbits; i++) { + if (CPU_ISSET(i, cpuset)) { + set_bit(i, *host_cpus); + } + } + CPU_FREE(cpuset); + return 0; +#else + return -ENOSYS; +#endif +} + +void qemu_thread_get_self(QemuThread *thread) { + thread->thread = pthread_self(); +} + +bool qemu_thread_is_self(QemuThread *thread) { + return pthread_equal(pthread_self(), thread->thread); +} + +void qemu_thread_exit(void *retval) { + pthread_exit(retval); +} + +void *qemu_thread_join(QemuThread *thread) { + int err; + void *ret; + + err = pthread_join(thread->thread, &ret); + if (err) { + error_exit(err, __func__); + } + return ret; +} + +const char *qemu_thread_get_name(void) { + int rv; + if (namebuf[0] != '\0') { + return namebuf; + } + +#if defined(CONFIG_PTHREAD_GETNAME_NP) + rv = pthread_getname_np(pthread_self(), namebuf, sizeof(namebuf)); +#elif defined(CONFIG_PTHREAD_GET_NAME_NP) + pthread_get_name_np(pthread_self(), namebuf, sizeof(namebuf)); + rv = 0; +#else + rv = -1; +#endif + if (rv != 0) { + g_strlcpy(namebuf, "unnamed", G_N_ELEMENTS(namebuf)); + } + return namebuf; +} diff --git a/libutils/src/utils/qht.c b/libutils/src/utils/qht.c new file mode 100644 index 000000000..25a4fc080 --- /dev/null +++ b/libutils/src/utils/qht.c @@ -0,0 +1,900 @@ +/* + * qht.c - QEMU Hash Table, designed to scale for read-mostly workloads. + * + * Copyright (C) 2016, Emilio G. Cota + * + * License: GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + * Assumptions: + * - NULL cannot be inserted/removed as a pointer value. + * - Trying to insert an already-existing hash-pointer pair is OK. However, + * it is not OK to insert into the same hash table different hash-pointer + * pairs that have the same pointer value, but not the hashes. + * - Lookups are performed under an RCU read-critical section; removals + * must wait for a grace period to elapse before freeing removed objects. + * + * Features: + * - Reads (i.e. lookups and iterators) can be concurrent with other reads. + * Lookups that are concurrent with writes to the same bucket will retry + * via a seqlock; iterators acquire all bucket locks and therefore can be + * concurrent with lookups and are serialized wrt writers. + * - Writes (i.e. insertions/removals) can be concurrent with writes to + * different buckets; writes to the same bucket are serialized through a lock. + * - Optional auto-resizing: the hash table resizes up if the load surpasses + * a certain threshold. Resizing is done concurrently with readers; writes + * are serialized with the resize operation. + * + * The key structure is the bucket, which is cacheline-sized. Buckets + * contain a few hash values and pointers; the u32 hash values are stored in + * full so that resizing is fast. Having this structure instead of directly + * chaining items has two advantages: + * - Failed lookups fail fast, and touch a minimum number of cache lines. + * - Resizing the hash table with concurrent lookups is easy. + * + * There are two types of buckets: + * 1. "head" buckets are the ones allocated in the array of buckets in qht_map. + * 2. all "non-head" buckets (i.e. all others) are members of a chain that + * starts from a head bucket. + * Note that the seqlock and spinlock of a head bucket applies to all buckets + * chained to it; these two fields are unused in non-head buckets. + * + * On removals, we move the last valid item in the chain to the position of the + * just-removed entry. This makes lookups slightly faster, since the moment an + * invalid entry is found, the (failed) lookup is over. + * + * Resizing is done by taking all bucket spinlocks (so that no other writers can + * race with us) and then copying all entries into a new hash map. Then, the + * ht->map pointer is set, and the old map is freed once no RCU readers can see + * it anymore. + * + * Writers check for concurrent resizes by comparing ht->map before and after + * acquiring their bucket lock. If they don't match, a resize has occurred + * while the bucket spinlock was being acquired. + * + * Related Work: + * - Idea of cacheline-sized buckets with full hashes taken from: + * David, Guerraoui & Trigonakis, "Asynchronized Concurrency: + * The Secret to Scaling Concurrent Search Data Structures", ASPLOS'15. + * - Why not RCU-based hash tables? They would allow us to get rid of the + * seqlock, but resizing would take forever since RCU read critical + * sections in QEMU take quite a long time. + * More info on relativistic hash tables: + * + Triplett, McKenney & Walpole, "Resizable, Scalable, Concurrent Hash + * Tables via Relativistic Programming", USENIX ATC'11. + * + Corbet, "Relativistic hash tables, part 1: Algorithms", @ lwn.net, 2014. + * https://lwn.net/Articles/612021/ + */ +#include +#include +#include +#include +#include +#include + +// #define QHT_DEBUG + +/* + * We want to avoid false sharing of cache lines. Most systems have 64-byte + * cache lines so we go with it for simplicity. + * + * Note that systems with smaller cache lines will be fine (the struct is + * almost 64-bytes); systems with larger cache lines might suffer from + * some false sharing. + */ +#define QHT_BUCKET_ALIGN 64 + +/* define these to keep sizeof(qht_bucket) within QHT_BUCKET_ALIGN */ +#if HOST_LONG_BITS == 32 +#define QHT_BUCKET_ENTRIES 6 +#else /* 64-bit */ +#define QHT_BUCKET_ENTRIES 4 +#endif + +enum qht_iter_type { + QHT_ITER_VOID, /* do nothing; use retvoid */ + QHT_ITER_RM, /* remove element if retbool returns true */ +}; + +struct qht_iter { + union { + qht_iter_func_t retvoid; + qht_iter_bool_func_t retbool; + } f; + enum qht_iter_type type; +}; + +/* + * Do _not_ use qemu_mutex_[try]lock directly! Use these macros, otherwise + * the profiler (QSP) will deadlock. + */ +static inline void qht_lock(struct qht *ht) { + if (ht->mode & QHT_MODE_RAW_MUTEXES) { + qemu_mutex_lock__raw(&ht->lock); + } else { + qemu_mutex_lock(&ht->lock); + } +} + +static inline int qht_trylock(struct qht *ht) { + if (ht->mode & QHT_MODE_RAW_MUTEXES) { + return qemu_mutex_trylock__raw(&(ht)->lock); + } + return qemu_mutex_trylock(&(ht)->lock); +} + +/* this inline is not really necessary, but it helps keep code consistent */ +static inline void qht_unlock(struct qht *ht) { + qemu_mutex_unlock(&ht->lock); +} + +/* + * Note: reading partially-updated pointers in @pointers could lead to + * segfaults. We thus access them with qatomic_read/set; this guarantees + * that the compiler makes all those accesses atomic. We also need the + * volatile-like behavior in qatomic_read, since otherwise the compiler + * might refetch the pointer. + * qatomic_read's are of course not necessary when the bucket lock is held. + * + * If both ht->lock and b->lock are grabbed, ht->lock should always + * be grabbed first. + */ +struct qht_bucket { + QemuSpin lock; + QemuSeqLock sequence; + uint32_t hashes[QHT_BUCKET_ENTRIES]; + void *pointers[QHT_BUCKET_ENTRIES]; + struct qht_bucket *next; +} QEMU_ALIGNED(QHT_BUCKET_ALIGN); + +QEMU_BUILD_BUG_ON(sizeof(struct qht_bucket) > QHT_BUCKET_ALIGN); + +/* + * Under TSAN, we use striped locks instead of one lock per bucket chain. + * This avoids crashing under TSAN, since TSAN aborts the program if more than + * 64 locks are held (this is a hardcoded limit in TSAN). + * When resizing a QHT we grab all the buckets' locks, which can easily + * go over TSAN's limit. By using striped locks, we avoid this problem. + * + * Note: this number must be a power of two for easy index computation. + */ +#define QHT_TSAN_BUCKET_LOCKS_BITS 4 +#define QHT_TSAN_BUCKET_LOCKS (1 << QHT_TSAN_BUCKET_LOCKS_BITS) + +struct qht_tsan_lock { + QemuSpin lock; +} QEMU_ALIGNED(QHT_BUCKET_ALIGN); + +/** + * struct qht_map - structure to track an array of buckets + * @rcu: used by RCU. Keep it as the top field in the struct to help valgrind + * find the whole struct. + * @buckets: array of head buckets. It is constant once the map is created. + * @n_buckets: number of head buckets. It is constant once the map is created. + * @n_added_buckets: number of added (i.e. "non-head") buckets + * @n_added_buckets_threshold: threshold to trigger an upward resize once the + * number of added buckets surpasses it. + * @tsan_bucket_locks: Array of striped locks to be used only under TSAN. + * + * Buckets are tracked in what we call a "map", i.e. this structure. + */ +struct qht_map { + struct rcu_head rcu; + struct qht_bucket *buckets; + size_t n_buckets; + size_t n_added_buckets; + size_t n_added_buckets_threshold; +#ifdef CONFIG_TSAN + struct qht_tsan_lock tsan_bucket_locks[QHT_TSAN_BUCKET_LOCKS]; +#endif +}; + +/* trigger a resize when n_added_buckets > n_buckets / div */ +#define QHT_NR_ADDED_BUCKETS_THRESHOLD_DIV 8 + +static void qht_do_resize_reset(struct qht *ht, struct qht_map *new, bool reset); +static void qht_grow_maybe(struct qht *ht); + +#ifdef QHT_DEBUG + +#define qht_debug_assert(X) \ + do { \ + assert(X); \ + } while (0) + +static void qht_bucket_debug__locked(struct qht_bucket *b) { + bool seen_empty = false; + bool corrupt = false; + int i; + + do { + for (i = 0; i < QHT_BUCKET_ENTRIES; i++) { + if (b->pointers[i] == NULL) { + seen_empty = true; + continue; + } + if (seen_empty) { + fprintf(stderr, "%s: b: %p, pos: %i, hash: 0x%x, p: %p\n", __func__, b, i, b->hashes[i], + b->pointers[i]); + corrupt = true; + } + } + b = b->next; + } while (b); + qht_debug_assert(!corrupt); +} + +static void qht_map_debug__all_locked(struct qht_map *map) { + int i; + + for (i = 0; i < map->n_buckets; i++) { + qht_bucket_debug__locked(&map->buckets[i]); + } +} +#else + +#define qht_debug_assert(X) \ + do { \ + (void) (X); \ + } while (0) + +static inline void qht_bucket_debug__locked(struct qht_bucket *b) { +} + +static inline void qht_map_debug__all_locked(struct qht_map *map) { +} +#endif /* QHT_DEBUG */ + +static inline size_t qht_elems_to_buckets(size_t n_elems) { + return pow2ceil(n_elems / QHT_BUCKET_ENTRIES); +} + +/* + * When using striped locks (i.e. under TSAN), we have to be careful not + * to operate on the same lock twice (e.g. when iterating through all buckets). + * We achieve this by operating only on each stripe's first matching lock. + */ +static inline void qht_do_if_first_in_stripe(struct qht_map *map, struct qht_bucket *b, void (*func)(QemuSpin *spin)) { +#ifdef CONFIG_TSAN + unsigned long bucket_idx = b - map->buckets; + bool is_first_in_stripe = (bucket_idx >> QHT_TSAN_BUCKET_LOCKS_BITS) == 0; + if (is_first_in_stripe) { + unsigned long lock_idx = bucket_idx & (QHT_TSAN_BUCKET_LOCKS - 1); + func(&map->tsan_bucket_locks[lock_idx].lock); + } +#else + func(&b->lock); +#endif +} + +static inline void qht_bucket_lock_do(struct qht_map *map, struct qht_bucket *b, void (*func)(QemuSpin *lock)) { +#ifdef CONFIG_TSAN + unsigned long bucket_idx = b - map->buckets; + unsigned long lock_idx = bucket_idx & (QHT_TSAN_BUCKET_LOCKS - 1); + func(&map->tsan_bucket_locks[lock_idx].lock); +#else + func(&b->lock); +#endif +} + +static inline void qht_bucket_lock(struct qht_map *map, struct qht_bucket *b) { + qht_bucket_lock_do(map, b, qemu_spin_lock); +} + +static inline void qht_bucket_unlock(struct qht_map *map, struct qht_bucket *b) { + qht_bucket_lock_do(map, b, qemu_spin_unlock); +} + +static inline void qht_head_init(struct qht_map *map, struct qht_bucket *b) { + memset(b, 0, sizeof(*b)); + qht_do_if_first_in_stripe(map, b, qemu_spin_init); + seqlock_init(&b->sequence); +} + +static inline struct qht_bucket *qht_map_to_bucket(const struct qht_map *map, uint32_t hash) { + return &map->buckets[hash & (map->n_buckets - 1)]; +} + +/* acquire all bucket locks from a map */ +static void qht_map_lock_buckets(struct qht_map *map) { + size_t i; + + for (i = 0; i < map->n_buckets; i++) { + struct qht_bucket *b = &map->buckets[i]; + + qht_do_if_first_in_stripe(map, b, qemu_spin_lock); + } +} + +static void qht_map_unlock_buckets(struct qht_map *map) { + size_t i; + + for (i = 0; i < map->n_buckets; i++) { + struct qht_bucket *b = &map->buckets[i]; + + qht_do_if_first_in_stripe(map, b, qemu_spin_unlock); + } +} + +/* + * Call with at least a bucket lock held. + * @map should be the value read before acquiring the lock (or locks). + */ +static inline bool qht_map_is_stale__locked(const struct qht *ht, const struct qht_map *map) { + return map != ht->map; +} + +/* + * Grab all bucket locks, and set @pmap after making sure the map isn't stale. + * + * Pairs with qht_map_unlock_buckets(), hence the pass-by-reference. + * + * Note: callers cannot have ht->lock held. + */ +static inline void qht_map_lock_buckets__no_stale(struct qht *ht, struct qht_map **pmap) { + struct qht_map *map; + + map = qatomic_rcu_read(&ht->map); + qht_map_lock_buckets(map); + if (likely(!qht_map_is_stale__locked(ht, map))) { + *pmap = map; + return; + } + qht_map_unlock_buckets(map); + + /* we raced with a resize; acquire ht->lock to see the updated ht->map */ + qht_lock(ht); + map = ht->map; + qht_map_lock_buckets(map); + qht_unlock(ht); + *pmap = map; +} + +/* + * Get a head bucket and lock it, making sure its parent map is not stale. + * @pmap is filled with a pointer to the bucket's parent map. + * + * Unlock with qht_bucket_unlock. + * + * Note: callers cannot have ht->lock held. + */ +static inline struct qht_bucket *qht_bucket_lock__no_stale(struct qht *ht, uint32_t hash, struct qht_map **pmap) { + struct qht_bucket *b; + struct qht_map *map; + + map = qatomic_rcu_read(&ht->map); + b = qht_map_to_bucket(map, hash); + + qht_bucket_lock(map, b); + if (likely(!qht_map_is_stale__locked(ht, map))) { + *pmap = map; + return b; + } + qht_bucket_unlock(map, b); + + /* we raced with a resize; acquire ht->lock to see the updated ht->map */ + qht_lock(ht); + map = ht->map; + b = qht_map_to_bucket(map, hash); + qht_bucket_lock(map, b); + qht_unlock(ht); + *pmap = map; + return b; +} + +static inline bool qht_map_needs_resize(const struct qht_map *map) { + return qatomic_read(&map->n_added_buckets) > map->n_added_buckets_threshold; +} + +static inline void qht_chain_destroy(struct qht_map *map, struct qht_bucket *head) { + struct qht_bucket *curr = head->next; + struct qht_bucket *prev; + + qht_do_if_first_in_stripe(map, head, qemu_spin_destroy); + while (curr) { + prev = curr; + curr = curr->next; + qemu_vfree(prev); + } +} + +/* pass only an orphan map */ +static void qht_map_destroy(struct qht_map *map) { + size_t i; + + for (i = 0; i < map->n_buckets; i++) { + qht_chain_destroy(map, &map->buckets[i]); + } + qemu_vfree(map->buckets); + g_free(map); +} + +static struct qht_map *qht_map_create(size_t n_buckets) { + struct qht_map *map; + size_t i; + + map = g_malloc(sizeof(*map)); + map->n_buckets = n_buckets; + + map->n_added_buckets = 0; + map->n_added_buckets_threshold = n_buckets / QHT_NR_ADDED_BUCKETS_THRESHOLD_DIV; + + /* let tiny hash tables to at least add one non-head bucket */ + if (unlikely(map->n_added_buckets_threshold == 0)) { + map->n_added_buckets_threshold = 1; + } + + map->buckets = qemu_memalign(QHT_BUCKET_ALIGN, sizeof(*map->buckets) * n_buckets); + for (i = 0; i < n_buckets; i++) { + qht_head_init(map, &map->buckets[i]); + } + return map; +} + +void qht_init(struct qht *ht, qht_cmp_func_t cmp, size_t n_elems, unsigned int mode) { + struct qht_map *map; + size_t n_buckets = qht_elems_to_buckets(n_elems); + + g_assert(cmp); + ht->cmp = cmp; + ht->mode = mode; + qemu_mutex_init(&ht->lock); + map = qht_map_create(n_buckets); + qatomic_rcu_set(&ht->map, map); +} + +/* call only when there are no readers/writers left */ +void qht_destroy(struct qht *ht) { + qht_map_destroy(ht->map); + memset(ht, 0, sizeof(*ht)); +} + +static void qht_bucket_reset__locked(struct qht_bucket *head) { + struct qht_bucket *b = head; + int i; + + seqlock_write_begin(&head->sequence); + do { + for (i = 0; i < QHT_BUCKET_ENTRIES; i++) { + if (b->pointers[i] == NULL) { + goto done; + } + qatomic_set(&b->hashes[i], 0); + qatomic_set(&b->pointers[i], NULL); + } + b = b->next; + } while (b); +done: + seqlock_write_end(&head->sequence); +} + +/* call with all bucket locks held */ +static void qht_map_reset__all_locked(struct qht_map *map) { + size_t i; + + for (i = 0; i < map->n_buckets; i++) { + qht_bucket_reset__locked(&map->buckets[i]); + } + qht_map_debug__all_locked(map); +} + +void qht_reset(struct qht *ht) { + struct qht_map *map; + + qht_map_lock_buckets__no_stale(ht, &map); + qht_map_reset__all_locked(map); + qht_map_unlock_buckets(map); +} + +static inline void qht_do_resize(struct qht *ht, struct qht_map *new) { + qht_do_resize_reset(ht, new, false); +} + +static inline void qht_do_resize_and_reset(struct qht *ht, struct qht_map *new) { + qht_do_resize_reset(ht, new, true); +} + +bool qht_reset_size(struct qht *ht, size_t n_elems) { + struct qht_map *new = NULL; + struct qht_map *map; + size_t n_buckets; + + n_buckets = qht_elems_to_buckets(n_elems); + + qht_lock(ht); + map = ht->map; + if (n_buckets != map->n_buckets) { + new = qht_map_create(n_buckets); + } + qht_do_resize_and_reset(ht, new); + qht_unlock(ht); + + return !!new; +} + +static inline void *qht_do_lookup(const struct qht_bucket *head, qht_lookup_func_t func, const void *userp, + uint32_t hash) { + const struct qht_bucket *b = head; + int i; + + do { + for (i = 0; i < QHT_BUCKET_ENTRIES; i++) { + if (qatomic_read(&b->hashes[i]) == hash) { + /* The pointer is dereferenced before seqlock_read_retry, + * so (unlike qht_insert__locked) we need to use + * qatomic_rcu_read here. + */ + void *p = qatomic_rcu_read(&b->pointers[i]); + + if (likely(p) && likely(func(p, userp))) { + return p; + } + } + } + b = qatomic_rcu_read(&b->next); + } while (b); + + return NULL; +} + +static __attribute__((noinline)) void *qht_lookup__slowpath(const struct qht_bucket *b, qht_lookup_func_t func, + const void *userp, uint32_t hash) { + unsigned int version; + void *ret; + + do { + version = seqlock_read_begin(&b->sequence); + ret = qht_do_lookup(b, func, userp, hash); + } while (seqlock_read_retry(&b->sequence, version)); + return ret; +} + +void *qht_lookup_custom(const struct qht *ht, const void *userp, uint32_t hash, qht_lookup_func_t func) { + const struct qht_bucket *b; + const struct qht_map *map; + unsigned int version; + void *ret; + + map = qatomic_rcu_read(&ht->map); + b = qht_map_to_bucket(map, hash); + + version = seqlock_read_begin(&b->sequence); + ret = qht_do_lookup(b, func, userp, hash); + if (likely(!seqlock_read_retry(&b->sequence, version))) { + return ret; + } + /* + * Removing the do/while from the fastpath gives a 4% perf. increase when + * running a 100%-lookup microbenchmark. + */ + return qht_lookup__slowpath(b, func, userp, hash); +} + +void *qht_lookup(const struct qht *ht, const void *userp, uint32_t hash) { + return qht_lookup_custom(ht, userp, hash, ht->cmp); +} + +/* + * call with head->lock held + * @ht is const since it is only used for ht->cmp() + */ +static void *qht_insert__locked(const struct qht *ht, struct qht_map *map, struct qht_bucket *head, void *p, + uint32_t hash, bool *needs_resize) { + struct qht_bucket *b = head; + struct qht_bucket *prev = NULL; + struct qht_bucket *new = NULL; + int i; + + do { + for (i = 0; i < QHT_BUCKET_ENTRIES; i++) { + if (b->pointers[i]) { + if (unlikely(b->hashes[i] == hash && ht->cmp(b->pointers[i], p))) { + return b->pointers[i]; + } + } else { + goto found; + } + } + prev = b; + b = b->next; + } while (b); + + b = qemu_memalign(QHT_BUCKET_ALIGN, sizeof(*b)); + memset(b, 0, sizeof(*b)); + new = b; + i = 0; + qatomic_inc(&map->n_added_buckets); + if (unlikely(qht_map_needs_resize(map)) && needs_resize) { + *needs_resize = true; + } + +found: + /* found an empty key: acquire the seqlock and write */ + seqlock_write_begin(&head->sequence); + if (new) { + qatomic_rcu_set(&prev->next, b); + } + /* smp_wmb() implicit in seqlock_write_begin. */ + qatomic_set(&b->hashes[i], hash); + qatomic_set(&b->pointers[i], p); + seqlock_write_end(&head->sequence); + return NULL; +} + +static __attribute__((noinline)) void qht_grow_maybe(struct qht *ht) { + struct qht_map *map; + + /* + * If the lock is taken it probably means there's an ongoing resize, + * so bail out. + */ + if (qht_trylock(ht)) { + return; + } + map = ht->map; + /* another thread might have just performed the resize we were after */ + if (qht_map_needs_resize(map)) { + struct qht_map *new = qht_map_create(map->n_buckets * 2); + + qht_do_resize(ht, new); + } + qht_unlock(ht); +} + +bool qht_insert(struct qht *ht, void *p, uint32_t hash, void **existing) { + struct qht_bucket *b; + struct qht_map *map; + bool needs_resize = false; + void *prev; + + /* NULL pointers are not supported */ + qht_debug_assert(p); + + b = qht_bucket_lock__no_stale(ht, hash, &map); + prev = qht_insert__locked(ht, map, b, p, hash, &needs_resize); + qht_bucket_debug__locked(b); + qht_bucket_unlock(map, b); + + if (unlikely(needs_resize) && ht->mode & QHT_MODE_AUTO_RESIZE) { + qht_grow_maybe(ht); + } + if (likely(prev == NULL)) { + return true; + } + if (existing) { + *existing = prev; + } + return false; +} + +static inline bool qht_entry_is_last(const struct qht_bucket *b, int pos) { + if (pos == QHT_BUCKET_ENTRIES - 1) { + if (b->next == NULL) { + return true; + } + return b->next->pointers[0] == NULL; + } + return b->pointers[pos + 1] == NULL; +} + +static void qht_entry_move(struct qht_bucket *to, int i, struct qht_bucket *from, int j) { + qht_debug_assert(!(to == from && i == j)); + qht_debug_assert(to->pointers[i]); + qht_debug_assert(from->pointers[j]); + + qatomic_set(&to->hashes[i], from->hashes[j]); + qatomic_set(&to->pointers[i], from->pointers[j]); + + qatomic_set(&from->hashes[j], 0); + qatomic_set(&from->pointers[j], NULL); +} + +/* + * Find the last valid entry in @orig, and swap it with @orig[pos], which has + * just been invalidated. + */ +static inline void qht_bucket_remove_entry(struct qht_bucket *orig, int pos) { + struct qht_bucket *b = orig; + struct qht_bucket *prev = NULL; + int i; + + if (qht_entry_is_last(orig, pos)) { + qatomic_set(&orig->hashes[pos], 0); + qatomic_set(&orig->pointers[pos], NULL); + return; + } + do { + for (i = 0; i < QHT_BUCKET_ENTRIES; i++) { + if (b->pointers[i]) { + continue; + } + if (i > 0) { + return qht_entry_move(orig, pos, b, i - 1); + } + qht_debug_assert(prev); + return qht_entry_move(orig, pos, prev, QHT_BUCKET_ENTRIES - 1); + } + prev = b; + b = b->next; + } while (b); + /* no free entries other than orig[pos], so swap it with the last one */ + qht_entry_move(orig, pos, prev, QHT_BUCKET_ENTRIES - 1); +} + +/* call with b->lock held */ +static inline bool qht_remove__locked(struct qht_bucket *head, const void *p, uint32_t hash) { + struct qht_bucket *b = head; + int i; + + do { + for (i = 0; i < QHT_BUCKET_ENTRIES; i++) { + void *q = b->pointers[i]; + + if (unlikely(q == NULL)) { + return false; + } + if (q == p) { + qht_debug_assert(b->hashes[i] == hash); + seqlock_write_begin(&head->sequence); + qht_bucket_remove_entry(b, i); + seqlock_write_end(&head->sequence); + return true; + } + } + b = b->next; + } while (b); + return false; +} + +bool qht_remove(struct qht *ht, const void *p, uint32_t hash) { + struct qht_bucket *b; + struct qht_map *map; + bool ret; + + /* NULL pointers are not supported */ + qht_debug_assert(p); + + b = qht_bucket_lock__no_stale(ht, hash, &map); + ret = qht_remove__locked(b, p, hash); + qht_bucket_debug__locked(b); + qht_bucket_unlock(map, b); + return ret; +} + +static inline void qht_bucket_iter(struct qht_bucket *head, const struct qht_iter *iter, void *userp) { + struct qht_bucket *b = head; + int i; + + do { + for (i = 0; i < QHT_BUCKET_ENTRIES; i++) { + if (b->pointers[i] == NULL) { + return; + } + switch (iter->type) { + case QHT_ITER_VOID: + iter->f.retvoid(b->pointers[i], b->hashes[i], userp); + break; + case QHT_ITER_RM: + if (iter->f.retbool(b->pointers[i], b->hashes[i], userp)) { + /* replace i with the last valid element in the bucket */ + seqlock_write_begin(&head->sequence); + qht_bucket_remove_entry(b, i); + seqlock_write_end(&head->sequence); + qht_bucket_debug__locked(b); + /* reevaluate i, since it just got replaced */ + i--; + continue; + } + break; + default: + g_assert_not_reached(); + } + } + b = b->next; + } while (b); +} + +/* call with all of the map's locks held */ +static inline void qht_map_iter__all_locked(struct qht_map *map, const struct qht_iter *iter, void *userp) { + size_t i; + + for (i = 0; i < map->n_buckets; i++) { + qht_bucket_iter(&map->buckets[i], iter, userp); + } +} + +static inline void do_qht_iter(struct qht *ht, const struct qht_iter *iter, void *userp) { + struct qht_map *map; + + map = qatomic_rcu_read(&ht->map); + qht_map_lock_buckets(map); + qht_map_iter__all_locked(map, iter, userp); + qht_map_unlock_buckets(map); +} + +void qht_iter(struct qht *ht, qht_iter_func_t func, void *userp) { + const struct qht_iter iter = { + .f.retvoid = func, + .type = QHT_ITER_VOID, + }; + + do_qht_iter(ht, &iter, userp); +} + +void qht_iter_remove(struct qht *ht, qht_iter_bool_func_t func, void *userp) { + const struct qht_iter iter = { + .f.retbool = func, + .type = QHT_ITER_RM, + }; + + do_qht_iter(ht, &iter, userp); +} + +struct qht_map_copy_data { + struct qht *ht; + struct qht_map *new; +}; + +static void qht_map_copy(void *p, uint32_t hash, void *userp) { + struct qht_map_copy_data *data = userp; + struct qht *ht = data->ht; + struct qht_map *new = data->new; + struct qht_bucket *b = qht_map_to_bucket(new, hash); + + /* no need to acquire b->lock because no thread has seen this map yet */ + qht_insert__locked(ht, new, b, p, hash, NULL); +} + +/* + * Atomically perform a resize and/or reset. + * Call with ht->lock held. + */ +static void qht_do_resize_reset(struct qht *ht, struct qht_map *new, bool reset) { + struct qht_map *old; + const struct qht_iter iter = { + .f.retvoid = qht_map_copy, + .type = QHT_ITER_VOID, + }; + struct qht_map_copy_data data; + + old = ht->map; + qht_map_lock_buckets(old); + + if (reset) { + qht_map_reset__all_locked(old); + } + + if (new == NULL) { + qht_map_unlock_buckets(old); + return; + } + + g_assert(new->n_buckets != old->n_buckets); + data.ht = ht; + data.new = new; + qht_map_iter__all_locked(old, &iter, &data); + qht_map_debug__all_locked(new); + + qatomic_rcu_set(&ht->map, new); + qht_map_unlock_buckets(old); + call_rcu(old, qht_map_destroy, rcu); +} + +bool qht_resize(struct qht *ht, size_t n_elems) { + size_t n_buckets = qht_elems_to_buckets(n_elems); + size_t ret = false; + + qht_lock(ht); + if (n_buckets != ht->map->n_buckets) { + struct qht_map *new; + + new = qht_map_create(n_buckets); + qht_do_resize(ht, new); + ret = true; + } + qht_unlock(ht); + + return ret; +} + +/* Upstream qht_statistics_init/destroy are removed along with qdist; see qht.h. */ diff --git a/libutils/src/utils/rcu.c b/libutils/src/utils/rcu.c new file mode 100644 index 000000000..33e410139 --- /dev/null +++ b/libutils/src/utils/rcu.c @@ -0,0 +1,456 @@ +/* + * urcu-mb.c + * + * Userspace RCU library with explicit memory barriers + * + * Copyright (c) 2009 Mathieu Desnoyers + * Copyright (c) 2009 Paul E. McKenney, IBM Corporation. + * Copyright 2015 Red Hat, Inc. + * + * Ported to QEMU by Paolo Bonzini + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see + * . + * + * IBM's contributions to this file may be relicensed under LGPLv2 or later. + */ + +#include +#include +#include +#include +#include +#if defined(CONFIG_MALLOC_TRIM) +#include +#endif + +/* + * Upstream runs RCU callbacks under the big QEMU lock (qemu/main-loop.h). + * The BQL is not vendored, so callbacks here must not rely on it. + */ + +/* + * Global grace period counter. Bit 0 is always one in rcu_gp_ctr. + * Bits 1 and above are defined in synchronize_rcu. + */ +#define RCU_GP_LOCKED (1UL << 0) +#define RCU_GP_CTR (1UL << 1) + +#define RCU_CALL_MIN_SIZE 30 + +unsigned long rcu_gp_ctr = RCU_GP_LOCKED; + +QemuEvent rcu_gp_event; +static int in_drain_call_rcu; +static int rcu_call_count; +static QemuMutex rcu_registry_lock; +static QemuMutex rcu_sync_lock; + +/* + * Check whether a quiescent state was crossed between the beginning of + * update_counter_and_wait and now. + */ +static inline int rcu_gp_ongoing(unsigned long *ctr) { + unsigned long v; + + v = qatomic_read(ctr); + return v && (v != rcu_gp_ctr); +} + +/* Written to only by each individual reader. Read by both the reader and the + * writers. + */ +QEMU_DEFINE_CO_TLS(struct rcu_reader_data, rcu_reader) + +/* Protected by rcu_registry_lock. */ +typedef QLIST_HEAD(, rcu_reader_data) ThreadList; +static ThreadList registry = QLIST_HEAD_INITIALIZER(registry); + +/* Wait for previous parity/grace period to be empty of readers. */ +static void wait_for_readers(void) { + ThreadList qsreaders = QLIST_HEAD_INITIALIZER(qsreaders); + struct rcu_reader_data *index, *tmp; + int sleeps = 0; + bool forced = false; + + for (;;) { + /* + * Force the grace period to end and wait for it if any of the + * following heuristical conditions are satisfied: + * - A decent number of callbacks piled up. + * - It timed out. + * - It is in a drain_call_rcu() call. + * + * Otherwise, periodically poll the grace period, hoping it ends + * promptly. + */ + if (!forced && + (qatomic_read(&rcu_call_count) >= RCU_CALL_MIN_SIZE || sleeps >= 5 || qatomic_read(&in_drain_call_rcu))) { + forced = true; + + QLIST_FOREACH (index, ®istry, node) { + notifier_list_notify(&index->force_rcu, NULL); + qatomic_set(&index->waiting, true); + } + } + + /* Here, order the stores to index->waiting before the loads of + * index->ctr. Pairs with smp_mb_placeholder() in rcu_read_unlock(), + * ensuring that the loads of index->ctr are sequentially consistent. + * + * If this is the last iteration, this barrier also prevents + * frees from seeping upwards, and orders the two wait phases + * on architectures with 32-bit longs; see synchronize_rcu(). + */ + smp_mb_global(); + + QLIST_FOREACH_SAFE(index, ®istry, node, tmp) { + if (!rcu_gp_ongoing(&index->ctr)) { + QLIST_REMOVE(index, node); + QLIST_INSERT_HEAD(&qsreaders, index, node); + + /* No need for memory barriers here, worst of all we + * get some extra futex wakeups. + */ + qatomic_set(&index->waiting, false); + } + } + + if (QLIST_EMPTY(®istry)) { + break; + } + + /* + * Sleep for a while and try again. + * Release rcu_registry_lock, so rcu_(un)register_thread() doesn't + * wait too much time. + * + * rcu_register_thread() may add nodes to ®istry; it will not + * wake up synchronize_rcu, but that is okay because at least another + * thread must exit its RCU read-side critical section before + * synchronize_rcu is done. The next iteration of the loop will + * move the new thread's rcu_reader from ®istry to &qsreaders, + * because rcu_gp_ongoing() will return false. + * + * rcu_unregister_thread() may remove nodes from &qsreaders instead + * of ®istry if it runs during qemu_event_wait. That's okay; + * the node then will not be added back to ®istry by QLIST_SWAP + * below. The invariant is that the node is part of one list when + * rcu_registry_lock is released. + */ + qemu_mutex_unlock(&rcu_registry_lock); + + if (forced) { + qemu_event_wait(&rcu_gp_event); + + /* + * We want to be notified of changes made to rcu_gp_ongoing + * while we walk the list. + */ + qemu_event_reset(&rcu_gp_event); + } else { + g_usleep(10000); + sleeps++; + } + + qemu_mutex_lock(&rcu_registry_lock); + } + + /* put back the reader list in the registry */ + QLIST_SWAP(®istry, &qsreaders, node); +} + +void synchronize_rcu(void) { + QEMU_LOCK_GUARD(&rcu_sync_lock); + + /* Write RCU-protected pointers before reading p_rcu_reader->ctr. + * Pairs with smp_mb_placeholder() in rcu_read_lock(). + * + * Also orders write to RCU-protected pointers before + * write to rcu_gp_ctr. + */ + smp_mb_global(); + + QEMU_LOCK_GUARD(&rcu_registry_lock); + if (!QLIST_EMPTY(®istry)) { + if (sizeof(rcu_gp_ctr) < 8) { + /* For architectures with 32-bit longs, a two-subphases algorithm + * ensures we do not encounter overflow bugs. + * + * Switch parity: 0 -> 1, 1 -> 0. + */ + qatomic_set(&rcu_gp_ctr, rcu_gp_ctr ^ RCU_GP_CTR); + wait_for_readers(); + qatomic_set(&rcu_gp_ctr, rcu_gp_ctr ^ RCU_GP_CTR); + } else { + /* Increment current grace period. */ + qatomic_set(&rcu_gp_ctr, rcu_gp_ctr + RCU_GP_CTR); + } + + wait_for_readers(); + } +} + +/* Multi-producer, single-consumer queue based on urcu/static/wfqueue.h + * from liburcu. Note that head is only used by the consumer. + */ +static struct rcu_head dummy; +static struct rcu_head *head = &dummy, **tail = &dummy.next; +static QemuEvent rcu_call_ready_event; + +static void enqueue(struct rcu_head *node) { + struct rcu_head **old_tail; + + node->next = NULL; + + /* + * Make this node the tail of the list. The node will be + * used by further enqueue operations, but it will not + * be dequeued yet... + */ + old_tail = qatomic_xchg(&tail, &node->next); + + /* + * ... until it is pointed to from another item in the list. + * In the meantime, try_dequeue() will find a NULL next pointer + * and loop. + * + * Synchronizes with qatomic_load_acquire() in try_dequeue(). + */ + qatomic_store_release(old_tail, node); +} + +static struct rcu_head *try_dequeue(void) { + struct rcu_head *node, *next; + +retry: + /* Head is only written by this thread, so no need for barriers. */ + node = head; + + /* + * If the head node has NULL in its next pointer, the value is + * wrong and we need to wait until its enqueuer finishes the update. + */ + next = qatomic_load_acquire(&node->next); + if (!next) { + return NULL; + } + + /* + * Test for an empty list, which we do not expect. Note that for + * the consumer head and tail are always consistent. The head + * is consistent because only the consumer reads/writes it. + * The tail, because it is the first step in the enqueuing. + * It is only the next pointers that might be inconsistent. + */ + if (head == &dummy && qatomic_read(&tail) == &dummy.next) { + abort(); + } + + /* + * Since we are the sole consumer, and we excluded the empty case + * above, the queue will always have at least two nodes: the + * dummy node, and the one being removed. So we do not need to update + * the tail pointer. + */ + head = next; + + /* If we dequeued the dummy node, add it back at the end and retry. */ + if (node == &dummy) { + enqueue(node); + goto retry; + } + + return node; +} + +static void *call_rcu_thread(void *opaque) { + struct rcu_head *node; + + rcu_register_thread(); + + for (;;) { + int n; + + /* + * Fetch rcu_call_count now, we only must process elements that were + * added before synchronize_rcu() starts. + */ + for (;;) { + qemu_event_reset(&rcu_call_ready_event); + n = qatomic_read(&rcu_call_count); + if (n) { + break; + } + +#if defined(CONFIG_MALLOC_TRIM) + malloc_trim(4 * 1024 * 1024); +#endif + qemu_event_wait(&rcu_call_ready_event); + } + + synchronize_rcu(); + qatomic_sub(&rcu_call_count, n); + while (n > 0) { + node = try_dequeue(); + while (!node) { + qemu_event_reset(&rcu_call_ready_event); + node = try_dequeue(); + if (!node) { + qemu_event_wait(&rcu_call_ready_event); + node = try_dequeue(); + } + } + + n--; + node->func(node); + } + } + abort(); +} + +void call_rcu1(struct rcu_head *node, void (*func)(struct rcu_head *node)) { + node->func = func; + enqueue(node); + qatomic_inc(&rcu_call_count); + qemu_event_set(&rcu_call_ready_event); +} + +struct rcu_drain { + struct rcu_head rcu; + QemuEvent drain_complete_event; +}; + +static void drain_rcu_callback(struct rcu_head *node) { + struct rcu_drain *event = (struct rcu_drain *) node; + qemu_event_set(&event->drain_complete_event); +} + +/* + * This function ensures that all pending RCU callbacks + * on the current thread are done executing + */ + +void drain_call_rcu(void) { + struct rcu_drain rcu_drain; + + memset(&rcu_drain, 0, sizeof(struct rcu_drain)); + qemu_event_init(&rcu_drain.drain_complete_event, false); + + /* + * RCU callbacks are invoked in the same order as in which they + * are registered, thus we can be sure that when 'drain_rcu_callback' + * is called, all RCU callbacks that were registered on this thread + * prior to calling this function are completed. + * + * Note that since we have only one global queue of the RCU callbacks, + * we also end up waiting for most of RCU callbacks that were registered + * on the other threads, but this is a side effect that shouldn't be + * assumed. + */ + + qatomic_inc(&in_drain_call_rcu); + call_rcu1(&rcu_drain.rcu, drain_rcu_callback); + qemu_event_wait(&rcu_drain.drain_complete_event); + qatomic_dec(&in_drain_call_rcu); +} + +void rcu_register_thread(void) { + assert(get_ptr_rcu_reader()->ctr == 0); + qemu_mutex_lock(&rcu_registry_lock); + QLIST_INSERT_HEAD(®istry, get_ptr_rcu_reader(), node); + qemu_mutex_unlock(&rcu_registry_lock); +} + +void rcu_unregister_thread(void) { + qemu_mutex_lock(&rcu_registry_lock); + QLIST_REMOVE(get_ptr_rcu_reader(), node); + qemu_mutex_unlock(&rcu_registry_lock); +} + +void rcu_add_force_rcu_notifier(Notifier *n) { + qemu_mutex_lock(&rcu_registry_lock); + notifier_list_add(&get_ptr_rcu_reader()->force_rcu, n); + qemu_mutex_unlock(&rcu_registry_lock); +} + +void rcu_remove_force_rcu_notifier(Notifier *n) { + qemu_mutex_lock(&rcu_registry_lock); + notifier_remove(n); + qemu_mutex_unlock(&rcu_registry_lock); +} + +static void rcu_init_complete(void) { + QemuThread thread; + + qemu_mutex_init(&rcu_registry_lock); + qemu_mutex_init(&rcu_sync_lock); + qemu_event_init(&rcu_gp_event, true); + + qemu_event_init(&rcu_call_ready_event, false); + + /* The caller is assumed to have BQL, so the call_rcu thread + * must have been quiescent even after forking, just recreate it. + */ + qemu_thread_create(&thread, "call_rcu", call_rcu_thread, NULL, QEMU_THREAD_DETACHED); + + rcu_register_thread(); +} + +static int atfork_depth = 1; + +void rcu_enable_atfork(void) { + atfork_depth++; +} + +void rcu_disable_atfork(void) { + atfork_depth--; +} + +#ifdef CONFIG_POSIX +static void rcu_init_lock(void) { + if (atfork_depth < 1) { + return; + } + + qemu_mutex_lock(&rcu_sync_lock); + qemu_mutex_lock(&rcu_registry_lock); +} + +static void rcu_init_unlock(void) { + if (atfork_depth < 1) { + return; + } + + qemu_mutex_unlock(&rcu_registry_lock); + qemu_mutex_unlock(&rcu_sync_lock); +} + +static void rcu_init_child(void) { + if (atfork_depth < 1) { + return; + } + + memset(®istry, 0, sizeof(registry)); + rcu_init_complete(); +} +#endif + +static void __attribute__((__constructor__)) rcu_init(void) { + smp_mb_global_init(); +#ifdef CONFIG_POSIX + pthread_atfork(rcu_init_lock, rcu_init_unlock, rcu_init_child); +#endif + rcu_init_complete(); +} diff --git a/scripts/upgrade/README.md b/scripts/upgrade/README.md index 054594e9e..2efe51482 100644 --- a/scripts/upgrade/README.md +++ b/scripts/upgrade/README.md @@ -143,8 +143,13 @@ libutils' `utils/mutex.h` and `utils/spinlock.h` stay S2E-original: upstream's ## After merging Re-run `run-clang-format.sh` from the S2E source root so the tree stays -normalized for the next upgrade, update each component's `BASELINE`, and -confirm normalization by merging the new tag onto itself: +normalized for the next upgrade, update each component's `BASELINE`, and check +that every mapping row still resolves by merging the new tag onto itself: - ./merge.sh libutils # must be 0 conflicts - ./merge.sh libtcg # must be 0 conflicts + ./merge.sh libutils + ./merge.sh libtcg + +A same-tag run cannot conflict, because base and theirs are identical, so zero +conflicts here proves only that the mapping resolves at the tag and that the +normalize pipeline runs. Whether the S2E deviations (including pruned sections) +merge cleanly is only tested by a real upgrade to a different tag. From 3dc5bd9fa460bb3cb315564049cc8f9421fe3843 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Mon, 24 Aug 2026 10:16:20 +0000 Subject: [PATCH 23/52] libcpu: moved the CPU caches out of CPUX86State into ArchCPU The new cpu/state.h defines the slim CPUState, CPUNegativeOffsetState and ArchCPU with upstream's layout contract: CPUX86State immediately follows CPUState, so cpu_env() / env_cpu() are pointer arithmetic and generated code reaches the TLB at a negative offset from env (tlb-update.md, step 2). The TLB, the RAM TLB, se_tlb_current and the TB jump cache moved from CPU_COMMON into CPUNegativeOffsetState, keeping the QEMU-1.0 TLB organization; the unused iotlb_ramaddr array is gone. cpu_x86_init() allocates the enclosing ArchCPU, and tlb_fast_offset is now negative. libs2ecore registers the cache region as a third shared-concrete KLEE object so the bitcode softmmu fast path still resolves, snapshots it explicitly in saveConcreteState() / restoreConcreteState() to keep the per-state semantics unchanged, and reaches it through the new getCpuCaches() accessor, which also fixes flushTlbCachePage() and clearRamTlb() bypassing the per-state buffer via the global env. Co-Authored-By: Claude Fable 5 --- libcpu/include/cpu/common.h | 5 +- libcpu/include/cpu/i386/cpu.h | 3 + libcpu/include/cpu/state.h | 158 ++++++++++++++++++ libcpu/include/cpu/tlb.h | 21 +-- libcpu/src/cpu-all.h | 2 +- libcpu/src/cpu-exec.c | 4 +- libcpu/src/exec-tb.c | 6 +- libcpu/src/exec-tlb.c | 49 +++--- libcpu/src/exec-tlb.h | 2 +- libcpu/src/exec.c | 8 +- libcpu/src/softmmu_header.h | 10 +- libcpu/src/softmmu_template.h | 28 ++-- libcpu/src/target-i386/helper.c | 5 +- libcpu/src/translate-all.c | 3 +- .../include/s2e/S2EExecutionStateRegisters.h | 19 ++- libs2ecore/include/s2e/S2EExecutionStateTlb.h | 2 +- libs2ecore/src/ExprInterface.cpp | 6 +- libs2ecore/src/MMUFunctionHandlers.cpp | 6 +- libs2ecore/src/S2EExecutionState.cpp | 4 +- libs2ecore/src/S2EExecutionStateRegisters.cpp | 18 +- libs2ecore/src/S2EExecutionStateTlb.cpp | 36 ++-- libs2ecore/src/S2EExecutor.cpp | 10 +- 22 files changed, 294 insertions(+), 111 deletions(-) create mode 100644 libcpu/include/cpu/state.h diff --git a/libcpu/include/cpu/common.h b/libcpu/include/cpu/common.h index 6cca0f401..d53f3adb5 100644 --- a/libcpu/include/cpu/common.h +++ b/libcpu/include/cpu/common.h @@ -63,10 +63,7 @@ typedef struct CPUWatchpoint { uint32_t halted; /* Nonzero if the CPU is in suspend state */ \ uint32_t interrupt_request; \ volatile sig_atomic_t exit_request; \ - CPU_COMMON_TLB \ - CPU_COMMON_PHYSRAM_TLB \ - CPUTLBEntry *se_tlb_current; \ - struct TranslationBlock *tb_jmp_cache[TB_JMP_CACHE_SIZE]; \ + /* The TLB, RAM TLB and TB jump cache live in CPUState; see cpu/state.h */ \ /* buffer for temporaries in the code generator */ \ long temp_buf[CPU_TEMP_BUF_NLONGS]; \ /* Used to handle self-modifying code */ \ diff --git a/libcpu/include/cpu/i386/cpu.h b/libcpu/include/cpu/i386/cpu.h index 393044ba9..56771b82f 100644 --- a/libcpu/include/cpu/i386/cpu.h +++ b/libcpu/include/cpu/i386/cpu.h @@ -201,6 +201,9 @@ typedef struct CPUX86State { #endif } CPUX86State; +/* Requires the complete CPUX86State: defines ArchCPU and the CPU caches. */ +#include + void do_cpu_init(CPUX86State *env); CPUX86State *cpu_x86_init(const cpuid_t *cpuid); diff --git a/libcpu/include/cpu/state.h b/libcpu/include/cpu/state.h new file mode 100644 index 000000000..c0031b4fc --- /dev/null +++ b/libcpu/include/cpu/state.h @@ -0,0 +1,158 @@ +/// Copyright (C) 2003 Fabrice Bellard +/// Copyright (C) 2012 SUSE LINUX Products GmbH +/// Copyright (C) 2026 Vitaly Chipounov +/// Copyrights of all contributions belong to their respective owners. +/// +/// This library is free software; you can redistribute it and/or +/// modify it under the terms of the GNU Library General Public +/// License as published by the Free Software Foundation; either +/// version 2 of the License, or (at your option) any later version. +/// +/// This library is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +/// Library General Public License for more details. +/// +/// You should have received a copy of the GNU Library General Public +/// License along with this library; if not, see . + +#ifndef S2E_CPU_STATE_H +#define S2E_CPU_STATE_H + +/* + * Hand-written replacement for upstream's include/hw/core/cpu.h (PORTING.md, + * decision 3.1). It carries upstream's layout contract: neg is the last + * member of CPUState, and CPUArchState immediately follows CPUState inside + * ArchCPU, so that cpu_env() / env_cpu() are pointer arithmetic and generated + * code reaches the TLB at a fixed negative offset from env. + * + * CPUState holds only the CPU caches for now: the TLB, the RAM TLB and the + * TB jump cache, moved out of CPUX86State so that they stop being part of + * the snapshotted execution state (tlb-update.md). The execution-state fields + * of upstream's CPUState (exception_index, interrupt_request, jmp_env, ...) + * migrate here from CPUX86State during the port (PORTING.md phase 4). + * + * The TLB keeps the QEMU 1.0 organization (fixed size, iotlb, no victim TLB, + * no CPUTLBEntryFull); upstream's algorithms arrive with the cputlb.c import + * (PORTING.md phase 2). + * + * This header is included at the end of cpu/i386/cpu.h: ArchCPU embeds + * CPUArchState by value, so the complete CPUX86State must be visible first. + */ + +#include +#include + +#include + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef CPUArchState +#define CPUArchState struct CPUX86State +#endif + +struct TCGCPUOps; +struct TranslationBlock; + +/* Data elements that are per MMU mode, minus the bits accessed by the TCG fast path. */ +typedef struct CPUTLBDesc { + target_phys_addr_t iotlb[CPU_TLB_SIZE]; + /* Backing store for the fast-path table; f[i].table points here. */ + CPUTLBEntry table[CPU_TLB_SIZE]; +} CPUTLBDesc; + +/* The entire softmmu tlb, for all MMU modes. */ +typedef struct CPUTLB { + CPUTLBDesc d[NB_MMU_MODES]; + CPUTLBDescFast f[NB_MMU_MODES]; + /* Region covered by large pages, one pair for all MMU modes; invalidating + it forces a full flush (upstream 11.1 tracks this per CPUTLBDesc). */ + target_ulong tlb_flush_addr; + target_ulong tlb_flush_mask; +} CPUTLB; + +/* + * Elements of CPUState accessed from CPUArchState via negative offsets. + * The most frequently used members should be last, closest to env. + */ +typedef struct CPUNegativeOffsetState { + CPUTLB tlb; + +#if defined(SE_ENABLE_PHYSRAM_TLB) + /* The RAM TLB has no CPUTLBDescFast and keeps its own pinned size (PORTING.md 9.2). */ + CPUTLBRAMEntry se_ram_tlb[CPU_TLB_SIZE]; +#endif + /* Cached by the softmmu IO path; points into the tables above, so it + lives and dies with them (PORTING.md 9.6). */ + CPUTLBEntry *se_tlb_current; + + struct TranslationBlock *tb_jmp_cache[TB_JMP_CACHE_SIZE]; +} CPUNegativeOffsetState; + +/* + * Common state of one CPU core or thread. Slim version of upstream's + * CPUState: no QOM, no threading, no work queues, one address space. + */ +typedef struct CPUState { + /* Replaces upstream's cpu->cc->tcg_ops; wired up when the 11.1 accel/tcg + code lands (PORTING.md 3.1). */ + const struct TCGCPUOps *tcg_ops; + + /* MUST BE LAST, to minimize the displacement to CPUArchState. */ + char neg_align[-sizeof(CPUNegativeOffsetState) % 16] QEMU_ALIGNED(16); + CPUNegativeOffsetState neg; +} CPUState; + +/* Validate placement of CPUNegativeOffsetState. */ +QEMU_BUILD_BUG_ON(offsetof(CPUState, neg) != sizeof(CPUState) - sizeof(CPUNegativeOffsetState)); + +typedef struct ArchCPU { + CPUState parent_obj; + + /* Must immediately follow parent_obj: cpu_env() and env_cpu() depend on it. */ + CPUArchState env; + + /* Target fields (phys_bits, cache info, ...) land here in phase 3 (PORTING.md 3.5). */ +} ArchCPU; + +QEMU_BUILD_BUG_ON(offsetof(ArchCPU, parent_obj) != 0); +QEMU_BUILD_BUG_ON(offsetof(ArchCPU, env) != sizeof(CPUState)); + +static inline CPUArchState *cpu_env(CPUState *cpu) { + return (CPUArchState *) (cpu + 1); +} + +static inline const CPUState *env_cpu_const(const CPUArchState *env) { + return (const CPUState *) ((const char *) env - sizeof(CPUState)); +} + +static inline CPUState *env_cpu(CPUArchState *env) { + return (CPUState *) env_cpu_const(env); +} + +static inline ArchCPU *env_archcpu(CPUArchState *env) { + return (ArchCPU *) env_cpu(env); +} + +static inline CPUTLB *env_tlb(CPUArchState *env) { + return &env_cpu(env)->neg.tlb; +} + +/* f[] is indexed directly, without upstream's mmuidx_to_fast_index() + inversion; libtcg's tlb_mask_table_ofs() does the same (tlb-update.md). */ +static inline CPUTLBDescFast *cpu_tlb_fast(CPUState *cpu, int mmu_idx) { + return &cpu->neg.tlb.f[mmu_idx]; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libcpu/include/cpu/tlb.h b/libcpu/include/cpu/tlb.h index 2ab513ae3..611d39b4b 100644 --- a/libcpu/include/cpu/tlb.h +++ b/libcpu/include/cpu/tlb.h @@ -32,20 +32,7 @@ extern "C" { #define CPU_TLB_BITS 10 #define CPU_TLB_SIZE (1 << CPU_TLB_BITS) -#if defined(CONFIG_SYMBEX) && defined(CONFIG_SYMBEX_MP) -#define CPU_IOTLB_CHECK target_phys_addr_t iotlb_ramaddr[NB_MMU_MODES][CPU_TLB_SIZE]; -#else -#define CPU_IOTLB_CHECK -#endif - -#define CPU_COMMON_TLB \ - /* The meaning of the MMU modes is defined in the target code. */ \ - CPUTLBDescFast tlb_table[NB_MMU_MODES]; \ - CPUTLBEntry _tlb_table[NB_MMU_MODES][CPU_TLB_SIZE]; \ - target_phys_addr_t iotlb[NB_MMU_MODES][CPU_TLB_SIZE]; \ - CPU_IOTLB_CHECK \ - target_ulong tlb_flush_addr; \ - target_ulong tlb_flush_mask; +/* The TLB itself lives outside CPUX86State, in CPUState; see cpu/state.h. */ typedef struct CPUTLBRAMEntry { uintptr_t host_page; @@ -53,12 +40,6 @@ typedef struct CPUTLBRAMEntry { void *object_state; } CPUTLBRAMEntry; -#if defined(SE_ENABLE_PHYSRAM_TLB) -#define CPU_COMMON_PHYSRAM_TLB CPUTLBRAMEntry se_ram_tlb[CPU_TLB_SIZE]; -#else -#define CPU_COMMON_PHYSRAM_TLB -#endif - #ifdef __cplusplus } #endif diff --git a/libcpu/src/cpu-all.h b/libcpu/src/cpu-all.h index 564973a1c..97ae4acbf 100644 --- a/libcpu/src/cpu-all.h +++ b/libcpu/src/cpu-all.h @@ -156,7 +156,7 @@ static inline void *_se_check_translate_ram_access(const void *p, unsigned size) #if defined(SE_ENABLE_PHYSRAM_TLB) extern CPUArchState *env; uintptr_t tlb_index = ((uintptr_t) p >> 12) & (CPU_TLB_SIZE - 1); - CPUTLBRAMEntry *re = &env->se_ram_tlb[tlb_index]; + CPUTLBRAMEntry *re = &env_cpu(env)->neg.se_ram_tlb[tlb_index]; if (re->host_page == (((uintptr_t) p) & (~(uintptr_t) 0xfff | (size - 1)))) { return (void *) ((uintptr_t) p + re->addend); } diff --git a/libcpu/src/cpu-exec.c b/libcpu/src/cpu-exec.c index b085e608a..8e3f0b91f 100644 --- a/libcpu/src/cpu-exec.c +++ b/libcpu/src/cpu-exec.c @@ -126,7 +126,7 @@ static TranslationBlock *tb_find_slow(CPUArchState *env, target_ulong pc, target tb_phys_hash[h] = tb; } /* we add the TB in the virtual pc hash table */ - env->tb_jmp_cache[tb_jmp_cache_hash_func(pc)] = tb; + env_cpu(env)->neg.tb_jmp_cache[tb_jmp_cache_hash_func(pc)] = tb; return tb; } @@ -151,7 +151,7 @@ static inline TranslationBlock *tb_find_fast(CPUArchState *env) { always be the same before a given translated block is executed. */ cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags); - tb = env->tb_jmp_cache[tb_jmp_cache_hash_func(pc)]; + tb = env_cpu(env)->neg.tb_jmp_cache[tb_jmp_cache_hash_func(pc)]; #ifdef CONFIG_SYMBEX int llvm_nok = env->generate_llvm && (!tb || !tb->llvm_function); diff --git a/libcpu/src/exec-tb.c b/libcpu/src/exec-tb.c index 8eb45fd16..0b476b232 100644 --- a/libcpu/src/exec-tb.c +++ b/libcpu/src/exec-tb.c @@ -94,7 +94,7 @@ void tb_flush(CPUArchState *env) { #endif for (env = first_cpu; env != NULL; env = env->next_cpu) { - memset(env->tb_jmp_cache, 0, TB_JMP_CACHE_SIZE * sizeof(void *)); + memset(env_cpu(env)->neg.tb_jmp_cache, 0, TB_JMP_CACHE_SIZE * sizeof(void *)); } memset(tb_phys_hash, 0, CODE_GEN_PHYS_HASH_SIZE * sizeof(void *)); @@ -208,8 +208,8 @@ void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr) { /* remove the TB from the hash list */ h = tb_jmp_cache_hash_func(tb->pc); for (env = first_cpu; env != NULL; env = env->next_cpu) { - if (env->tb_jmp_cache[h] == tb) - env->tb_jmp_cache[h] = NULL; + if (env_cpu(env)->neg.tb_jmp_cache[h] == tb) + env_cpu(env)->neg.tb_jmp_cache[h] = NULL; } /* suppress this TB from the two jump lists */ diff --git a/libcpu/src/exec-tlb.c b/libcpu/src/exec-tlb.c index f88589733..b9616486f 100644 --- a/libcpu/src/exec-tlb.c +++ b/libcpu/src/exec-tlb.c @@ -36,10 +36,10 @@ static inline void tlb_flush_jmp_cache(CPUArchState *env, target_ulong addr) { /* Discard jump cache entries for any tb which might potentially overlap the flushed page. */ i = tb_jmp_cache_hash_page(addr - TARGET_PAGE_SIZE); - memset(&env->tb_jmp_cache[i], 0, TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *)); + memset(&env_cpu(env)->neg.tb_jmp_cache[i], 0, TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *)); i = tb_jmp_cache_hash_page(addr); - memset(&env->tb_jmp_cache[i], 0, TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *)); + memset(&env_cpu(env)->neg.tb_jmp_cache[i], 0, TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *)); } static const CPUTLBEntry s_cputlb_empty_entry = { @@ -86,11 +86,12 @@ void tlb_flush(CPUArchState *env, int flush_global) { env->current_tb = NULL; int mmu_idx; + CPUTLB *tlb = env_tlb(env); for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - env->tlb_table[mmu_idx].mask = (CPU_TLB_SIZE - 1) << CPU_TLB_ENTRY_BITS; - env->tlb_table[mmu_idx].table = &env->_tlb_table[mmu_idx][0]; + tlb->f[mmu_idx].mask = (CPU_TLB_SIZE - 1) << CPU_TLB_ENTRY_BITS; + tlb->f[mmu_idx].table = &tlb->d[mmu_idx].table[0]; for (i = 0; i < CPU_TLB_SIZE; i++) { - env->tlb_table[mmu_idx].table[i] = s_cputlb_empty_entry; + tlb->f[mmu_idx].table[i] = s_cputlb_empty_entry; } } @@ -100,10 +101,10 @@ void tlb_flush(CPUArchState *env, int flush_global) { } #endif - memset(env->tb_jmp_cache, 0, TB_JMP_CACHE_SIZE * sizeof(void *)); + memset(env_cpu(env)->neg.tb_jmp_cache, 0, TB_JMP_CACHE_SIZE * sizeof(void *)); - env->tlb_flush_addr = -1; - env->tlb_flush_mask = 0; + tlb->tlb_flush_addr = -1; + tlb->tlb_flush_mask = 0; g_tlb_flush_count++; } @@ -115,10 +116,10 @@ void tlb_flush_page(CPUArchState *env, target_ulong addr) { printf("tlb_flush_page: " TARGET_FMT_lx "\n", addr); #endif /* Check if we need to flush due to large pages. */ - if ((addr & env->tlb_flush_mask) == env->tlb_flush_addr) { + if ((addr & env_tlb(env)->tlb_flush_mask) == env_tlb(env)->tlb_flush_addr) { #if defined(DEBUG_TLB) - printf("tlb_flush_page: forced full flush (" TARGET_FMT_lx "/" TARGET_FMT_lx ")\n", env->tlb_flush_addr, - env->tlb_flush_mask); + printf("tlb_flush_page: forced full flush (" TARGET_FMT_lx "/" TARGET_FMT_lx ")\n", + env_tlb(env)->tlb_flush_addr, env_tlb(env)->tlb_flush_mask); #endif tlb_flush(env, 1); return; @@ -130,13 +131,12 @@ void tlb_flush_page(CPUArchState *env, target_ulong addr) { addr &= TARGET_PAGE_MASK; i = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - // tlb_flush_entry(&env->tlb_table[mmu_idx][i], addr); - CPUTLBEntry *tlb_entry = &env->tlb_table[mmu_idx].table[i]; + CPUTLBEntry *tlb_entry = &env_tlb(env)->f[mmu_idx].table[i]; if (addr == (tlb_entry->addr_read & (TARGET_PAGE_MASK | TLB_INVALID_MASK)) || addr == (tlb_entry->addr_write & (TARGET_PAGE_MASK | TLB_INVALID_MASK)) || addr == (tlb_entry->addr_code & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) { #if defined(CONFIG_SYMBEX) - g_sqi.tlb.flush_tlb_cache_page(env->tlb_table[mmu_idx].table[i].objectState, mmu_idx, i); + g_sqi.tlb.flush_tlb_cache_page(tlb_entry->objectState, mmu_idx, i); #endif *tlb_entry = s_cputlb_empty_entry; } @@ -170,7 +170,7 @@ int tlb_is_dirty(CPUArchState *env, target_ulong vaddr) { vaddr &= TARGET_PAGE_MASK; i = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - ret &= tlb_get_dirty1(&env->tlb_table[mmu_idx].table[i], vaddr); + ret &= tlb_get_dirty1(&env_tlb(env)->f[mmu_idx].table[i], vaddr); } return ret; @@ -181,21 +181,22 @@ int tlb_is_dirty(CPUArchState *env, target_ulong vaddr) { large pages and trigger a full TLB flush if these are invalidated. */ static void tlb_add_large_page(CPUArchState *env, target_ulong vaddr, target_ulong size) { target_ulong mask = ~(size - 1); + CPUTLB *tlb = env_tlb(env); - if (env->tlb_flush_addr == (target_ulong) -1) { - env->tlb_flush_addr = vaddr & mask; - env->tlb_flush_mask = mask; + if (tlb->tlb_flush_addr == (target_ulong) -1) { + tlb->tlb_flush_addr = vaddr & mask; + tlb->tlb_flush_mask = mask; return; } /* Extend the existing region to include the new page. This is a compromise between unnecessary flushes and the cost of maintaining a full variable size TLB. */ - mask &= env->tlb_flush_mask; - while (((env->tlb_flush_addr ^ vaddr) & mask) != 0) { + mask &= tlb->tlb_flush_mask; + while (((tlb->tlb_flush_addr ^ vaddr) & mask) != 0) { mask <<= 1; } - env->tlb_flush_addr &= mask; - env->tlb_flush_mask = mask; + tlb->tlb_flush_addr &= mask; + tlb->tlb_flush_mask = mask; } /* Add a new TLB entry. At most one entry for a given virtual address @@ -252,9 +253,9 @@ void tlb_set_page(CPUArchState *env, target_ulong vaddr, target_phys_addr_t padd } index = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); - env->iotlb[mmu_idx][index] = iotlb - vaddr; + env_tlb(env)->d[mmu_idx].iotlb[index] = iotlb - vaddr; - te = &env->tlb_table[mmu_idx].table[index]; + te = &env_tlb(env)->f[mmu_idx].table[index]; te->addend = addend - vaddr; if (prot & PAGE_READ) { te->addr_read = address; diff --git a/libcpu/src/exec-tlb.h b/libcpu/src/exec-tlb.h index 2d7bc1ec5..b60dde59b 100644 --- a/libcpu/src/exec-tlb.h +++ b/libcpu/src/exec-tlb.h @@ -39,7 +39,7 @@ static inline void tlb_set_dirty(CPUArchState *env, target_ulong vaddr) { vaddr &= TARGET_PAGE_MASK; i = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - tlb_set_dirty1(&env->tlb_table[mmu_idx].table[i], vaddr); + tlb_set_dirty1(&env_tlb(env)->f[mmu_idx].table[i], vaddr); } } diff --git a/libcpu/src/exec.c b/libcpu/src/exec.c index cf78f7123..66cc5d5f0 100644 --- a/libcpu/src/exec.c +++ b/libcpu/src/exec.c @@ -162,7 +162,7 @@ void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t end, int dirty int mmu_idx; for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { for (i = 0; i < CPU_TLB_SIZE; i++) - tlb_reset_dirty_range(&env->tlb_table[mmu_idx].table[i], start1, length); + tlb_reset_dirty_range(&env_tlb(env)->f[mmu_idx].table[i], start1, length); } } } @@ -536,10 +536,10 @@ tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr) { page_index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); mmu_idx = cpu_mmu_index(env1); - if (unlikely(env1->tlb_table[mmu_idx].table[page_index].addr_code != (addr & TARGET_PAGE_MASK))) { + if (unlikely(env_tlb(env1)->f[mmu_idx].table[page_index].addr_code != (addr & TARGET_PAGE_MASK))) { cpu_ldub_code(env1, addr); } - pd = env1->iotlb[mmu_idx][page_index] & ~TARGET_PAGE_MASK; + pd = env_tlb(env1)->d[mmu_idx].iotlb[page_index] & ~TARGET_PAGE_MASK; if (!mem_desc_find(pd)) { #if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_SPARC) cpu_unassigned_access(env1, addr, 0, 1, 0, 4); @@ -547,7 +547,7 @@ tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr) { cpu_abort(env1, "Trying to execute code outside RAM or ROM at 0x" TARGET_FMT_lx "\n", addr); #endif } - p = (void *) ((uintptr_t) addr + env1->tlb_table[mmu_idx].table[page_index].addend); + p = (void *) ((uintptr_t) addr + env_tlb(env1)->f[mmu_idx].table[page_index].addend); return qemu_ram_addr_from_host_nofail(p); } diff --git a/libcpu/src/softmmu_header.h b/libcpu/src/softmmu_header.h index fb08a2f72..0f7ce68ab 100644 --- a/libcpu/src/softmmu_header.h +++ b/libcpu/src/softmmu_header.h @@ -170,7 +170,7 @@ static SMHINLINE RES_TYPE glue(glue(glue(CPU_PREFIX, ld), USUFFIX), MEMSUFFIX)(C #endif mmu_idx = CPU_MMU_INDEX; - tlb_entry = &env->tlb_table[mmu_idx].table[page_index]; + tlb_entry = &env_tlb(env)->f[mmu_idx].table[page_index]; tlb_addr = tlb_entry->ADDR_READ & ~TLB_MEM_TRACE; if (unlikely(tlb_addr != (addr & (TARGET_PAGE_MASK | (DATA_SIZE - 1))))) { res = glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(env, addr, mmu_idx, NULL); @@ -182,7 +182,7 @@ static SMHINLINE RES_TYPE glue(glue(glue(CPU_PREFIX, ld), USUFFIX), MEMSUFFIX)(C physaddr = addr + tlb_entry->se_addend; res = glue(glue(ld, USUFFIX), _p)((uint8_t *) physaddr); #else - physaddr = addr + env->tlb_table[mmu_idx].table[page_index].addend; + physaddr = addr + env_tlb(env)->f[mmu_idx].table[page_index].addend; res = glue(glue(ld, USUFFIX), _p)((uint8_t *) physaddr); #endif @@ -214,7 +214,7 @@ static SMHINLINE int glue(glue(glue(CPU_PREFIX, lds), SUFFIX), MEMSUFFIX)(CPUArc #endif mmu_idx = CPU_MMU_INDEX; - tlb_entry = &env->tlb_table[mmu_idx].table[page_index]; + tlb_entry = &env_tlb(env)->f[mmu_idx].table[page_index]; tlb_addr = tlb_entry->ADDR_READ & ~TLB_MEM_TRACE; if (unlikely(tlb_addr != (addr & (TARGET_PAGE_MASK | (DATA_SIZE - 1))))) { res = (DATA_STYPE) glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(env, addr, mmu_idx, NULL); @@ -259,7 +259,7 @@ static SMHINLINE void glue(glue(glue(CPU_PREFIX, st), SUFFIX), MEMSUFFIX)(CPUArc #endif mmu_idx = CPU_MMU_INDEX; - tlb_entry = &env->tlb_table[mmu_idx].table[page_index]; + tlb_entry = &env_tlb(env)->f[mmu_idx].table[page_index]; tlb_addr = tlb_entry->addr_write & ~TLB_MEM_TRACE; if (unlikely(tlb_addr != (addr & (TARGET_PAGE_MASK | (DATA_SIZE - 1))))) { glue(glue(glue(HELPER_PREFIX, st), SUFFIX), MMUSUFFIX)(env, addr, v, mmu_idx, NULL); @@ -269,7 +269,7 @@ static SMHINLINE void glue(glue(glue(CPU_PREFIX, st), SUFFIX), MEMSUFFIX)(CPUArc physaddr = addr + tlb_entry->se_addend; glue(glue(st, SUFFIX), _p)((uint8_t *) physaddr, v); #else - physaddr = addr + env->tlb_table[mmu_idx].table[page_index].addend; + physaddr = addr + env_tlb(env)->f[mmu_idx].table[page_index].addend; glue(glue(st, SUFFIX), _p)((uint8_t *) physaddr, v); #endif diff --git a/libcpu/src/softmmu_template.h b/libcpu/src/softmmu_template.h index e0c645ebf..ff6641673 100644 --- a/libcpu/src/softmmu_template.h +++ b/libcpu/src/softmmu_template.h @@ -146,7 +146,7 @@ DATA_TYPE glue(glue(io_read, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_ } if (is_notdirty_ops(ops)) { - CPUTLBEntry *e = env->se_tlb_current; + CPUTLBEntry *e = env_cpu(env)->neg.se_tlb_current; if (likely(_se_check_concrete(e->objectState, addr & ~SE_RAM_OBJECT_MASK, DATA_SIZE))) { return glue(glue(ld, USUFFIX), _p)((uint8_t *) (addr + (e->se_addend))); } else if (!tcg_is_dyngen_addr(retaddr)) { @@ -275,16 +275,16 @@ glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(CPUArchState *env, target #endif redo: - tlb_entry = &env->tlb_table[mmu_idx].table[index]; + tlb_entry = &env_tlb(env)->f[mmu_idx].table[index]; tlb_addr = tlb_entry->ADDR_READ & ~TLB_MEM_TRACE; if (likely((addr & TARGET_PAGE_MASK) == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK)))) { if (unlikely(tlb_addr & ~TARGET_PAGE_MASK)) { /* IO access */ if ((addr & (DATA_SIZE - 1)) != 0) goto do_unaligned_access; - ioaddr = env->iotlb[mmu_idx][index]; + ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; #ifdef CONFIG_SYMBEX - env->se_tlb_current = tlb_entry; + env_cpu(env)->neg.se_tlb_current = tlb_entry; #endif res = glue(glue(io_read_chk, SUFFIX), MMUSUFFIX)(env, ioaddr, addr, retaddr); @@ -347,7 +347,7 @@ static DATA_TYPE glue(glue(slow_ld, SUFFIX), MMUSUFFIX)(CPUArchState *env, targe object_index = INSTR_FORK_AND_CONCRETIZE(addr >> SE_RAM_OBJECT_BITS, ADDR_MAX >> SE_RAM_OBJECT_BITS); index = (object_index >> SE_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); redo: - tlb_entry = &env->tlb_table[mmu_idx].table[index]; + tlb_entry = &env_tlb(env)->f[mmu_idx].table[index]; tlb_addr = tlb_entry->ADDR_READ & ~TLB_MEM_TRACE; if ((addr & TARGET_PAGE_MASK) == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) { @@ -355,10 +355,10 @@ static DATA_TYPE glue(glue(slow_ld, SUFFIX), MMUSUFFIX)(CPUArchState *env, targe /* IO access */ if ((addr & (DATA_SIZE - 1)) != 0) goto do_unaligned_access; - ioaddr = env->iotlb[mmu_idx][index]; + ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; #ifdef CONFIG_SYMBEX - env->se_tlb_current = tlb_entry; + env_cpu(env)->neg.se_tlb_current = tlb_entry; #endif res = glue(glue(io_read_chk, SUFFIX), MMUSUFFIX)(env, ioaddr, addr, retaddr); @@ -425,7 +425,7 @@ void glue(glue(io_write, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr } if (unlikely(is_notdirty_ops(ops))) { - CPUTLBEntry *e = env->se_tlb_current; + CPUTLBEntry *e = env_cpu(env)->neg.se_tlb_current; if (!(e->addr_write & (TLB_NOT_OURS | TLB_NOTDIRTY))) { if (likely(_se_check_concrete(e->objectState, addr & ~SE_RAM_OBJECT_MASK, DATA_SIZE))) { glue(glue(st, SUFFIX), _p)((uint8_t *) (addr + (e->se_addend)), val); @@ -527,7 +527,7 @@ void glue(glue(glue(HELPER_PREFIX, st), SUFFIX), MMUSUFFIX)(CPUArchState *env, t #endif redo: - tlb_entry = &env->tlb_table[mmu_idx].table[index]; + tlb_entry = &env_tlb(env)->f[mmu_idx].table[index]; tlb_addr = tlb_entry->addr_write & ~TLB_MEM_TRACE; if (likely((addr & TARGET_PAGE_MASK) == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK)))) { @@ -536,10 +536,10 @@ void glue(glue(glue(HELPER_PREFIX, st), SUFFIX), MMUSUFFIX)(CPUArchState *env, t if ((addr & (DATA_SIZE - 1)) != 0) goto do_unaligned_access; - ioaddr = env->iotlb[mmu_idx][index]; + ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; #ifdef CONFIG_SYMBEX - env->se_tlb_current = tlb_entry; + env_cpu(env)->neg.se_tlb_current = tlb_entry; #endif glue(glue(io_write_chk, SUFFIX), MMUSUFFIX)(env, ioaddr, val, addr, retaddr); @@ -594,7 +594,7 @@ static void glue(glue(slow_st, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulo object_index = INSTR_FORK_AND_CONCRETIZE(addr >> SE_RAM_OBJECT_BITS, ADDR_MAX >> SE_RAM_OBJECT_BITS); index = (object_index >> SE_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); redo: - tlb_entry = &env->tlb_table[mmu_idx].table[index]; + tlb_entry = &env_tlb(env)->f[mmu_idx].table[index]; tlb_addr = tlb_entry->addr_write & ~TLB_MEM_TRACE; ; if ((addr & TARGET_PAGE_MASK) == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) { @@ -602,9 +602,9 @@ static void glue(glue(slow_st, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulo /* IO access */ if ((addr & (DATA_SIZE - 1)) != 0) goto do_unaligned_access; - ioaddr = env->iotlb[mmu_idx][index]; + ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; #ifdef CONFIG_SYMBEX - env->se_tlb_current = tlb_entry; + env_cpu(env)->neg.se_tlb_current = tlb_entry; #endif glue(glue(io_write_chk, SUFFIX), MMUSUFFIX)(env, ioaddr, val, addr, retaddr); diff --git a/libcpu/src/target-i386/helper.c b/libcpu/src/target-i386/helper.c index 7758984e8..a3525d9bd 100644 --- a/libcpu/src/target-i386/helper.c +++ b/libcpu/src/target-i386/helper.c @@ -1078,7 +1078,10 @@ CPUX86State *cpu_x86_init(const cpuid_t *cpuid) { CPUX86State *env; static int inited; - env = g_malloc0(sizeof(CPUX86State)); + /* The env must be embedded in an ArchCPU so that the caches in CPUState + are reachable at negative offsets from it; see cpu/state.h. */ + ArchCPU *cpu = g_malloc0(sizeof(ArchCPU)); + env = &cpu->env; cpu_exec_init(env); /* init various static tables used in TCG mode */ diff --git a/libcpu/src/translate-all.c b/libcpu/src/translate-all.c index b44449d44..4f13bb4b0 100644 --- a/libcpu/src/translate-all.c +++ b/libcpu/src/translate-all.c @@ -169,8 +169,7 @@ int cpu_gen_code(CPUArchState *env, TranslationBlock *tb) { tcg_ctx->page_bits = TARGET_PAGE_BITS; tcg_ctx->page_mask = TARGET_PAGE_MASK; tcg_ctx->tlb_dyn_max_bits = CPU_TLB_DYN_MAX_BITS; - tcg_ctx->tlb_fast_offset = - offsetof(CPUX86State, tlb_table); // (int) offsetof(ArchCPU, neg.tlb.f) - (int) offsetof(ArchCPU, env); + tcg_ctx->tlb_fast_offset = (int) offsetof(ArchCPU, parent_obj.neg.tlb.f) - (int) offsetof(ArchCPU, env); #endif #ifdef TCG_GUEST_DEFAULT_MO tcg_ctx->guest_mo = TCG_GUEST_DEFAULT_MO; diff --git a/libs2ecore/include/s2e/S2EExecutionStateRegisters.h b/libs2ecore/include/s2e/S2EExecutionStateRegisters.h index 26fe7b014..ef7f143da 100644 --- a/libs2ecore/include/s2e/S2EExecutionStateRegisters.h +++ b/libs2ecore/include/s2e/S2EExecutionStateRegisters.h @@ -33,6 +33,7 @@ extern "C" { struct CPUX86State; +struct CPUState; } #define CPU_OFFSET(field) offsetof(CPUX86State, field) @@ -60,8 +61,13 @@ class S2EExecutionStateRegisters { static klee::ObjectKey s_symbolicRegs; static klee::ObjectKey s_concreteRegs; + // The CPU caches (TLB, RAM TLB, TB jump cache), i.e., the CPUState part + // of the global ArchCPU that precedes CPUX86State (see cpu/state.h) + static klee::ObjectKey s_cpuCaches; + klee::ObjectStatePtr m_symbolicRegs; klee::ObjectStatePtr m_concreteRegs; + klee::ObjectStatePtr m_cpuCaches; const bool *m_active; const bool *m_runningConcrete; @@ -101,7 +107,7 @@ class S2EExecutionStateRegisters { m_concretizer(concretizer) {}; void initialize(klee::AddressSpace &addressSpace, const klee::ObjectStatePtr &symbolicRegs, - const klee::ObjectStatePtr &concreteRegs); + const klee::ObjectStatePtr &concreteRegs, const klee::ObjectStatePtr &cpuCaches); void update(klee::AddressSpace &addressSpace, const bool *active, const bool *running_concrete, klee::IAddressSpaceNotification *notification, klee::IConcretizer *concretizer); @@ -112,10 +118,12 @@ class S2EExecutionStateRegisters { inline void saveConcreteState() { memcpy((void *) m_concreteRegs->getConcreteBuffer(), (void *) s_concreteRegs.address, s_concreteRegs.size); + memcpy((void *) m_cpuCaches->getConcreteBuffer(), (void *) s_cpuCaches.address, s_cpuCaches.size); } inline void restoreConcreteState() { memcpy((void *) s_concreteRegs.address, (void *) m_concreteRegs->getConcreteBuffer(), s_concreteRegs.size); + memcpy((void *) s_cpuCaches.address, (void *) m_cpuCaches->getConcreteBuffer(), s_cpuCaches.size); } bool addressSpaceChange(const klee::ObjectKey &key, const klee::ObjectStateConstPtr &oldState, @@ -125,6 +133,10 @@ class S2EExecutionStateRegisters { return s_concreteRegs; } + static const klee::ObjectKey &getCpuCachesKey() { + return s_cpuCaches; + } + void dump(std::ostream &ss) const; /// Returns a pointer to the store where the concrete @@ -133,6 +145,11 @@ class S2EExecutionStateRegisters { /// the global CPUState object if active. CPUX86State *getCpuState() const; + /// Returns a pointer to the store holding the CPU caches (the CPUState + /// part of ArchCPU): the global object if the state is active, the + /// snapshot buffer otherwise. + CPUState *getCpuCaches() const; + bool allConcrete() const { return m_symbolicRegs->isAllConcrete(); } diff --git a/libs2ecore/include/s2e/S2EExecutionStateTlb.h b/libs2ecore/include/s2e/S2EExecutionStateTlb.h index af77b9952..e6a69b40c 100644 --- a/libs2ecore/include/s2e/S2EExecutionStateTlb.h +++ b/libs2ecore/include/s2e/S2EExecutionStateTlb.h @@ -73,7 +73,7 @@ class S2EExecutionStateTlb { void flushTlbCachePage(const klee::ObjectStatePtr &objectState, int mmu_idx, int index); - void updateTlbEntryConcreteStatus(struct CPUX86State *env, unsigned mmu_idx, unsigned index, + void updateTlbEntryConcreteStatus(struct CPUState *cpu, unsigned mmu_idx, unsigned index, const klee::ObjectStateConstPtr &state); #if defined(SE_ENABLE_PHYSRAM_TLB) diff --git a/libs2ecore/src/ExprInterface.cpp b/libs2ecore/src/ExprInterface.cpp index d0fd59672..ddeab218a 100644 --- a/libs2ecore/src/ExprInterface.cpp +++ b/libs2ecore/src/ExprInterface.cpp @@ -184,14 +184,14 @@ template static inline bool s2e_fast_read_mem(uint64_t addr, T *res page_index = object_index & (CPU_TLB_SIZE - 1); mmu_idx = cpu_mmu_index(env); - CPUTLBEntry *tlb_entry = &env->tlb_table[mmu_idx].table[page_index]; - if (unlikely(env->tlb_table[mmu_idx].table[page_index].addr_read != + CPUTLBEntry *tlb_entry = &env_tlb(env)->f[mmu_idx].table[page_index]; + if (unlikely(env_tlb(env)->f[mmu_idx].table[page_index].addr_read != (addr & (TARGET_PAGE_MASK | (sizeof(*res) - 1))))) { return false; } else { // When we get here, the address is aligned with the size of the access, // which by definition means that it will fall inside the small page, without overflowing. - // physaddr = addr + env->tlb_table[mmu_idx][page_index].addend; + // physaddr = addr + env_tlb(env)->f[mmu_idx][page_index].addend; #ifdef CONFIG_SYMBEX_MP uint64_t addend = tlb_entry->se_addend; diff --git a/libs2ecore/src/MMUFunctionHandlers.cpp b/libs2ecore/src/MMUFunctionHandlers.cpp index 2af659134..48e6a4829 100644 --- a/libs2ecore/src/MMUFunctionHandlers.cpp +++ b/libs2ecore/src/MMUFunctionHandlers.cpp @@ -233,7 +233,7 @@ static ref handle_ldst_mmu(Executor *executor, ExecutionState *state, klee redo: - const auto &tlbEntry = env->tlb_table[mmu_idx].table[index]; + const auto &tlbEntry = env_tlb(env)->f[mmu_idx].table[index]; if (isWrite) { tlb_addr = tlbEntry.addr_write & ~TLB_MEM_TRACE; @@ -248,7 +248,7 @@ static ref handle_ldst_mmu(Executor *executor, ExecutionState *state, klee goto do_unaligned_access; } - ioaddr = env->iotlb[mmu_idx][index]; + ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; if (!isWrite) { value = io_read_chk(s2estate, tlbEntry, ioaddr, addr, retaddr, width); @@ -458,7 +458,7 @@ static void handle_ldst_kernel(Executor *executor, ExecutionState *state, klee:: page_index = (object_index >> S2E_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); ////////////////////////////////////////// - const auto &tlbEntry = env->tlb_table[mmu_idx].table[page_index]; + const auto &tlbEntry = env_tlb(env)->f[mmu_idx].table[page_index]; if (isWrite) { value = args[2]; diff --git a/libs2ecore/src/S2EExecutionState.cpp b/libs2ecore/src/S2EExecutionState.cpp index 13fa38c91..4782b6bf8 100644 --- a/libs2ecore/src/S2EExecutionState.cpp +++ b/libs2ecore/src/S2EExecutionState.cpp @@ -835,8 +835,8 @@ void se_write_dirty_mask(uint64_t host_address, uint8_t val) { static inline CPUTLBRAMEntry *s2e_get_ram_tlb_entry(uint64_t host_address) { #if defined(SE_ENABLE_PHYSRAM_TLB) uintptr_t tlb_index = (host_address >> 12) & (CPU_TLB_SIZE - 1); - CPUX86State *env = g_s2e_state->regs()->getCpuState(); - return &env->se_ram_tlb[tlb_index]; + CPUState *cpu = g_s2e_state->regs()->getCpuCaches(); + return &cpu->neg.se_ram_tlb[tlb_index]; #else return nullptr; #endif diff --git a/libs2ecore/src/S2EExecutionStateRegisters.cpp b/libs2ecore/src/S2EExecutionStateRegisters.cpp index 4e3027a87..d6a1a7a8f 100644 --- a/libs2ecore/src/S2EExecutionStateRegisters.cpp +++ b/libs2ecore/src/S2EExecutionStateRegisters.cpp @@ -43,15 +43,19 @@ using namespace klee; ObjectKey S2EExecutionStateRegisters::s_concreteRegs; ObjectKey S2EExecutionStateRegisters::s_symbolicRegs; +ObjectKey S2EExecutionStateRegisters::s_cpuCaches; void S2EExecutionStateRegisters::initialize(klee::AddressSpace &addressSpace, const klee::ObjectStatePtr &symbolicRegs, - const klee::ObjectStatePtr &concreteRegs) { - assert(!s_concreteRegs.address && !s_symbolicRegs.address); + const klee::ObjectStatePtr &concreteRegs, + const klee::ObjectStatePtr &cpuCaches) { + assert(!s_concreteRegs.address && !s_symbolicRegs.address && !s_cpuCaches.address); s_concreteRegs = concreteRegs->getKey(); s_symbolicRegs = symbolicRegs->getKey(); + s_cpuCaches = cpuCaches->getKey(); symbolicRegs->setName("SymbolicCpuRegisters"); concreteRegs->setName("ConcreteCpuRegisters"); + cpuCaches->setName("CpuCaches"); /* The fast path in the cpu loop relies on this */ symbolicRegs->setNotifyOnConcretenessChange(true); @@ -64,9 +68,11 @@ void S2EExecutionStateRegisters::update(klee::AddressSpace &addressSpace, const klee::IConcretizer *concretizer) { auto concreteState = addressSpace.findObject(s_concreteRegs.address); auto symbolicState = addressSpace.findObject(s_symbolicRegs.address); + auto cachesState = addressSpace.findObject(s_cpuCaches.address); m_symbolicRegs = addressSpace.getWriteable(symbolicState); m_concreteRegs = addressSpace.getWriteable(concreteState); + m_cpuCaches = addressSpace.getWriteable(cachesState); if (active && running_concrete) { m_runningConcrete = running_concrete; @@ -100,6 +106,10 @@ CPUX86State *S2EExecutionStateRegisters::getCpuState() const { return cpu; } +CPUState *S2EExecutionStateRegisters::getCpuCaches() const { + return *m_active ? (CPUState *) s_cpuCaches.address : (CPUState *) m_cpuCaches->getConcreteBuffer(true); +} + bool S2EExecutionStateRegisters::addressSpaceChange(const klee::ObjectKey &key, const klee::ObjectStateConstPtr &oldState, const klee::ObjectStatePtr &newState) { @@ -115,6 +125,10 @@ bool S2EExecutionStateRegisters::addressSpaceChange(const klee::ObjectKey &key, m_symbolicRegs = newState; assert(newState); return true; + } else if (key == s_cpuCaches) { + m_cpuCaches = newState; + assert(newState); + return true; } else { return false; } diff --git a/libs2ecore/src/S2EExecutionStateTlb.cpp b/libs2ecore/src/S2EExecutionStateTlb.cpp index b41c1b2b9..f3c252d3b 100644 --- a/libs2ecore/src/S2EExecutionStateTlb.cpp +++ b/libs2ecore/src/S2EExecutionStateTlb.cpp @@ -87,9 +87,9 @@ bool S2EExecutionStateTlb::addressSpaceChangeUpdateTlb(const klee::ObjectStateCo #if defined(SE_ENABLE_PHYSRAM_TLB) void S2EExecutionStateTlb::updateRamTlb(const klee::ObjectStateConstPtr &oldState, const klee::ObjectStatePtr &newState) { - CPUX86State *cpu = m_registers->getCpuState(); + CPUState *cpu = m_registers->getCpuCaches(); uintptr_t tlb_index = (oldState->getAddress() >> 12) & (CPU_TLB_SIZE - 1); - CPUTLBRAMEntry *re = &cpu->se_ram_tlb[tlb_index]; + CPUTLBRAMEntry *re = &cpu->neg.se_ram_tlb[tlb_index]; assert(oldState->isSharedConcrete() == newState->isSharedConcrete()); @@ -112,7 +112,7 @@ void S2EExecutionStateTlb::updateRamTlb(const klee::ObjectStateConstPtr &oldStat void S2EExecutionStateTlb::updateTlb(const klee::ObjectStateConstPtr &oldState, const klee::ObjectStatePtr &newState) { - CPUX86State *cpu = m_registers->getCpuState(); + CPUState *cpu = m_registers->getCpuCaches(); if (g_s2e_single_path_mode) { llvm::errs() << "Multi-path mode disabled.\n"; @@ -137,7 +137,7 @@ void S2EExecutionStateTlb::updateTlb(const klee::ObjectStateConstPtr &oldState, #ifdef S2E_DEBUG_TLBCACHE g_s2e->getDebugStream() << " mmu_idx=" << coords.first << " index=" << coords.second << "\n"; #endif - CPUTLBEntry *entry = &cpu->tlb_table[coords.first].table[coords.second]; + CPUTLBEntry *entry = &cpu->neg.tlb.f[coords.first].table[coords.second]; assert(entry->objectState == (void *) oldState.get()); assert(newState); @@ -187,8 +187,9 @@ void S2EExecutionStateTlb::flushTlbCachePage(const klee::ObjectStatePtr &objectS << "flushTlbCachePage: clearing cache entry for " << objectState << " (" << mmu_idx << "," << index << ")\n"; #endif - env->tlb_table[mmu_idx].table[index].objectState = 0; - env->tlb_table[mmu_idx].table[index].se_addend = 0; + CPUTLBEntry *entry = &m_registers->getCpuCaches()->neg.tlb.f[mmu_idx].table[index]; + entry->objectState = 0; + entry->se_addend = 0; if (g_s2e_single_path_mode) { return; @@ -224,9 +225,9 @@ void S2EExecutionStateTlb::flushTlbCachePage(const klee::ObjectStatePtr &objectS * If a page contains at least one byte of symbolic data, it will go through * the slow path. Otherwise, softmmu will directly access the concrete array. */ -void S2EExecutionStateTlb::updateTlbEntryConcreteStatus(struct CPUX86State *env, unsigned mmu_idx, unsigned index, +void S2EExecutionStateTlb::updateTlbEntryConcreteStatus(struct CPUState *cpu, unsigned mmu_idx, unsigned index, const klee::ObjectStateConstPtr &state) { - CPUTLBEntry *te = &env->tlb_table[mmu_idx].table[index]; + CPUTLBEntry *te = &cpu->neg.tlb.f[mmu_idx].table[index]; if (!state->isAllConcrete()) { te->addr_read |= TLB_SYMB; @@ -240,7 +241,7 @@ void S2EExecutionStateTlb::updateTlbEntryConcreteStatus(struct CPUX86State *env, #ifdef SE_ENABLE_PHYSRAM_TLB uintptr_t ram_tlb_index = (state->getAddress() >> 12) & (CPU_TLB_SIZE - 1); - CPUTLBRAMEntry *re = &env->se_ram_tlb[ram_tlb_index]; + CPUTLBRAMEntry *re = &cpu->neg.se_ram_tlb[ram_tlb_index]; re->host_page = 0; re->addend = 0; re->object_state = 0; @@ -250,18 +251,19 @@ void S2EExecutionStateTlb::updateTlbEntryConcreteStatus(struct CPUX86State *env, #if defined(SE_ENABLE_PHYSRAM_TLB) void S2EExecutionStateTlb::clearRamTlb() { static CPUTLBRAMEntry empty = {0, 0, nullptr}; + CPUState *cpu = m_registers->getCpuCaches(); for (unsigned i = 0; i < CPU_TLB_SIZE; i++) { - env->se_ram_tlb[i] = empty; + cpu->neg.se_ram_tlb[i] = empty; } } #endif void S2EExecutionStateTlb::clearTlbOwnership() { - CPUX86State *env = m_registers->getCpuState(); + CPUState *cpu = m_registers->getCpuCaches(); for (unsigned i = 0; i < CPU_TLB_SIZE; i++) { for (unsigned mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - env->tlb_table[mmu_idx].table[i].addr_write |= TLB_NOT_OURS; + cpu->neg.tlb.f[mmu_idx].table[i].addr_write |= TLB_NOT_OURS; } } } @@ -272,7 +274,7 @@ void S2EExecutionStateTlb::updateTlbEntry(CPUX86State *env, int mmu_idx, uint64_ unsigned int index = (virtAddr >> SE_RAM_OBJECT_BITS) & (CPU_TLB_SIZE - 1); - CPUTLBEntry *entry = &env->tlb_table[mmu_idx].table[index]; + CPUTLBEntry *entry = &env_cpu(env)->neg.tlb.f[mmu_idx].table[index]; ObjectState *oldObjectState = static_cast(entry->objectState); /* Retrieve the object state using the host address */ @@ -315,7 +317,7 @@ void S2EExecutionStateTlb::updateTlbEntry(CPUX86State *env, int mmu_idx, uint64_ } } - updateTlbEntryConcreteStatus(env, mmu_idx, index, newObjectState); + updateTlbEntryConcreteStatus(env_cpu(env), mmu_idx, index, newObjectState); #ifdef S2E_DEBUG_TLBCACHE audit(); @@ -327,7 +329,7 @@ bool S2EExecutionStateTlb::audit() { * Go through the TLB and make sure that all object states are * properly referenced. */ - CPUX86State *env = m_registers->getCpuState(); + CPUState *cpu = m_registers->getCpuCaches(); for (auto tlbIt : m_tlbMap) { auto os = tlbIt.first; @@ -336,7 +338,7 @@ bool S2EExecutionStateTlb::audit() { unsigned mmu_idx = (*vit).first; unsigned index = (*vit).second; - CPUTLBEntry *entry = &env->tlb_table[mmu_idx].table[index]; + CPUTLBEntry *entry = &cpu->neg.tlb.f[mmu_idx].table[index]; assert(entry->objectState == os); (void) entry; (void) os; @@ -345,7 +347,7 @@ bool S2EExecutionStateTlb::audit() { for (unsigned i = 0; i < CPU_TLB_SIZE; i++) { for (unsigned mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - CPUTLBEntry *entry = &env->tlb_table[mmu_idx].table[i]; + CPUTLBEntry *entry = &cpu->neg.tlb.f[mmu_idx].table[i]; if (!entry->objectState) { continue; } diff --git a/libs2ecore/src/S2EExecutor.cpp b/libs2ecore/src/S2EExecutor.cpp index dd4669a1c..be66d9a0d 100644 --- a/libs2ecore/src/S2EExecutor.cpp +++ b/libs2ecore/src/S2EExecutor.cpp @@ -543,8 +543,16 @@ void S2EExecutor::registerCpu(S2EExecutionState *initialState, CPUX86State *cpuE /* isReadOnly = */ false, /* isSharedConcrete = */ true); - initialState->m_registers.initialize(initialState->addressSpace(), symbolicRegs, concreteRegs); + /* Add the CPU caches (TLB, RAM TLB, TB jump cache) that precede the env + inside ArchCPU. The softmmu fast path runs as bitcode inside KLEE and + reads the TLB through this object. See cpu/state.h. */ + auto cpuCaches = initialState->addExternalObject(env_cpu(cpuEnv), offsetof(ArchCPU, env), + /* isReadOnly = */ false, + /* isSharedConcrete = */ true); + + initialState->m_registers.initialize(initialState->addressSpace(), symbolicRegs, concreteRegs, cpuCaches); klee::ExecutionState::s_ignoredMergeObjects.insert(initialState->m_registers.getConcreteRegs()); + klee::ExecutionState::s_ignoredMergeObjects.insert(initialState->m_registers.getCpuCachesKey()); } void S2EExecutor::registerSharedExternalObject(S2EExecutionState *state, void *address, unsigned size) { From 8e52db4e4daaf11545ee9b92108aba6e7e2c1c10 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Thu, 3 Sep 2026 23:01:29 +0200 Subject: [PATCH 24/52] libcpu: dropped the performance measurements from the tlb plan Co-Authored-By: Claude Fable 5.1 --- libcpu/tlb-update.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/libcpu/tlb-update.md b/libcpu/tlb-update.md index ef00677b6..5b844a515 100644 --- a/libcpu/tlb-update.md +++ b/libcpu/tlb-update.md @@ -120,8 +120,7 @@ behavior. ### Step 0: Baseline and harness (half a day) -- Record testsuite results, and two numbers to compare against later: - `doStateSwitch()` wall time, and resident memory at a fixed state count. +- Record testsuite results. - Promote `audit()` from the `S2E_DEBUG_TLBCACHE` compile-time switch to a runtime flag (`--tlb-audit`) so it can be turned on for a whole suite run. @@ -211,9 +210,7 @@ This step changes behavior; the earlier ones do not. hoisting it to the executor and gives the same guarantee; hoist later if it reads better. -Exit: testsuite green; the two step-0 numbers re-measured. Expect -`doStateSwitch()` to get *faster* (the memcpy drops by ~216 KB) and per-state -memory to drop by the same amount. +Exit: testsuite green. ### Step 5: Test the assumption directly (1 day) From 6bbcc738ad8a0e6b992f7218f0a7332d8134e7d0 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Thu, 3 Sep 2026 23:01:29 +0200 Subject: [PATCH 25/52] libs2ecore: promoted the tlb cache audit to a runtime flag The audit ran only when S2E_DEBUG_TLBCACHE was defined at compile time and relied on asserts. It is now enabled with --tlb-audit, runs after every TLB update, and reports the mismatching coordinates and object pointers before aborting. The checks are plain conditionals, so they are not compiled out with NDEBUG, and the loops use range-based for instead of foreach2. Co-Authored-By: Claude Fable 5.1 --- libs2ecore/src/S2EExecutionStateTlb.cpp | 63 +++++++++++++------------ 1 file changed, 34 insertions(+), 29 deletions(-) diff --git a/libs2ecore/src/S2EExecutionStateTlb.cpp b/libs2ecore/src/S2EExecutionStateTlb.cpp index f3c252d3b..6f26d0c49 100644 --- a/libs2ecore/src/S2EExecutionStateTlb.cpp +++ b/libs2ecore/src/S2EExecutionStateTlb.cpp @@ -39,11 +39,13 @@ #undef cat #endif -#include -#include - extern llvm::cl::opt PrintModeSwitch; +namespace { +llvm::cl::opt TlbAudit("tlb-audit", llvm::cl::desc("Check the TLB cache map against the TLB after every update"), + llvm::cl::init(false)); +} + namespace s2e { using namespace klee; @@ -163,9 +165,9 @@ void S2EExecutionStateTlb::updateTlb(const klee::ObjectStateConstPtr &oldState, } } -#ifdef S2E_DEBUG_TLBCACHE - audit(); -#endif + if (TlbAudit && !audit()) { + pabort("TLB cache audit failed"); + } } /***/ @@ -319,9 +321,9 @@ void S2EExecutionStateTlb::updateTlbEntry(CPUX86State *env, int mmu_idx, uint64_ updateTlbEntryConcreteStatus(env_cpu(env), mmu_idx, index, newObjectState); -#ifdef S2E_DEBUG_TLBCACHE - audit(); -#endif + if (TlbAudit && !audit()) { + pabort("TLB cache audit failed"); + } } bool S2EExecutionStateTlb::audit() { @@ -331,39 +333,42 @@ bool S2EExecutionStateTlb::audit() { */ CPUState *cpu = m_registers->getCpuCaches(); - for (auto tlbIt : m_tlbMap) { - auto os = tlbIt.first; - const ObjectStateTlbReferences &vec = tlbIt.second; - foreach2 (vit, vec.begin(), vec.end()) { - unsigned mmu_idx = (*vit).first; - unsigned index = (*vit).second; - - CPUTLBEntry *entry = &cpu->neg.tlb.f[mmu_idx].table[index]; - assert(entry->objectState == os); - (void) entry; - (void) os; + for (const auto &[os, refs] : m_tlbMap) { + for (const auto &[mmu_idx, index] : refs) { + const CPUTLBEntry *entry = &cpu->neg.tlb.f[mmu_idx].table[index]; + if (entry->objectState != os.get()) { + llvm::errs() << "TLB audit: map entry (" << mmu_idx << "," << index << ") refers to " + << hexval(os.get()) << " but the TLB holds " << hexval(entry->objectState) << "\n"; + return false; + } } } - for (unsigned i = 0; i < CPU_TLB_SIZE; i++) { - for (unsigned mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - CPUTLBEntry *entry = &cpu->neg.tlb.f[mmu_idx].table[i]; + for (unsigned mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { + for (unsigned index = 0; index < CPU_TLB_SIZE; index++) { + const CPUTLBEntry *entry = &cpu->neg.tlb.f[mmu_idx].table[index]; if (!entry->objectState) { continue; } - TlbMap::const_iterator it = m_tlbMap.find((ObjectState *) entry->objectState); - assert(it != m_tlbMap.end()); + auto it = m_tlbMap.find(static_cast(entry->objectState)); + if (it == m_tlbMap.end()) { + llvm::errs() << "TLB audit: TLB entry (" << mmu_idx << "," << index << ") refers to " + << hexval(entry->objectState) << " which is not in the map\n"; + return false; + } - const ObjectStateTlbReferences &vec = (*it).second; unsigned foundCount = 0; - foreach2 (vit, vec.begin(), vec.end()) { - if ((*vit).first == mmu_idx && (*vit).second == i) { + for (const auto &coords : it->second) { + if (coords == TlbCoordinates(mmu_idx, index)) { foundCount++; } } + if (foundCount != 1) { - abort(); + llvm::errs() << "TLB audit: TLB entry (" << mmu_idx << "," << index << ") is referenced " << foundCount + << " times by " << hexval(entry->objectState) << "\n"; + return false; } } } From 0164b5a9bf13d543339ef6c4449fb5546c220a26 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Thu, 3 Sep 2026 23:36:05 +0200 Subject: [PATCH 26/52] libs2ecore: routed every tlb method through the caches accessor updateTlbEntry() took the global env and updateTlbEntryConcreteStatus() took a CPUState pointer while the other TLB methods went through getCpuCaches(), so one update could index the global TLB and then clear the per-state buffer. Both now fetch the caches through the accessor, and updateTlbEntryConcreteStatus() is private since only the class calls it. The libcpu hook s2e_update_tlb_entry() keeps its env parameter and aborts when it does not name the active state's CPU, which is the only CPU libcpu fills TLB entries for (tlb-update.md, step 1). The plan records that step 4 turns getCpuCaches() into the place that enforces I3. Co-Authored-By: Claude Fable 5.1 --- libcpu/tlb-update.md | 8 +++++++- libs2ecore/include/s2e/S2EExecutionStateTlb.h | 11 +++-------- libs2ecore/src/S2EExecutionStateTlb.cpp | 11 ++++++----- libs2ecore/src/S2EExecutor.cpp | 7 ++++++- 4 files changed, 22 insertions(+), 15 deletions(-) diff --git a/libcpu/tlb-update.md b/libcpu/tlb-update.md index 5b844a515..92fa9c613 100644 --- a/libcpu/tlb-update.md +++ b/libcpu/tlb-update.md @@ -138,7 +138,10 @@ fixing them afterwards. `updateTlbEntryConcreteStatus()` take `env` as a parameter, with a latent mixed-accessor bug: `updateTlbEntry()` indexes its parameter, but the `flushTlbCachePage()` it calls clears the global. Route all of them through - one accessor, a three-way unification rather than a two-way one. + one accessor, a three-way unification rather than a two-way one. The libcpu + hook `s2e_update_tlb_entry()` keeps its `env` parameter, since that is + libcpu's interface, but only checks that it names the active state's CPU + and then calls the parameterless method. - **`addressSpaceChangeUpdateTlb()` can fire on an inactive state.** `AddressSpace::getWriteable()` notifies whichever state owns the address space. The merge path runs with `!m_active`, and, in the dominant case, any @@ -202,6 +205,9 @@ This step changes behavior; the earlier ones do not. - `addressSpaceChangeUpdateTlb()`: early-return when the state is not active. Sound, because an inactive state has no TLB; it gets one when it is activated. +- `getCpuCaches()`: drop the per-state buffer branch. It aborts when the state + is not active and otherwise returns the global region, so every TLB method + enforces I3 through the one accessor step 1 routed them through. - Assert `m_tlbMap.empty()` whenever `!m_active`. This needs one edit first: `S2EExecutionState`'s copy constructor does `m_tlb = state.m_tlb`, handing every forked child the parent's populated map, so `clone()` must clear the diff --git a/libs2ecore/include/s2e/S2EExecutionStateTlb.h b/libs2ecore/include/s2e/S2EExecutionStateTlb.h index e6a69b40c..69b463a39 100644 --- a/libs2ecore/include/s2e/S2EExecutionStateTlb.h +++ b/libs2ecore/include/s2e/S2EExecutionStateTlb.h @@ -31,10 +31,6 @@ #include "AddressSpaceCache.h" #include "S2EExecutionStateRegisters.h" -extern "C" { -struct CPUX86State; -} - namespace s2e { class S2EExecutionStateTlb { @@ -54,6 +50,8 @@ class S2EExecutionStateTlb { void updateRamTlb(const klee::ObjectStateConstPtr &oldState, const klee::ObjectStatePtr &newState); #endif + void updateTlbEntryConcreteStatus(unsigned mmu_idx, unsigned index, const klee::ObjectStateConstPtr &state); + public: S2EExecutionStateTlb(AddressSpaceCache *ascache, S2EExecutionStateRegisters *regs) : m_asCache(ascache), m_registers(regs) { @@ -73,16 +71,13 @@ class S2EExecutionStateTlb { void flushTlbCachePage(const klee::ObjectStatePtr &objectState, int mmu_idx, int index); - void updateTlbEntryConcreteStatus(struct CPUState *cpu, unsigned mmu_idx, unsigned index, - const klee::ObjectStateConstPtr &state); - #if defined(SE_ENABLE_PHYSRAM_TLB) void clearRamTlb(); #endif void clearTlbOwnership(); - void updateTlbEntry(struct CPUX86State *env, int mmu_idx, uint64_t virtAddr, uint64_t hostAddr); + void updateTlbEntry(int mmu_idx, uint64_t virtAddr, uint64_t hostAddr); bool audit(); }; diff --git a/libs2ecore/src/S2EExecutionStateTlb.cpp b/libs2ecore/src/S2EExecutionStateTlb.cpp index 6f26d0c49..fe378b0cc 100644 --- a/libs2ecore/src/S2EExecutionStateTlb.cpp +++ b/libs2ecore/src/S2EExecutionStateTlb.cpp @@ -156,7 +156,7 @@ void S2EExecutionStateTlb::updateTlb(const klee::ObjectStateConstPtr &oldState, } } - updateTlbEntryConcreteStatus(cpu, coords.first, coords.second, newState); + updateTlbEntryConcreteStatus(coords.first, coords.second, newState); } m_tlbMap[newState] = vec; @@ -227,8 +227,9 @@ void S2EExecutionStateTlb::flushTlbCachePage(const klee::ObjectStatePtr &objectS * If a page contains at least one byte of symbolic data, it will go through * the slow path. Otherwise, softmmu will directly access the concrete array. */ -void S2EExecutionStateTlb::updateTlbEntryConcreteStatus(struct CPUState *cpu, unsigned mmu_idx, unsigned index, +void S2EExecutionStateTlb::updateTlbEntryConcreteStatus(unsigned mmu_idx, unsigned index, const klee::ObjectStateConstPtr &state) { + CPUState *cpu = m_registers->getCpuCaches(); CPUTLBEntry *te = &cpu->neg.tlb.f[mmu_idx].table[index]; if (!state->isAllConcrete()) { @@ -270,13 +271,13 @@ void S2EExecutionStateTlb::clearTlbOwnership() { } } -void S2EExecutionStateTlb::updateTlbEntry(CPUX86State *env, int mmu_idx, uint64_t virtAddr, uint64_t hostAddr) { +void S2EExecutionStateTlb::updateTlbEntry(int mmu_idx, uint64_t virtAddr, uint64_t hostAddr) { assert((hostAddr & ~TARGET_PAGE_MASK) == 0); assert((virtAddr & ~TARGET_PAGE_MASK) == 0); unsigned int index = (virtAddr >> SE_RAM_OBJECT_BITS) & (CPU_TLB_SIZE - 1); - CPUTLBEntry *entry = &env_cpu(env)->neg.tlb.f[mmu_idx].table[index]; + CPUTLBEntry *entry = &m_registers->getCpuCaches()->neg.tlb.f[mmu_idx].table[index]; ObjectState *oldObjectState = static_cast(entry->objectState); /* Retrieve the object state using the host address */ @@ -319,7 +320,7 @@ void S2EExecutionStateTlb::updateTlbEntry(CPUX86State *env, int mmu_idx, uint64_ } } - updateTlbEntryConcreteStatus(env_cpu(env), mmu_idx, index, newObjectState); + updateTlbEntryConcreteStatus(mmu_idx, index, newObjectState); if (TlbAudit && !audit()) { pabort("TLB cache audit failed"); diff --git a/libs2ecore/src/S2EExecutor.cpp b/libs2ecore/src/S2EExecutor.cpp index be66d9a0d..fb9ae834c 100644 --- a/libs2ecore/src/S2EExecutor.cpp +++ b/libs2ecore/src/S2EExecutor.cpp @@ -1786,7 +1786,12 @@ void se_flush_tlb_cache_page(void *objectState, int mmu_idx, int index) { /** Tlb cache helpers */ void s2e_update_tlb_entry(CPUX86State *env, int mmu_idx, uint64_t virtAddr, uint64_t hostAddr) { #if defined(SE_ENABLE_TLB) && defined(CONFIG_SYMBEX_MP) - g_s2e_state->getTlb()->updateTlbEntry(env, mmu_idx, virtAddr, hostAddr); + // libcpu fills TLB entries only for the CPU it is executing, which must be + // the active state's. The TLB code itself never takes a CPU pointer. + if (env_cpu(env) != g_s2e_state->regs()->getCpuCaches()) { + pabort("TLB entry update for a CPU that is not the active state's"); + } + g_s2e_state->getTlb()->updateTlbEntry(mmu_idx, virtAddr, hostAddr); #endif } From a3699794a1d4adb9d2bad53e2434e7c1abd3af02 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Thu, 3 Sep 2026 23:45:53 +0200 Subject: [PATCH 27/52] libs2ecore: stopped inactive states from updating the concrete fast path addressSpaceSymbolicStatusChange() called updateConcreteFastPath() for whichever state's registers changed concreteness. The fast path flag, generate_llvm and the clock scaling are globals that describe the active state, so a plugin making a suspended state's registers symbolic clobbered them until the next state switch. The call now runs only on the active state; selectSearcherState() recomputes the flags after every switch. The plan records the decision for the unguarded TLB entry points: the per-state address space cache invalidation always runs, and the TLB update becomes a checked no-op on inactive states in step 4, inside updateTlb() and updateRamTlb() (tlb-update.md, step 1). Co-Authored-By: Claude Fable 5.1 --- libcpu/tlb-update.md | 32 +++++++++++++++++++++++----- libs2ecore/src/S2EExecutionState.cpp | 9 ++++++-- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/libcpu/tlb-update.md b/libcpu/tlb-update.md index 92fa9c613..5b56953a3 100644 --- a/libcpu/tlb-update.md +++ b/libcpu/tlb-update.md @@ -148,8 +148,27 @@ fixing them afterwards. plugin write to guest memory of a *suspended* state (`S2EExecutionStateMemory::write()` has no `m_active` guard) lands here too. `addressSpaceSymbolicStatusChange()` and `addressSpaceObjectSplit()` are two - more unguarded entry points into `updateTlb()`. Decide the intended - behavior now and document it; step 4 makes all of them an early return. + more unguarded entry points into `updateTlb()`. + + Decision: each entry point does two kinds of work, and they split along + the active/inactive line. Invalidating the per-state `AddressSpaceCache` + (directly, or through `notifySplit()`) must run on every state, because a + suspended state whose object was replaced would otherwise hand back the + stale one when it next runs. The TLB update is only meaningful for the + active state, but today it must run on inactive states too: the snapshot + buffer holds object pointers that a copy-on-write in a suspended state has + to repoint, or the restored TLB dangles. So step 1 changes nothing on the + TLB path and step 4 adds the guard inside `updateTlb()` / `updateRamTlb()`, + below the cache invalidation, where it covers all three callers. + `S2EExecutionStateMemory::write()` stays unguarded: writing to a suspended + state is legitimate, and the notifications are the bookkeeping it needs. + + One part is a bug already: `addressSpaceSymbolicStatusChange()` calls + `updateConcreteFastPath()`, which writes globals describing the *active* + state (the fast-path flag, `generate_llvm`, the clock scaling), for + whichever state changed. A plugin that makes a suspended state's registers + symbolic clobbers the active state's flags until the next switch. Guard + that call with `m_active` in step 1; it is independent of the TLB. ### Step 2: Introduce `ArchCPU`, no ownership change (2-3 days) @@ -202,9 +221,12 @@ This step changes behavior; the earlier ones do not. always against the *active* state), `clearRamTlb()`, and an explicit `m_tlbMap.clear()` on the *outgoing* state, which the hook does not touch. Ordering matters, because `tlb_flush()` returns early while the guard is set. -- `addressSpaceChangeUpdateTlb()`: early-return when the state is not active. - Sound, because an inactive state has no TLB; it gets one when it is - activated. +- `updateTlb()` and `updateRamTlb()`: when the state is not active, check + that `m_tlbMap` is empty and return. Sound, because an inactive state has + no TLB; it gets one when it is activated. The guard sits below the + `AddressSpaceCache` invalidation in the three entry points (step 1 + decision), and `S2EExecutionStateTlb` receives the `m_active` pointer the + way `S2EExecutionStateMemory` does. - `getCpuCaches()`: drop the per-state buffer branch. It aborts when the state is not active and otherwise returns the global region, so every TLB method enforces I3 through the one accessor step 1 routed them through. diff --git a/libs2ecore/src/S2EExecutionState.cpp b/libs2ecore/src/S2EExecutionState.cpp index 4782b6bf8..07cd798f8 100644 --- a/libs2ecore/src/S2EExecutionState.cpp +++ b/libs2ecore/src/S2EExecutionState.cpp @@ -622,8 +622,13 @@ void S2EExecutionState::addressSpaceChange(const klee::ObjectKey &key, const kle } void S2EExecutionState::addressSpaceSymbolicStatusChange(const ObjectStatePtr &object, bool becameConcrete) { - // Deal with CPU registers - g_s2e->getExecutor()->updateConcreteFastPath(this); + // Deal with CPU registers. The fast path flags are globals that describe + // the active state, so a suspended state whose registers change (e.g., + // a plugin writing a symbolic value into them) must not touch them. + // selectSearcherState() recomputes them after switching to the state. + if (m_active) { + g_s2e->getExecutor()->updateConcreteFastPath(this); + } // Deal with RAM if (object->getBitArraySize() != SE_RAM_OBJECT_SIZE) { From 623aa0f1f9b9b0266d3e87eccaa92cb0a227a803 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Fri, 4 Sep 2026 00:29:55 +0200 Subject: [PATCH 28/52] libs2ecore: stopped snapshotting the CPU caches across state switches The TLB, the RAM TLB and the TB jump cache are caches of a mapping that the guest page tables and the KLEE address space determine, so they no longer travel with the state. saveConcreteState() and restoreConcreteState() leave the cache region alone, and doStateSwitch() flushes the TLB, clears the RAM TLB and empties the outgoing state's TLB map once the flush guard is cleared, so every activated state starts with an empty TLB. Only the active state has a TLB now. getCpuCaches() aborts on an inactive state, updateTlb() and updateRamTlb() return early on one after checking that its map is empty, and a forked state no longer inherits the parent's map. The per-state copy of the cache object is gone with the snapshot; the KLEE registration stays so that the bitcode softmmu fast path still resolves (tlb-update.md, step 4). Co-Authored-By: Claude Fable 5.1 --- libs2ecore/include/s2e/S2EExecutionState.h | 6 ++-- .../include/s2e/S2EExecutionStateRegisters.h | 14 ++++----- libs2ecore/include/s2e/S2EExecutionStateTlb.h | 14 +++++++-- libs2ecore/src/S2EExecutionState.cpp | 4 +-- libs2ecore/src/S2EExecutionStateRegisters.cpp | 11 ++++--- libs2ecore/src/S2EExecutionStateTlb.cpp | 20 +++++++++++-- libs2ecore/src/S2EExecutor.cpp | 30 +++++++++++++++++++ 7 files changed, 78 insertions(+), 21 deletions(-) diff --git a/libs2ecore/include/s2e/S2EExecutionState.h b/libs2ecore/include/s2e/S2EExecutionState.h index 920f9da64..b4910e595 100644 --- a/libs2ecore/include/s2e/S2EExecutionState.h +++ b/libs2ecore/include/s2e/S2EExecutionState.h @@ -176,7 +176,7 @@ class S2EExecutionState : public klee::ExecutionState, public klee::IConcretizer S2EExecutionState(const S2EExecutionState &state) : ExecutionState(state), m_pluginState(state.m_pluginState), m_toRunSymbolically(state.m_toRunSymbolically), m_deviceState(state.m_deviceState), m_asCache(state.m_asCache), m_registers(state.m_registers), - m_memory(state.m_memory), m_tlb(&m_asCache, &m_registers) { + m_memory(state.m_memory), m_tlb(&m_asCache, &m_registers, &m_active) { m_stateID = state.m_stateID; // To be updated in clone(). m_guid = state.m_guid; m_startSymbexAtPC = state.m_startSymbexAtPC; @@ -187,7 +187,9 @@ class S2EExecutionState : public klee::ExecutionState, public klee::IConcretizer m_pinned = state.m_pinned; m_isStateSwitchForbidden = state.m_isStateSwitchForbidden; - m_tlb = state.m_tlb; + // m_tlb is deliberately not copied. The fork logic deactivates the + // copy, and it has no TLB until doStateSwitch() activates it with a + // flushed one, so its map must start empty. m_timersState = state.m_timersState; m_lastS2ETb = state.m_lastS2ETb; diff --git a/libs2ecore/include/s2e/S2EExecutionStateRegisters.h b/libs2ecore/include/s2e/S2EExecutionStateRegisters.h index ef7f143da..03ee226b7 100644 --- a/libs2ecore/include/s2e/S2EExecutionStateRegisters.h +++ b/libs2ecore/include/s2e/S2EExecutionStateRegisters.h @@ -62,12 +62,14 @@ class S2EExecutionStateRegisters { static klee::ObjectKey s_concreteRegs; // The CPU caches (TLB, RAM TLB, TB jump cache), i.e., the CPUState part - // of the global ArchCPU that precedes CPUX86State (see cpu/state.h) + // of the global ArchCPU that precedes CPUX86State (see cpu/state.h). + // The region is registered so that the bitcode softmmu fast path can + // resolve it, but it is never snapshotted: the active state owns the + // global copy and doStateSwitch() flushes it on every switch. static klee::ObjectKey s_cpuCaches; klee::ObjectStatePtr m_symbolicRegs; klee::ObjectStatePtr m_concreteRegs; - klee::ObjectStatePtr m_cpuCaches; const bool *m_active; const bool *m_runningConcrete; @@ -118,12 +120,10 @@ class S2EExecutionStateRegisters { inline void saveConcreteState() { memcpy((void *) m_concreteRegs->getConcreteBuffer(), (void *) s_concreteRegs.address, s_concreteRegs.size); - memcpy((void *) m_cpuCaches->getConcreteBuffer(), (void *) s_cpuCaches.address, s_cpuCaches.size); } inline void restoreConcreteState() { memcpy((void *) s_concreteRegs.address, (void *) m_concreteRegs->getConcreteBuffer(), s_concreteRegs.size); - memcpy((void *) s_cpuCaches.address, (void *) m_cpuCaches->getConcreteBuffer(), s_cpuCaches.size); } bool addressSpaceChange(const klee::ObjectKey &key, const klee::ObjectStateConstPtr &oldState, @@ -145,9 +145,9 @@ class S2EExecutionStateRegisters { /// the global CPUState object if active. CPUX86State *getCpuState() const; - /// Returns a pointer to the store holding the CPU caches (the CPUState - /// part of ArchCPU): the global object if the state is active, the - /// snapshot buffer otherwise. + /// Returns a pointer to the global CPU caches (the CPUState part of + /// ArchCPU). Only the active state has a TLB, so this aborts when the + /// state is inactive. CPUState *getCpuCaches() const; bool allConcrete() const { diff --git a/libs2ecore/include/s2e/S2EExecutionStateTlb.h b/libs2ecore/include/s2e/S2EExecutionStateTlb.h index 69b463a39..32c1b9659 100644 --- a/libs2ecore/include/s2e/S2EExecutionStateTlb.h +++ b/libs2ecore/include/s2e/S2EExecutionStateTlb.h @@ -45,6 +45,7 @@ class S2EExecutionStateTlb { TlbMap m_tlbMap; AddressSpaceCache *m_asCache; S2EExecutionStateRegisters *m_registers; + const bool *m_active; #if defined(SE_ENABLE_PHYSRAM_TLB) void updateRamTlb(const klee::ObjectStateConstPtr &oldState, const klee::ObjectStatePtr &newState); @@ -53,13 +54,20 @@ class S2EExecutionStateTlb { void updateTlbEntryConcreteStatus(unsigned mmu_idx, unsigned index, const klee::ObjectStateConstPtr &state); public: - S2EExecutionStateTlb(AddressSpaceCache *ascache, S2EExecutionStateRegisters *regs) - : m_asCache(ascache), m_registers(regs) { + S2EExecutionStateTlb(AddressSpaceCache *ascache, S2EExecutionStateRegisters *regs, const bool *active) + : m_asCache(ascache), m_registers(regs), m_active(active) { } - void assignNewState(AddressSpaceCache *ascache, S2EExecutionStateRegisters *regs) { + void assignNewState(AddressSpaceCache *ascache, S2EExecutionStateRegisters *regs, const bool *active) { m_asCache = ascache; m_registers = regs; + m_active = active; + } + + /// True when no TLB entry refers to any object state. This must hold + /// whenever the state is inactive, since only the active state has a TLB. + bool isEmpty() const { + return m_tlbMap.empty(); } /* Change all entries that refer to oldState to newState */ diff --git a/libs2ecore/src/S2EExecutionState.cpp b/libs2ecore/src/S2EExecutionState.cpp index 07cd798f8..27c53edf7 100644 --- a/libs2ecore/src/S2EExecutionState.cpp +++ b/libs2ecore/src/S2EExecutionState.cpp @@ -78,7 +78,7 @@ S2EExecutionState::S2EExecutionState(klee::KFunction *kf) m_active(true), m_zombie(false), m_yielded(false), m_runningConcrete(true), m_pinned(false), m_isStateSwitchForbidden(false), m_asCache(&addressSpace()), m_registers(&m_active, &m_runningConcrete, this, this), m_memory(), m_lastS2ETb(nullptr), - m_needFinalizeTBExec(false), m_forkAborted(false), m_nextSymbVarId(0), m_tlb(&m_asCache, &m_registers), + m_needFinalizeTBExec(false), m_forkAborted(false), m_nextSymbVarId(0), m_tlb(&m_asCache, &m_registers, &m_active), m_runningExceptionEmulationCode(false) { m_guid = m_stateID; } @@ -132,7 +132,7 @@ ExecutionStatePtr S2EExecutionState::clone() { ret->m_stateID = g_s2e->fetchAndIncrementStateId(); ret->m_guid = ret->m_stateID; - ret->m_tlb.assignNewState(&ret->m_asCache, &ret->m_registers); + ret->m_tlb.assignNewState(&ret->m_asCache, &ret->m_registers, &ret->m_active); ret->m_registers.update(ret->addressSpace(), &ret->m_active, &ret->m_runningConcrete, ret, ret); ret->m_asCache.update(&ret->addressSpace()); m_registers.update(addressSpace(), &m_active, &m_runningConcrete, this, this); diff --git a/libs2ecore/src/S2EExecutionStateRegisters.cpp b/libs2ecore/src/S2EExecutionStateRegisters.cpp index d6a1a7a8f..dec0a8288 100644 --- a/libs2ecore/src/S2EExecutionStateRegisters.cpp +++ b/libs2ecore/src/S2EExecutionStateRegisters.cpp @@ -68,11 +68,9 @@ void S2EExecutionStateRegisters::update(klee::AddressSpace &addressSpace, const klee::IConcretizer *concretizer) { auto concreteState = addressSpace.findObject(s_concreteRegs.address); auto symbolicState = addressSpace.findObject(s_symbolicRegs.address); - auto cachesState = addressSpace.findObject(s_cpuCaches.address); m_symbolicRegs = addressSpace.getWriteable(symbolicState); m_concreteRegs = addressSpace.getWriteable(concreteState); - m_cpuCaches = addressSpace.getWriteable(cachesState); if (active && running_concrete) { m_runningConcrete = running_concrete; @@ -107,7 +105,10 @@ CPUX86State *S2EExecutionStateRegisters::getCpuState() const { } CPUState *S2EExecutionStateRegisters::getCpuCaches() const { - return *m_active ? (CPUState *) s_cpuCaches.address : (CPUState *) m_cpuCaches->getConcreteBuffer(true); + if (!*m_active) { + pabort("CPU caches accessed from an inactive state"); + } + return (CPUState *) s_cpuCaches.address; } bool S2EExecutionStateRegisters::addressSpaceChange(const klee::ObjectKey &key, @@ -126,7 +127,9 @@ bool S2EExecutionStateRegisters::addressSpaceChange(const klee::ObjectKey &key, assert(newState); return true; } else if (key == s_cpuCaches) { - m_cpuCaches = newState; + // The caches are never snapshotted, so there is no per-state + // reference to patch. The object is only reported as handled + // so that the TLB code does not see it. assert(newState); return true; } else { diff --git a/libs2ecore/src/S2EExecutionStateTlb.cpp b/libs2ecore/src/S2EExecutionStateTlb.cpp index fe378b0cc..e84e91239 100644 --- a/libs2ecore/src/S2EExecutionStateTlb.cpp +++ b/libs2ecore/src/S2EExecutionStateTlb.cpp @@ -89,6 +89,11 @@ bool S2EExecutionStateTlb::addressSpaceChangeUpdateTlb(const klee::ObjectStateCo #if defined(SE_ENABLE_PHYSRAM_TLB) void S2EExecutionStateTlb::updateRamTlb(const klee::ObjectStateConstPtr &oldState, const klee::ObjectStatePtr &newState) { + // An inactive state has no RAM TLB; it gets an empty one when activated. + if (!*m_active) { + return; + } + CPUState *cpu = m_registers->getCpuCaches(); uintptr_t tlb_index = (oldState->getAddress() >> 12) & (CPU_TLB_SIZE - 1); CPUTLBRAMEntry *re = &cpu->neg.se_ram_tlb[tlb_index]; @@ -113,14 +118,23 @@ void S2EExecutionStateTlb::updateRamTlb(const klee::ObjectStateConstPtr &oldStat #endif void S2EExecutionStateTlb::updateTlb(const klee::ObjectStateConstPtr &oldState, const klee::ObjectStatePtr &newState) { - - CPUState *cpu = m_registers->getCpuCaches(); - if (g_s2e_single_path_mode) { llvm::errs() << "Multi-path mode disabled.\n"; exit(-1); } + // An inactive state has no TLB, so there is nothing to repoint. Its map + // must be empty: doStateSwitch() clears it on deactivation and a forked + // state starts with an empty one. + if (!*m_active) { + if (!m_tlbMap.empty()) { + pabort("Inactive state has a non-empty TLB cache map"); + } + return; + } + + CPUState *cpu = m_registers->getCpuCaches(); + #ifdef S2E_DEBUG_TLBCACHE g_s2e->getDebugStream(g_s2e_state.get()) << "updateTlb: Replacing " << hexval(oldState) << " by " << hexval(newState) << "\n"; diff --git a/libs2ecore/src/S2EExecutor.cpp b/libs2ecore/src/S2EExecutor.cpp index fb9ae834c..4269023ff 100644 --- a/libs2ecore/src/S2EExecutor.cpp +++ b/libs2ecore/src/S2EExecutor.cpp @@ -764,6 +764,15 @@ void S2EExecutor::doStateSwitch(S2EExecutionStatePtr oldState, S2EExecutionState oldState->m_timersState = timers_state; +#if defined(SE_ENABLE_PHYSRAM_TLB) + // The RAM TLB is not snapshotted. It is cleared here, while the + // state is still active, so that no state ever sees another state's + // entries: the device restore of the incoming state writes guest + // memory through it (cpu_host_memory_rw), and an inactive state + // cannot repopulate it since getCpuCaches() aborts. + oldState->getTlb()->clearRamTlb(); +#endif + oldState->m_registers.saveConcreteState(); oldState->m_active = false; } @@ -811,6 +820,27 @@ void S2EExecutor::doStateSwitch(S2EExecutionStatePtr oldState, S2EExecutionState g_se_disable_tlb_flush = 0; + // The CPU caches (TLB, RAM TLB, TB jump cache) are not part of the + // snapshotted state: only the active state has a TLB, and it starts + // empty. The RAM TLB was cleared at deactivation. The flush must come + // after the guard above is cleared, because tlb_flush() returns early + // while it is set. + if (oldState) { + // The outgoing state's entries are still in the global TLB; the map + // that tracks them goes away with them. + oldState->getTlb()->flushTlbCache(); + } + + if (newState) { + if (!newState->getTlb()->isEmpty()) { + pabort("Activated state has a non-empty TLB cache map"); + } + + // Clears the TLB and the TB jump cache, and in multi-path mode + // empties the active state's map, which is newState here. + tlb_flush(env, 1); + } + // m_s2e->getCorePlugin()->onStateSwitch.emit(oldState, newState); } From a8e32904c536145eec35060c0d58cabab44793f1 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Fri, 4 Sep 2026 01:04:09 +0200 Subject: [PATCH 29/52] libs2ecore: removed the tlb flush from state merging MergingSearcher::mergeEnd() flushed the TLB so that the two states' cached entries would compare equal in compareArchitecturalConcreteState(). The caches no longer live in CPUX86State and are not compared, and both states are deactivated before S2EExecutionState::merge() runs, so the survivor gets a fresh TLB from doStateSwitch() when it is activated again. The flush was dead and is gone. The comparison keeps its two-memcmp shape: the window between se_common_start and se_common_end still hides the current TB, jmp_env, the breakpoint and watchpoint lists and the other non-architectural execution fields that CPU_COMMON leaves in the structure. The comments now say what the window hides and how the merged dirty mask reaches the TLB (tlb-update.md, step 6). Co-Authored-By: Claude Fable 5.1 --- libs2ecore/src/S2EExecutionState.cpp | 10 +++++++--- libs2ecore/src/S2EExecutionStateRegisters.cpp | 19 +++++++++++++++---- .../s2e/Plugins/Searchers/MergingSearcher.cpp | 3 --- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/libs2ecore/src/S2EExecutionState.cpp b/libs2ecore/src/S2EExecutionState.cpp index 27c53edf7..a27ae106b 100644 --- a/libs2ecore/src/S2EExecutionState.cpp +++ b/libs2ecore/src/S2EExecutionState.cpp @@ -522,9 +522,13 @@ bool S2EExecutionState::merge(const ExecutionState &_b) { return false; } - // Merge dirty mask by clearing bits that differ. Clearning bits in - // dirty mask can only affect performance but not correcntess. - // NOTE: this requires flushing TLB + // Merge the dirty masks by clearing the bits that differ. A cleared bit + // sends the next write to that page through the slow path, which costs + // performance but never correctness. TLB entries cache the bit as + // TLB_NOTDIRTY, so a TLB filled from the old mask would be stale. This + // state is inactive here and has no TLB: doStateSwitch() flushes the + // TLB when the state is activated again, and every entry filled after + // that reads the merged mask. { auto &dirtyMask = S2EExecutionStateMemory::getDirtyMask(); auto os = addressSpace().findObject(dirtyMask.address); diff --git a/libs2ecore/src/S2EExecutionStateRegisters.cpp b/libs2ecore/src/S2EExecutionStateRegisters.cpp index dec0a8288..abe90ed10 100644 --- a/libs2ecore/src/S2EExecutionStateRegisters.cpp +++ b/libs2ecore/src/S2EExecutionStateRegisters.cpp @@ -364,10 +364,21 @@ bool S2EExecutionStateRegisters::getRegionType(unsigned offset, unsigned size, b } } -/** - * The architectural part of the concrete portion of CPUState contains the COMMON stuff. - * We skip this stuff in the comparison. - */ +/// Compares the concrete registers of two states, skipping the execution +/// fields that are not architectural state. +/// +/// The concrete region of CPUX86State holds, between the se_common_start +/// and se_common_end markers, the fields that CPU_COMMON leaves in the +/// structure: the current TB, the softmmu IO context, the breakpoint and +/// watchpoint lists, jmp_env, the code generator's temporary buffer and +/// the opaque pointer. Two states that agree on every register can differ +/// there without being different for the guest, so this function compares +/// the two ranges on either side of the markers. The CPU caches live in +/// CPUState and are not compared at all: only the active state has them. +/// +/// @param other the state to compare against +/// @return zero when the architectural registers are identical, and the +/// result of memcmp() on the first differing range otherwise int S2EExecutionStateRegisters::compareArchitecturalConcreteState(const S2EExecutionStateRegisters &other) { CPUX86State *a = getCpuState(); CPUX86State *b = other.getCpuState(); diff --git a/libs2eplugins/src/s2e/Plugins/Searchers/MergingSearcher.cpp b/libs2eplugins/src/s2e/Plugins/Searchers/MergingSearcher.cpp index 0ef33192a..efeed7881 100644 --- a/libs2eplugins/src/s2e/Plugins/Searchers/MergingSearcher.cpp +++ b/libs2eplugins/src/s2e/Plugins/Searchers/MergingSearcher.cpp @@ -192,9 +192,6 @@ bool MergingSearcher::mergeEnd(S2EExecutionState *state, bool skipOpcode, bool c state->regs()->write(CPU_OFFSET(cc_tmp), 0); } - // The TLB state must be identical when we merge - tlb_flush(env, 1); - if (!mergePool.firstState) { // state is the first to reach merge_end. // all other states that reach merge_end will be merged with it and destroyed From 13bf74bea08cee876987c6ea7e2fc3b1b9b56c2e Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Fri, 4 Sep 2026 01:31:09 +0200 Subject: [PATCH 30/52] libcpu: moved the execution fields of CPU_COMMON into CPUState CPUX86State no longer carries CPU_COMMON. The execution fields that upstream keeps in CPUState (exception_index, interrupt_request, halted, exit_request, jmp_env, the breakpoint and watchpoint lists, cpu_index) and the S2E additions that go with them (the current TB, se_current_tb, the softmmu IO context, translate_single_instruction, se_tb_abort, generate_llvm) now sit in the slim CPUState ahead of the caches. The fields that had no reader (temp_buf, restored_instruction_size, next_cpu, numa_node, running, opaque, created, stop) are gone, and the CPU list that next_cpu threaded is a single first_cpu pointer. cpu_state_reset() clears the CPUX86State prefix up to the size field and calls cpu_common_reset() for the CPUState fields a reset discards. libs2ecore registers the new region as its own shared-concrete object, CpuExecutionState, covering [&g_cpu, offsetof(CPUState, neg)), and snapshots it with the concrete registers on every state switch, so the fields do not inherit the never-snapshotted cache region. doStateSwitch() keeps carrying jmp_env across the restore because it belongs to the host call stack doing the switch. The se_common_start / se_common_end window and the two-memcmp comparison in compareArchitecturalConcreteState() are gone: the concrete region holds only architectural state now. Generated code reaches exit_request, se_current_tb and se_tb_abort at a negative offset from tcg_env, so TCGContext::env_offset_se_tb_abort is signed. All other accesses go through env_cpu(env). PORTING.md and tlb-update.md record the TLB ownership work and this move as landed, and phase 4 keeps only the renames onto 11.1 field names. Co-Authored-By: Claude Fable 5.1 --- libcpu/PORTING.md | 86 ++++++++------ libcpu/include/cpu/common.h | 54 --------- libcpu/include/cpu/i386/cpu.h | 10 +- libcpu/include/cpu/state.h | 76 +++++++++++- libcpu/src/cpu-exec.c | 108 +++++++++--------- libcpu/src/exec-bp.c | 42 +++---- libcpu/src/exec-tb.c | 31 ++--- libcpu/src/exec-tlb.c | 6 +- libcpu/src/exec.c | 47 ++++---- libcpu/src/softmmu_template.h | 12 +- libcpu/src/target-i386/cpu.h | 2 +- libcpu/src/target-i386/helper.c | 31 ++--- libcpu/src/target-i386/op_helper.c | 34 +++--- libcpu/src/target-i386/translate.c | 17 +-- libcpu/src/translate-all.c | 4 +- libcpu/tlb-update.md | 33 ++++-- libs2e/src/s2e-kvm-io.cpp | 10 +- libs2e/src/s2e-kvm-vcpu.cpp | 28 ++--- .../include/s2e/S2EExecutionStateRegisters.h | 42 +++++-- libs2ecore/src/CorePluginInterface.cpp | 42 +++---- libs2ecore/src/MMUFunctionHandlers.cpp | 4 +- libs2ecore/src/S2EExecutionState.cpp | 14 +-- libs2ecore/src/S2EExecutionStateRegisters.cpp | 46 ++++---- libs2ecore/src/S2EExecutor.cpp | 51 ++++++--- libs2ecore/src/S2EExternalDispatcher.cpp | 6 +- libtcg/include/tcg/tcg.h | 3 +- 26 files changed, 473 insertions(+), 366 deletions(-) diff --git a/libcpu/PORTING.md b/libcpu/PORTING.md index 47f3d1428..d2327faf3 100644 --- a/libcpu/PORTING.md +++ b/libcpu/PORTING.md @@ -5,7 +5,11 @@ the gap is too wide to merge: it gets rebuilt from upstream instead. This document is the plan for doing that **concrete execution first**, keeping S2E's KVM-shim architecture and leaving symbolic execution to land on top afterwards. -Measured against `~/qemu` at `v11.1.0` and this tree at `9982579d`. +Measured against `~/softs/qemu` at `v11.1.0` and this tree at `9982579d`. Work that +has landed since is marked **Done** in the phase it belongs to; the state +management half of the TLB work (`tlb-update.md`) and the move of the +execution fields out of `CPUX86State` are in, so phases 1, 2 and 4 are +lighter than the estimates below. | | | |---|---| @@ -111,6 +115,11 @@ the negative TLB offsets work unmodified), and replace `cpu->cc` with a direct imports as-is. - Cost: ~200 lines of hand-written header, in `libcpu/include/cpu/state.h`. + **Done**: the header exists, with `CPUState` carrying the execution fields + (`exception_index`, `interrupt_request`, `halted`, `exit_request`, + `jmp_env`, the breakpoint and watchpoint lists, the current TB and the S2E + flags) ahead of `CPUNegativeOffsetState`, and `cpu_env()` / `env_cpu()` as + pointer arithmetic. `tcg_ops` is declared but unused until phase 2. - Buys: accel/tcg and target/i386/tcg compile essentially unmodified. - Risk: **low**. Fields are added on demand; a missing one is a compile error, not a silent bug. @@ -170,7 +179,9 @@ Disable the victim TLB initially, and move S2E's flags into - Cost: mostly deletion. `exec-tlb.c` goes away, and so do ~216 KB of per-state cache. The main-TLB `CPU_TLB_SIZE` sites in libs2ecore become run-time mask - reads (the `se_ram_tlb` sites keep a pinned size; see 9.2). + reads (the `se_ram_tlb` sites keep a pinned size; see 9.2). **Done** for + the ownership half: the caches live in `ArchCPU`, are never snapshotted, + and are flushed on every state switch (`tlb-update.md`). - Buys: smaller per-state memory, faster state switches, and `objectState` gets a better home in `CPUTLBEntryFull` than in the fast entry. `cputlb.c` still needs one contained deviation (a pinned TLB size, two functions) because @@ -380,7 +391,13 @@ codebase. get their first real merge test at the next upgrade. - Write `libcpu/include/cpu/state.h`: slim `CPUState`, `CPUNegativeOffsetState`, `ArchCPU`, `cpu_env()` / `env_cpu()`, and the `TCGCPUOps` pointer that replaces - `cpu->cc`. + `cpu->cc`. Done: `CPU_COMMON` is gone from `CPUX86State`; its fields are in + `CPUState`, reached through `env_cpu(env)` in libcpu, libs2e and libs2ecore, + and `cpu_common_reset()` clears the ones a CPU reset discards. libs2ecore + registers `[&g_cpu, offsetof(CPUState, neg))` as a snapshotted + shared-concrete object (`CpuExecutionState`) next to the caches. Generated + code reaches `exit_request`, `se_current_tb` and `se_tb_abort` at negative + offsets from `tcg_env`, so `TCGContext::env_offset_se_tb_abort` is signed. - Write the memory shim: upstream's `iotlb_to_section`, `memory_region_dispatch_*`, `qemu_ram_addr_from_host*` and the dirty-tracking predicates, expressed over `MemoryDesc` and `exec-ram.h`. @@ -402,9 +419,9 @@ drives qht insert/lookup/remove/resize. - Rewrite the eight `MemoryRegion` touch points in `cputlb.c` against the phase 1 shim. - Apply the TLB decisions from section 9: disable the victim TLB, move S2E's flag - bits into `slow_flags[]`, and move `objectState` into `CPUTLBEntryFull`. If - `tlb-update.md` has landed first, the ownership half of this is already done - and `cputlb.c` imports without S2E-side surprises. Bring + bits into `slow_flags[]`, and move `objectState` into `CPUTLBEntryFull`. + `tlb-update.md` has landed, so the ownership half of this is done and + `cputlb.c` imports without S2E-side surprises. Bring `libtcg/include/tcg/tlb.h` forward to the 11.1 flag scheme at the same time. It is an S2E-original that was never upgraded and still describes the pre-11.1 bit allocation. @@ -457,29 +474,27 @@ off, in both release and debug trees. ### Phase 4: Wire to the KVM shim and boot (2-3 weeks) -- Update libs2e for fields that moved from `CPUX86State` into `CPUState`: - `jmp_env` (~30 sites), `interrupt_request`, `exception_index`, `halted`, - `current_tb`, `tlb_table`. Mostly mechanical; `s2e-kvm-vcpu.cpp` and - `s2e-kvm-state.cpp` carry most of it. -- **Extend the per-state snapshot to the non-cache part of `CPUState`.** Today - `interrupt_request`, `exception_index`, `halted` and `jmp_env` are saved - implicitly because they sit inside the snapshotted `CPUX86State` window; once - they move into the slim `CPUState` they land in the `[&g_cpu, &g_cpu.env)` - region that `tlb-update.md` registers as shared-concrete and *never - snapshots*. They are per-state execution state, not caches, so - `saveConcreteState()` / `restoreConcreteState()` (or a separate registered - object) must cover them explicitly, or state switches corrupt silently. +- Done: libs2e, libs2ecore and libcpu already reach the fields that moved + from `CPUX86State` into `CPUState` (`jmp_env`, `interrupt_request`, + `exception_index`, `halted`, `current_tb`, ...) through `env_cpu()`, and + the per-state snapshot covers them: `saveConcreteState()` / + `restoreConcreteState()` copy the `CpuExecutionState` object together with + the concrete registers, and `doStateSwitch()` carries `jmp_env` across the + restore because it belongs to the host call stack doing the switch. What + remains here is renaming the S2E-only fields upstream does not have + (`current_tb`, `se_current_tb`, `translate_single_instruction`, + `se_tb_abort`, `generate_llvm`, `mem_io_vaddr`) onto their 11.1 + equivalents where one exists (`cflags_next_tb`, `tcg_tb_lookup()`). - Map libcpu's exit reasons onto `kvm_run` as before; `cpu_x86_exec()` keeps its shape, `cpu_exec()` gains upstream's `cpu_exec_setjmp` structure. - Re-derive `cpu_get_pic_interrupt()`, `do_cpu_init()`, `cpu_state_reset()` against the new state layout, including `cpu_init_fp_statuses()`, which must run after every reset memset. -- Move the TLB, `se_ram_tlb`, `se_tlb_current` and `tb_jmp_cache` out of the - snapshotted concrete region, and flush them in `doStateSwitch()` after the new - state is activated - and `g_se_disable_tlb_flush` is cleared. Collapse the per-state - `S2EExecutionStateTlb` into executor-owned data. (Phase 6 work in spirit, but - the struct layout change belongs here.) +- Done: the TLB, `se_ram_tlb`, `se_tlb_current` and `tb_jmp_cache` are out of + the snapshotted region and flushed in `doStateSwitch()` after the new state + is activated and `g_se_disable_tlb_flush` is cleared. Still open: collapsing + the per-state `S2EExecutionStateTlb` into executor-owned data; today the + class stays per state and asserts that an inactive state's map is empty. - Rewire libs2e's CPUID plumbing to the new feature model: `S2EKVM::init()`'s `x86_cpudef_setup()` + `cpu_x86_register(&m_cpuid, model, is64)` pair becomes `x86_cpu_load_model()` + @@ -792,7 +807,8 @@ difference between ~200 MB and ~1 GB of cache nobody reads across a switch. *State switches get faster, not slower.* The `saveConcreteState` / `restoreConcreteState` memcpy shrinks from ~216 KB to a few KB. -**What it requires.** +**What it requires.** All of this has landed except the collapse of +`S2EExecutionStateTlb` into a single instance; see `tlb-update.md`. - Flush the TLB, the RAM TLB and `m_tlbMap` on state switch. Placement matters: `doStateSwitch()` sets `g_se_disable_tlb_flush = 1` for the duration precisely @@ -855,12 +871,14 @@ doing only if profiling says the misses matter. The ownership change above is entangled with S2E's state management rather than with QEMU's code, so it is the part of the port least helped by being done in -the middle of a 43k-line import. It can be landed on the current tree first +the middle of a 43k-line import. It was landed on the current tree first (introduce the `ArchCPU` layout, move the caches out of the registered KLEE region entirely, flush at state switch) and validated on its own, on a tree -that still boots. `tlb-update.md` is that plan; it also shows why upstream's -dynamic sizing needs a pinned size or a fixed arena rather than an -allocator hook. +that still boots. `tlb-update.md` is that plan and records what landed; it +also shows why upstream's dynamic sizing needs a pinned size or a fixed arena +rather than an allocator hook. The same argument then carried the rest of +`CPU_COMMON` into `CPUState` (phase 1), so the snapshot boundary that +`tlb-update.md` section 1 warned about is settled before the import. ### 9.6 What still has to be pinned or checked @@ -883,11 +901,11 @@ analysis: inheriting upstream's 22-mode maximum. - **The `CPUTLBDescFast` index convention** must match between libtcg's `tlb_mask_table_ofs()` and upstream's `mmuidx_to_fast_index()`. See section 8. -- **`env->se_tlb_current`** is a cached `CPUTLBEntry *` inside the snapshotted - state, written by the softmmu IO path and read from bitcode. Once the tables - are executor-owned it becomes a raw pointer from per-state data into a - reallocatable array: move it next to the TLB in `CPUNegativeOffsetState`, or - demote it to an index. +- **`se_tlb_current`** is a cached `CPUTLBEntry *`, written by the softmmu IO + path and read from bitcode. It now sits next to the TLB in + `CPUNegativeOffsetState`, so it lives and dies with the tables; under the + arena option it would still have to be rebased or demoted to an index when + the in-use sub-range changes. - **`libtcg/include/tcg/tlb.h`** is an S2E-original that was never brought forward and still describes the pre-11.1 flag scheme (including `TLB_RECHECK`, removed upstream in 4.1, and a `TLB_FLAGS_MASK` that omits `TLB_MEM_TRACE`). diff --git a/libcpu/include/cpu/common.h b/libcpu/include/cpu/common.h index d53f3adb5..9e7f72ace 100644 --- a/libcpu/include/cpu/common.h +++ b/libcpu/include/cpu/common.h @@ -24,8 +24,6 @@ #include #include #include -#include -#include #ifdef __cplusplus extern "C" { @@ -44,58 +42,6 @@ typedef struct CPUWatchpoint { QTAILQ_ENTRY(CPUWatchpoint) entry; } CPUWatchpoint; -#define CPU_TEMP_BUF_NLONGS 128 -#define CPU_COMMON \ - int se_common_start; /* Dummy variable to mark the start of the common area */ \ - struct TranslationBlock *current_tb; /* currently executing TB */ \ - struct TranslationBlock *se_current_tb; /* currently executing TB */ \ - /* soft mmu support */ \ - /* in order to avoid passing too many arguments to the MMIO \ - helpers, we store some rarely used information in the CPU \ - context) */ \ - unsigned long mem_io_pc; /* host pc at which the memory was \ - accessed */ \ - target_ulong mem_io_vaddr; /* target virtual addr at which the \ - memory was accessed */ \ - /* When set, this forces the translator to put only one instruction in the next TB. \ - * This variable is automatically reset before code execution */ \ - uint32_t translate_single_instruction; \ - uint32_t halted; /* Nonzero if the CPU is in suspend state */ \ - uint32_t interrupt_request; \ - volatile sig_atomic_t exit_request; \ - /* The TLB, RAM TLB and TB jump cache live in CPUState; see cpu/state.h */ \ - /* buffer for temporaries in the code generator */ \ - long temp_buf[CPU_TEMP_BUF_NLONGS]; \ - /* Used to handle self-modifying code */ \ - unsigned restored_instruction_size; \ - /* Set when the LLVM interpreter should exit the current TB (e.g., self-modifying code) */ \ - uint32_t se_tb_abort; \ - \ - /* from this point: preserved by CPU reset */ \ - /* ice debug support */ \ - QTAILQ_HEAD(breakpoints_head, CPUBreakpoint) breakpoints; \ - int singlestep_enabled; \ - \ - QTAILQ_HEAD(watchpoints_head, CPUWatchpoint) watchpoints; \ - CPUWatchpoint *watchpoint_hit; \ - \ - /* Core interrupt code */ \ - jmp_buf jmp_env; \ - int exception_index; \ - \ - CPUArchState *next_cpu; /* next CPU sharing TB cache */ \ - int cpu_index; /* CPU index (informative) */ \ - int numa_node; /* NUMA node this cpu is belonging to */ \ - int running; /* Nonzero if cpu is currently running(usermode). */ \ - /* user data */ \ - void *opaque; \ - unsigned size; /* Size of this structure */ \ - \ - uint32_t created; \ - uint32_t stop; /* Stop request */ \ - int generate_llvm; /* Generate LLVM code during translation */ \ - int se_common_end; /* Dummy variable to mark the end of the common area */ - #ifdef __cplusplus } #endif diff --git a/libcpu/include/cpu/i386/cpu.h b/libcpu/include/cpu/i386/cpu.h index 56771b82f..0e68f8f71 100644 --- a/libcpu/include/cpu/i386/cpu.h +++ b/libcpu/include/cpu/i386/cpu.h @@ -167,7 +167,10 @@ typedef struct CPUX86State { uint8_t nmi_injected; uint8_t nmi_pending; - CPU_COMMON + /* cpu_state_reset() clears everything before this point; size and the + fields after it survive a reset. The execution fields that QEMU 1.0 + kept here (CPU_COMMON) live in CPUState; see cpu/state.h. */ + unsigned size; /* sizeof(CPUX86State), checked by libs2ecore against its own build */ uint64_t pat; @@ -210,8 +213,9 @@ CPUX86State *cpu_x86_init(const cpuid_t *cpuid); int cpu_x86_exec(CPUX86State *s); static inline bool cpu_has_work(CPUX86State *env) { - return ((env->interrupt_request & CPU_INTERRUPT_HARD) && (env->mflags & IF_MASK)) || - (env->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_INIT | CPU_INTERRUPT_SIPI | CPU_INTERRUPT_MCE)); + return ((env_cpu(env)->interrupt_request & CPU_INTERRUPT_HARD) && (env->mflags & IF_MASK)) || + (env_cpu(env)->interrupt_request & + (CPU_INTERRUPT_NMI | CPU_INTERRUPT_INIT | CPU_INTERRUPT_SIPI | CPU_INTERRUPT_MCE)); } target_ulong cpu_get_eflags(CPUX86State *env); diff --git a/libcpu/include/cpu/state.h b/libcpu/include/cpu/state.h index c0031b4fc..d66115b09 100644 --- a/libcpu/include/cpu/state.h +++ b/libcpu/include/cpu/state.h @@ -26,11 +26,28 @@ * ArchCPU, so that cpu_env() / env_cpu() are pointer arithmetic and generated * code reaches the TLB at a fixed negative offset from env. * - * CPUState holds only the CPU caches for now: the TLB, the RAM TLB and the - * TB jump cache, moved out of CPUX86State so that they stop being part of - * the snapshotted execution state (tlb-update.md). The execution-state fields - * of upstream's CPUState (exception_index, interrupt_request, jmp_env, ...) - * migrate here from CPUX86State during the port (PORTING.md phase 4). + * CPUState holds the execution fields that upstream keeps there + * (exception_index, interrupt_request, halted, jmp_env, the breakpoint and + * watchpoint lists, ...), the S2E additions that go with them (the current + * TB, the abort flag, generate_llvm), and the CPU caches: the TLB, the RAM + * TLB and the TB jump cache. QEMU 1.0 kept all of these inside CPUX86State + * (CPU_COMMON). + * + * libs2ecore registers the structure as two KLEE objects, split at neg: + * + * - [0, offsetof(CPUState, neg)) holds the execution fields. They are + * per-state, so libs2ecore snapshots them on every state switch together + * with the concrete registers. jmp_env is the exception: it belongs to the + * host call stack performing the switch, and doStateSwitch() carries it + * across the restore. + * - [offsetof(CPUState, neg), sizeof(CPUState)) holds the caches. Only the + * active state has a TLB; the region is never snapshotted and is flushed + * on every switch (tlb-update.md). + * + * Both objects are shared-concrete so that helpers and the softmmu fast path + * can reach the fields as bitcode inside KLEE. Generated code addresses the + * execution fields through tcg_env at a negative offset, computed as + * offsetof(ArchCPU, parent_obj.field) - offsetof(ArchCPU, env). * * The TLB keeps the QEMU 1.0 organization (fixed size, iotlb, no victim TLB, * no CPUTLBEntryFull); upstream's algorithms arrive with the cputlb.c import @@ -40,11 +57,14 @@ * CPUArchState by value, so the complete CPUX86State must be visible first. */ +#include +#include #include #include #include +#include #include #include #include @@ -99,12 +119,55 @@ typedef struct CPUNegativeOffsetState { /* * Common state of one CPU core or thread. Slim version of upstream's * CPUState: no QOM, no threading, no work queues, one address space. + * + * Everything before neg is snapshotted per execution state by libs2ecore. + * cpu_common_reset() clears the fields a CPU reset discards; the others + * (the breakpoint and watchpoint lists, single-step mode, jmp_env, + * exception_index, generate_llvm) survive a reset. */ typedef struct CPUState { /* Replaces upstream's cpu->cc->tcg_ops; wired up when the 11.1 accel/tcg code lands (PORTING.md 3.1). */ const struct TCGCPUOps *tcg_ops; + int cpu_index; + + /* Longjmp target of the CPU loop. See the note on state switches above. */ + jmp_buf jmp_env; + + /* Nonzero if the CPU is in suspend state. */ + uint32_t halted; + uint32_t interrupt_request; + /* Set by cpu_exit() to leave the CPU loop; tested by generated code. */ + volatile sig_atomic_t exit_request; + int exception_index; + int singlestep_enabled; + + /* Currently executing TB; NULL while no generated code runs. */ + struct TranslationBlock *current_tb; + /* TB being executed, stored by the TB itself so that a regenerated LLVM + function still names the original TB (S2E). */ + struct TranslationBlock *se_current_tb; + + /* Softmmu support: the host pc and the guest virtual address of the + memory access being handled, so that the MMIO helpers can restore the + CPU state without more arguments. */ + uintptr_t mem_io_pc; + target_ulong mem_io_vaddr; + + /* Forces the translator to put a single instruction in the next TB. + Reset before code execution (S2E). */ + uint32_t translate_single_instruction; + /* Set when the LLVM interpreter must exit the current TB, e.g., after + self-modifying code invalidated it (S2E). */ + uint32_t se_tb_abort; + /* Generate LLVM code during translation (S2E). */ + int generate_llvm; + + QTAILQ_HEAD(breakpoints_head, CPUBreakpoint) breakpoints; + QTAILQ_HEAD(watchpoints_head, CPUWatchpoint) watchpoints; + CPUWatchpoint *watchpoint_hit; + /* MUST BE LAST, to minimize the displacement to CPUArchState. */ char neg_align[-sizeof(CPUNegativeOffsetState) % 16] QEMU_ALIGNED(16); CPUNegativeOffsetState neg; @@ -151,6 +214,9 @@ static inline CPUTLBDescFast *cpu_tlb_fast(CPUState *cpu, int mmu_idx) { return &cpu->neg.tlb.f[mmu_idx]; } +/* Clears the execution fields that a CPU reset discards; defined in exec.c. */ +void cpu_common_reset(CPUState *cpu); + #ifdef __cplusplus } #endif diff --git a/libcpu/src/cpu-exec.c b/libcpu/src/cpu-exec.c index 8e3f0b91f..d9d51961a 100644 --- a/libcpu/src/cpu-exec.c +++ b/libcpu/src/cpu-exec.c @@ -46,8 +46,8 @@ void se_tb_safe_flush(void) { // #define CONFIG_DEBUG_EXEC void cpu_loop_exit(CPUArchState *env) { - env->current_tb = NULL; - longjmp(env->jmp_env, 1); + env_cpu(env)->current_tb = NULL; + longjmp(env_cpu(env)->jmp_env, 1); } void cpu_loop_exit_restore(CPUArchState *env, uintptr_t ra) { @@ -65,8 +65,8 @@ void cpu_loop_exit_restore(CPUArchState *env, uintptr_t ra) { void cpu_resume_from_signal(CPUArchState *env, void *puc) { /* XXX: restore cpu registers saved in host registers */ - env->exception_index = -1; - longjmp(env->jmp_env, 1); + env_cpu(env)->exception_index = -1; + longjmp(env_cpu(env)->jmp_env, 1); } #endif @@ -89,7 +89,7 @@ static TranslationBlock *tb_find_slow(CPUArchState *env, target_ulong pc, target int llvm_nok = 0; #if defined(CONFIG_SYMBEX_MP) - if (env->generate_llvm && !tb->llvm_function) { + if (env_cpu(env)->generate_llvm && !tb->llvm_function) { llvm_nok = 1; } #endif @@ -154,7 +154,7 @@ static inline TranslationBlock *tb_find_fast(CPUArchState *env) { tb = env_cpu(env)->neg.tb_jmp_cache[tb_jmp_cache_hash_func(pc)]; #ifdef CONFIG_SYMBEX - int llvm_nok = env->generate_llvm && (!tb || !tb->llvm_function); + int llvm_nok = env_cpu(env)->generate_llvm && (!tb || !tb->llvm_function); #else int llvm_nok = 0; #endif @@ -179,8 +179,8 @@ CPUDebugExcpHandler *cpu_set_debug_excp_handler(CPUDebugExcpHandler *handler) { static void cpu_handle_debug_exception(CPUArchState *env) { CPUWatchpoint *wp; - if (!env->watchpoint_hit) { - QTAILQ_FOREACH (wp, &env->watchpoints, entry) { + if (!env_cpu(env)->watchpoint_hit) { + QTAILQ_FOREACH (wp, &env_cpu(env)->watchpoints, entry) { wp->flags &= ~BP_WATCHPOINT_HIT; } } @@ -219,6 +219,7 @@ static void dump_regs(CPUX86State *env, int isStart) { } static uintptr_t fetch_and_run_tb(TranslationBlock *prev_tb, int tb_exit_code, CPUArchState *env) { + CPUState *cpu = env_cpu(env); uint8_t *tc_ptr; uintptr_t last_tb; @@ -245,16 +246,16 @@ static uintptr_t fetch_and_run_tb(TranslationBlock *prev_tb, int tb_exit_code, C /* cpu_interrupt might be called while translating the TB, but before it is linked into a potentially - infinite loop and becomes env->current_tb. Avoid + infinite loop and becomes cpu->current_tb. Avoid starting execution if there is a pending interrupt. */ - env->current_tb = tb; + cpu->current_tb = tb; - env->translate_single_instruction = 0; + cpu->translate_single_instruction = 0; barrier(); - if (unlikely(env->exit_request)) { - env->current_tb = NULL; + if (unlikely(cpu->exit_request)) { + cpu->current_tb = NULL; return 0; } @@ -270,15 +271,15 @@ static uintptr_t fetch_and_run_tb(TranslationBlock *prev_tb, int tb_exit_code, C } #if defined(CONFIG_SYMBEX) - env->se_tb_abort = 0; - env->se_current_tb = tb; + cpu->se_tb_abort = 0; + cpu->se_current_tb = tb; if (likely(*g_sqi.mode.fast_concrete_invocation)) { **g_sqi.mode.running_exception_emulation_code = 0; last_tb = tcg_qemu_tb_exec(env, tc_ptr); } else { last_tb = g_sqi.exec.tb_exec(env, tb); } - env->se_current_tb = NULL; + cpu->se_current_tb = NULL; #else last_tb = tcg_qemu_tb_exec(env, tc_ptr); @@ -289,13 +290,14 @@ static uintptr_t fetch_and_run_tb(TranslationBlock *prev_tb, int tb_exit_code, C dump_regs(env, 0); } - env->current_tb = NULL; + cpu->current_tb = NULL; return last_tb; } static bool process_interrupt_request(CPUArchState *env) { - int interrupt_request = env->interrupt_request; + CPUState *cpu = env_cpu(env); + int interrupt_request = cpu->interrupt_request; if (likely(!interrupt_request)) { return false; @@ -306,36 +308,36 @@ static bool process_interrupt_request(CPUArchState *env) { libcpu_log_mask(CPU_LOG_INT, " process_interrupt intrq=%#x mflags=%#lx hf1=%#x hf2=%#x\n", interrupt_request, (uint64_t) env->mflags, env->hflags, env->hflags2); - if (unlikely(env->singlestep_enabled & SSTEP_NOIRQ)) { + if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) { /* Mask out external interrupts for this step. */ interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK; } if (interrupt_request & CPU_INTERRUPT_DEBUG) { - env->interrupt_request &= ~CPU_INTERRUPT_DEBUG; - env->exception_index = EXCP_DEBUG; + cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG; + cpu->exception_index = EXCP_DEBUG; cpu_loop_exit(env); } if (interrupt_request & CPU_INTERRUPT_INIT) { svm_check_intercept(env, SVM_EXIT_INIT); do_cpu_init(env); - env->exception_index = EXCP_HALTED; + cpu->exception_index = EXCP_HALTED; cpu_loop_exit(env); } else if (interrupt_request & CPU_INTERRUPT_SIPI) { perror("Not implemented"); } else if (env->hflags2 & HF2_GIF_MASK) { if ((interrupt_request & CPU_INTERRUPT_SMI) && !(env->hflags & HF_SMM_MASK)) { svm_check_intercept(env, SVM_EXIT_SMI); - env->interrupt_request &= ~CPU_INTERRUPT_SMI; + cpu->interrupt_request &= ~CPU_INTERRUPT_SMI; do_smm_enter(env); has_interrupt = true; } else if ((interrupt_request & CPU_INTERRUPT_NMI) && !(env->hflags2 & HF2_NMI_MASK)) { - env->interrupt_request &= ~CPU_INTERRUPT_NMI; + cpu->interrupt_request &= ~CPU_INTERRUPT_NMI; env->hflags2 |= HF2_NMI_MASK; do_interrupt_x86_hardirq(env, EXCP02_NMI, 1); has_interrupt = true; } else if (interrupt_request & CPU_INTERRUPT_MCE) { - env->interrupt_request &= ~CPU_INTERRUPT_MCE; + cpu->interrupt_request &= ~CPU_INTERRUPT_MCE; do_interrupt_x86_hardirq(env, EXCP12_MCHK, 0); has_interrupt = true; } else if ((interrupt_request & CPU_INTERRUPT_HARD) && @@ -345,7 +347,7 @@ static bool process_interrupt_request(CPUArchState *env) { int intno; svm_check_intercept(env, SVM_EXIT_INTR); - env->interrupt_request &= ~CPU_INTERRUPT_VIRQ; + cpu->interrupt_request &= ~CPU_INTERRUPT_VIRQ; /* This clears the request of the source that supplies the vector. The request of the other source stays pending. */ @@ -369,15 +371,15 @@ static bool process_interrupt_request(CPUArchState *env) { intno = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_vector)); libcpu_log_mask(CPU_LOG_TB_IN_ASM, "Servicing virtual hardware INT=0x%02x\n", intno); do_interrupt_x86_hardirq(env, intno, 1); - env->interrupt_request &= ~CPU_INTERRUPT_VIRQ; + cpu->interrupt_request &= ~CPU_INTERRUPT_VIRQ; has_interrupt = true; } } /* Don't use the cached interrupt_request value, do_interrupt may have updated the EXITTB flag. */ - if (env->interrupt_request & CPU_INTERRUPT_EXITTB) { - env->interrupt_request &= ~CPU_INTERRUPT_EXITTB; + if (cpu->interrupt_request & CPU_INTERRUPT_EXITTB) { + cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB; has_interrupt = true; } @@ -385,29 +387,31 @@ static bool process_interrupt_request(CPUArchState *env) { } static int process_exceptions(CPUArchState *env) { + CPUState *cpu = env_cpu(env); int ret = 0; - if (env->exception_index < 0) { + if (cpu->exception_index < 0) { return ret; } /* if an exception is pending, we execute it here */ - if (env->exception_index >= EXCP_INTERRUPT) { + if (cpu->exception_index >= EXCP_INTERRUPT) { /* exit request from the cpu execution loop */ - ret = env->exception_index; + ret = cpu->exception_index; if (ret == EXCP_DEBUG) { cpu_handle_debug_exception(env); } } else { - libcpu_log_mask(CPU_LOG_INT, " do_interrupt exidx=%x\n", env->exception_index); + libcpu_log_mask(CPU_LOG_INT, " do_interrupt exidx=%x\n", cpu->exception_index); do_interrupt(env); - env->exception_index = -1; + cpu->exception_index = -1; } return ret; } static bool execution_loop(CPUArchState *env) { + CPUState *cpu = env_cpu(env); uintptr_t last_tb = 0; int last_tb_exit_code = 0; TranslationBlock *ltb = NULL; @@ -421,10 +425,10 @@ static bool execution_loop(CPUArchState *env) { has_interrupt = true; } - if (unlikely(!has_interrupt && env->exit_request)) { + if (unlikely(!has_interrupt && cpu->exit_request)) { libcpu_log_mask(CPU_LOG_EXEC, " execution_loop: exit_request\n"); - env->exit_request = 0; - env->exception_index = EXCP_INTERRUPT; + cpu->exit_request = 0; + cpu->exception_index = EXCP_INTERRUPT; // XXX: return status code instead cpu_loop_exit(env); @@ -467,14 +471,15 @@ static bool execution_loop(CPUArchState *env) { } int cpu_exec(CPUArchState *env) { + CPUState *cpu = env_cpu(env); int ret; - if (env->halted) { + if (cpu->halted) { if (!cpu_has_work(env)) { return EXCP_HALTED; } - env->halted = 0; + cpu->halted = 0; } cpu_single_env = env; @@ -487,30 +492,30 @@ int cpu_exec(CPUArchState *env) { } #endif - env->exception_index = -1; + cpu->exception_index = -1; libcpu_log_mask(CPU_LOG_EXEC, "cpu_loop enter mflags=%#lx hf1=%#x hf2=%#x\n", (uint64_t) env->mflags, env->hflags, env->hflags2); /* prepare setjmp context for exception handling */ for (;;) { - if (setjmp(env->jmp_env) == 0) { + if (setjmp(cpu->jmp_env) == 0) { /** * It is important to reset the current TB everywhere where the CPU loop exits. * Otherwise, TB unchaining might get stuck on the next signal. * This usually happens when TB cache is flushed but current tb is not reset. */ - env->current_tb = NULL; + cpu->current_tb = NULL; libcpu_log_mask(CPU_LOG_EXEC, " setjmp entered eip=%#lx\n", (uint64_t) env->eip); #ifdef CONFIG_SYMBEX - assert(env->exception_index != EXCP_SE); + assert(cpu->exception_index != EXCP_SE); if (g_sqi.exec.finalize_tb_exec()) { g_sqi.exec.cleanup_tb_exec(); - if (env->exception_index == EXCP_SE) { + if (cpu->exception_index == EXCP_SE) { cpu_single_env = NULL; - env->current_tb = NULL; + cpu->current_tb = NULL; return EXCP_SE; } continue; @@ -519,9 +524,9 @@ int cpu_exec(CPUArchState *env) { ret = process_exceptions(env); if (ret) { - if (ret == EXCP_HLT && env->interrupt_request) { - env->exception_index = -1; - env->halted = 0; + if (ret == EXCP_HLT && cpu->interrupt_request) { + cpu->exception_index = -1; + cpu->halted = 0; continue; } break; @@ -535,7 +540,7 @@ int cpu_exec(CPUArchState *env) { g_sqi.exec.cleanup_tb_exec(); if (!g_sqi.exec.is_runnable()) { cpu_single_env = NULL; - env->current_tb = NULL; + cpu->current_tb = NULL; return EXCP_SE; } #endif @@ -543,11 +548,12 @@ int cpu_exec(CPUArchState *env) { /* Reload env after longjmp - the compiler may have smashed all * local variables as longjmp is marked 'noreturn'. */ env = cpu_single_env; + cpu = env_cpu(env); } } /* for(;;) */ libcpu_log_mask(CPU_LOG_EXEC, "cpu_loop exit ret=%#x eip=%#lx\n", ret, (uint64_t) env->eip); - env->current_tb = NULL; + cpu->current_tb = NULL; #if defined(TARGET_I386) #ifdef CONFIG_SYMBEX @@ -588,7 +594,7 @@ int cpu_exec(CPUArchState *env) { #error unsupported target CPU #endif - env->current_tb = NULL; + cpu->current_tb = NULL; /* fail safe : never use cpu_single_env outside cpu_exec() */ cpu_single_env = NULL; diff --git a/libcpu/src/exec-bp.c b/libcpu/src/exec-bp.c index 2f95a88ca..b3cc6223a 100644 --- a/libcpu/src/exec-bp.c +++ b/libcpu/src/exec-bp.c @@ -61,9 +61,9 @@ int cpu_watchpoint_insert(CPUArchState *env, target_ulong addr, target_ulong len /* keep all GDB-injected watchpoints in front */ if (flags & BP_GDB) - QTAILQ_INSERT_HEAD(&env->watchpoints, wp, entry); + QTAILQ_INSERT_HEAD(&env_cpu(env)->watchpoints, wp, entry); else - QTAILQ_INSERT_TAIL(&env->watchpoints, wp, entry); + QTAILQ_INSERT_TAIL(&env_cpu(env)->watchpoints, wp, entry); tlb_flush_page(env, addr); @@ -77,7 +77,7 @@ int cpu_watchpoint_remove(CPUArchState *env, target_ulong addr, target_ulong len target_ulong len_mask = ~(len - 1); CPUWatchpoint *wp; - QTAILQ_FOREACH (wp, &env->watchpoints, entry) { + QTAILQ_FOREACH (wp, &env_cpu(env)->watchpoints, entry) { if (addr == wp->vaddr && len_mask == wp->len_mask && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) { cpu_watchpoint_remove_by_ref(env, wp); return 0; @@ -88,7 +88,7 @@ int cpu_watchpoint_remove(CPUArchState *env, target_ulong addr, target_ulong len /* Remove a specific watchpoint by reference. */ void cpu_watchpoint_remove_by_ref(CPUArchState *env, CPUWatchpoint *watchpoint) { - QTAILQ_REMOVE(&env->watchpoints, watchpoint, entry); + QTAILQ_REMOVE(&env_cpu(env)->watchpoints, watchpoint, entry); tlb_flush_page(env, watchpoint->vaddr); @@ -99,7 +99,7 @@ void cpu_watchpoint_remove_by_ref(CPUArchState *env, CPUWatchpoint *watchpoint) void cpu_watchpoint_remove_all(CPUArchState *env, int mask) { CPUWatchpoint *wp, *next; - QTAILQ_FOREACH_SAFE(wp, &env->watchpoints, entry, next) { + QTAILQ_FOREACH_SAFE(wp, &env_cpu(env)->watchpoints, entry, next) { if (wp->flags & mask) cpu_watchpoint_remove_by_ref(env, wp); } @@ -117,9 +117,9 @@ int cpu_breakpoint_insert(CPUArchState *env, target_ulong pc, int flags, CPUBrea /* keep all GDB-injected breakpoints in front */ if (flags & BP_GDB) - QTAILQ_INSERT_HEAD(&env->breakpoints, bp, entry); + QTAILQ_INSERT_HEAD(&env_cpu(env)->breakpoints, bp, entry); else - QTAILQ_INSERT_TAIL(&env->breakpoints, bp, entry); + QTAILQ_INSERT_TAIL(&env_cpu(env)->breakpoints, bp, entry); breakpoint_invalidate(env, pc); @@ -136,7 +136,7 @@ int cpu_breakpoint_remove(CPUArchState *env, target_ulong pc, int flags) { #if defined(TARGET_HAS_ICE) CPUBreakpoint *bp; - QTAILQ_FOREACH (bp, &env->breakpoints, entry) { + QTAILQ_FOREACH (bp, &env_cpu(env)->breakpoints, entry) { if (bp->pc == pc && bp->flags == flags) { cpu_breakpoint_remove_by_ref(env, bp); return 0; @@ -151,7 +151,7 @@ int cpu_breakpoint_remove(CPUArchState *env, target_ulong pc, int flags) { /* Remove a specific breakpoint by reference. */ void cpu_breakpoint_remove_by_ref(CPUArchState *env, CPUBreakpoint *breakpoint) { #if defined(TARGET_HAS_ICE) - QTAILQ_REMOVE(&env->breakpoints, breakpoint, entry); + QTAILQ_REMOVE(&env_cpu(env)->breakpoints, breakpoint, entry); breakpoint_invalidate(env, breakpoint->pc); @@ -164,7 +164,7 @@ void cpu_breakpoint_remove_all(CPUArchState *env, int mask) { #if defined(TARGET_HAS_ICE) CPUBreakpoint *bp, *next; - QTAILQ_FOREACH_SAFE(bp, &env->breakpoints, entry, next) { + QTAILQ_FOREACH_SAFE(bp, &env_cpu(env)->breakpoints, entry, next) { if (bp->flags & mask) cpu_breakpoint_remove_by_ref(env, bp); } @@ -175,8 +175,8 @@ void cpu_breakpoint_remove_all(CPUArchState *env, int mask) { CPU loop after each instruction */ void cpu_single_step(CPUArchState *env, int enabled) { #if defined(TARGET_HAS_ICE) - if (env->singlestep_enabled != enabled) { - env->singlestep_enabled = enabled; + if (env_cpu(env)->singlestep_enabled != enabled) { + env_cpu(env)->singlestep_enabled = enabled; /* must flush all the translated code to avoid inconsistencies */ /* XXX: only flush what is necessary */ @@ -194,7 +194,7 @@ static void check_watchpoint(int offset, int len_mask, int flags) { CPUWatchpoint *wp; int cpu_flags; - if (env->watchpoint_hit) { + if (env_cpu(env)->watchpoint_hit) { /* We re-entered the check after replacing the TB. Now raise * the debug interrupt so that is will trigger after the * current instruction. */ @@ -205,25 +205,25 @@ static void check_watchpoint(int offset, int len_mask, int flags) { #ifdef CONFIG_SYMBEX vaddr = (g_sqi.mem.read_mem_io_vaddr(1)) + offset; #else - vaddr = (env->mem_io_vaddr & TARGET_PAGE_MASK) + offset; + vaddr = (env_cpu(env)->mem_io_vaddr & TARGET_PAGE_MASK) + offset; #endif - QTAILQ_FOREACH (wp, &env->watchpoints, entry) { + QTAILQ_FOREACH (wp, &env_cpu(env)->watchpoints, entry) { if ((vaddr == (wp->vaddr & len_mask) || (vaddr & wp->len_mask) == wp->vaddr) && (wp->flags & flags)) { wp->flags |= BP_WATCHPOINT_HIT; - if (!env->watchpoint_hit) { - env->watchpoint_hit = wp; - tb = tcg_tb_lookup(env->mem_io_pc); + if (!env_cpu(env)->watchpoint_hit) { + env_cpu(env)->watchpoint_hit = wp; + tb = tcg_tb_lookup(env_cpu(env)->mem_io_pc); if (!tb) { cpu_abort(env, "check_watchpoint: could not find TB for " "pc=%p", - (void *) env->mem_io_pc); + (void *) env_cpu(env)->mem_io_pc); } - cpu_restore_state(env, env->mem_io_pc); + cpu_restore_state(env, env_cpu(env)->mem_io_pc); tb_phys_invalidate(tb, -1); if (wp->flags & BP_STOP_BEFORE_ACCESS) { - env->exception_index = EXCP_DEBUG; + env_cpu(env)->exception_index = EXCP_DEBUG; cpu_loop_exit(env); } else { cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags); diff --git a/libcpu/src/exec-tb.c b/libcpu/src/exec-tb.c index 0b476b232..28f3d7d3f 100644 --- a/libcpu/src/exec-tb.c +++ b/libcpu/src/exec-tb.c @@ -93,7 +93,8 @@ void tb_flush(CPUArchState *env) { g_sqi.tb.flush_tb_cache(); #endif - for (env = first_cpu; env != NULL; env = env->next_cpu) { + env = first_cpu; + if (env) { memset(env_cpu(env)->neg.tb_jmp_cache, 0, TB_JMP_CACHE_SIZE * sizeof(void *)); } @@ -207,7 +208,8 @@ void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr) { /* remove the TB from the hash list */ h = tb_jmp_cache_hash_func(tb->pc); - for (env = first_cpu; env != NULL; env = env->next_cpu) { + env = first_cpu; + if (env) { if (env_cpu(env)->neg.tb_jmp_cache[h] == tb) env_cpu(env)->neg.tb_jmp_cache[h] = NULL; } @@ -395,17 +397,17 @@ void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end, int if (current_tb_not_found) { current_tb_not_found = 0; current_tb = NULL; - if (env->mem_io_pc) { + if (env_cpu(env)->mem_io_pc) { /* now we have a real cpu fault */ - current_tb = tcg_tb_lookup(env->mem_io_pc); + current_tb = tcg_tb_lookup(env_cpu(env)->mem_io_pc); } else { #ifdef CONFIG_SYMBEX - env->se_tb_abort = 1; + env_cpu(env)->se_tb_abort = 1; #endif } } if (current_tb == tb && (current_tb->cflags & CF_COUNT_MASK) != 1) { - cpu_restore_state(env, env->mem_io_pc); + cpu_restore_state(env, env_cpu(env)->mem_io_pc); cpu_get_tb_cpu_state(env, ¤t_pc, ¤t_cs_base, ¤t_flags); // When an instruction modifies itself, advance pc to the next instruction @@ -414,7 +416,8 @@ void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end, int assert(instr_size); if (current_tb->pc + current_tb->size > env->eip + instr_size) { env->eip += instr_size; - tcg_target_force_tb_exit(env->mem_io_pc, (uintptr_t) (current_tb->tc.ptr + current_tb->tc.size)); + tcg_target_force_tb_exit(env_cpu(env)->mem_io_pc, + (uintptr_t) (current_tb->tc.ptr + current_tb->tc.size)); } } #endif /* TARGET_HAS_PRECISE_SMC */ @@ -422,15 +425,15 @@ void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end, int occurs while doing tb_phys_invalidate() */ saved_tb = NULL; if (env) { - saved_tb = env->current_tb; - env->current_tb = NULL; + saved_tb = env_cpu(env)->current_tb; + env_cpu(env)->current_tb = NULL; } tb_phys_invalidate(tb, -1); if (env) { - env->current_tb = saved_tb; + env_cpu(env)->current_tb = saved_tb; #if 0 - if (env->interrupt_request && env->current_tb) { - cpu_interrupt(env, env->interrupt_request); + if (env_cpu(env)->interrupt_request && env_cpu(env)->current_tb) { + cpu_interrupt(env, env_cpu(env)->interrupt_request); } #endif } @@ -446,7 +449,7 @@ void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end, int target_ulong iovaddr = g_sqi.mem.read_mem_io_vaddr(1); tlb_unprotect_code_phys(env, start, iovaddr); #else - tlb_unprotect_code_phys(env, start, env->mem_io_vaddr); + tlb_unprotect_code_phys(env, start, env_cpu(env)->mem_io_vaddr); #endif } } @@ -459,7 +462,7 @@ void tb_invalidate_phys_page_fast(tb_page_addr_t start, int len) { #if 0 if (1) { libcpu_log("modifying code at 0x%x size=%d EIP=%x PC=%08x\n", - cpu_single_env->mem_io_vaddr, len, + env_cpu(cpu_single_env)->mem_io_vaddr, len, cpu_single_env->eip, cpu_single_env->eip + (long)cpu_single_env->segs[R_CS].base); } diff --git a/libcpu/src/exec-tlb.c b/libcpu/src/exec-tlb.c index b9616486f..4f2b1386c 100644 --- a/libcpu/src/exec-tlb.c +++ b/libcpu/src/exec-tlb.c @@ -83,7 +83,7 @@ void tlb_flush(CPUArchState *env, int flush_global) { #endif /* must reset current TB so that interrupts cannot modify the links while we are modifying them */ - env->current_tb = NULL; + env_cpu(env)->current_tb = NULL; int mmu_idx; CPUTLB *tlb = env_tlb(env); @@ -126,7 +126,7 @@ void tlb_flush_page(CPUArchState *env, target_ulong addr) { } /* must reset current TB so that interrupts cannot modify the links while we are modifying them */ - env->current_tb = NULL; + env_cpu(env)->current_tb = NULL; addr &= TARGET_PAGE_MASK; i = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); @@ -241,7 +241,7 @@ void tlb_set_page(CPUArchState *env, target_ulong vaddr, target_phys_addr_t padd code_address = address; /* Make accesses to pages with watchpoints go via the watchpoint trap routines. */ - QTAILQ_FOREACH (wp, &env->watchpoints, entry) { + QTAILQ_FOREACH (wp, &env_cpu(env)->watchpoints, entry) { if (vaddr == (wp->vaddr & TARGET_PAGE_MASK)) { /* Avoid trapping reads of pages with a write breakpoint. */ if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) { diff --git a/libcpu/src/exec.c b/libcpu/src/exec.c index 66cc5d5f0..64a71a888 100644 --- a/libcpu/src/exec.c +++ b/libcpu/src/exec.c @@ -72,36 +72,42 @@ void cpu_exec_init_all(void) { } void cpu_exec_init(CPUArchState *env) { - CPUArchState **penv; - int cpu_index; - - env->next_cpu = NULL; - penv = &first_cpu; - cpu_index = 0; - while (*penv != NULL) { - penv = &(*penv)->next_cpu; - cpu_index++; - } - env->cpu_index = cpu_index; - env->numa_node = 0; - QTAILQ_INIT(&env->breakpoints); - QTAILQ_INIT(&env->watchpoints); - *penv = env; + CPUState *cpu = env_cpu(env); + + /* libcpu emulates exactly one CPU. */ + assert(first_cpu == NULL); + first_cpu = env; + + cpu->cpu_index = 0; + QTAILQ_INIT(&cpu->breakpoints); + QTAILQ_INIT(&cpu->watchpoints); +} + +void cpu_common_reset(CPUState *cpu) { + cpu->current_tb = NULL; + cpu->se_current_tb = NULL; + cpu->mem_io_pc = 0; + cpu->mem_io_vaddr = 0; + cpu->translate_single_instruction = 0; + cpu->halted = 0; + cpu->interrupt_request = 0; + cpu->exit_request = 0; + cpu->se_tb_abort = 0; } /* mask must never be zero, except for A20 change call */ static void tcg_handle_interrupt(CPUArchState *env, int mask) { - env->interrupt_request |= mask; + env_cpu(env)->interrupt_request |= mask; } CPUInterruptHandler cpu_interrupt_handler = tcg_handle_interrupt; void cpu_reset_interrupt(CPUArchState *env, int mask) { - env->interrupt_request &= ~mask; + env_cpu(env)->interrupt_request &= ~mask; } void cpu_exit(CPUArchState *env) { - env->exit_request = 1; + env_cpu(env)->exit_request = 1; } void cpu_abort(CPUArchState *env, const char *fmt, ...) { @@ -158,7 +164,8 @@ void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t end, int dirty abort(); } - for (env = first_cpu; env != NULL; env = env->next_cpu) { + env = first_cpu; + if (env) { int mmu_idx; for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { for (i = 0; i < CPU_TLB_SIZE; i++) @@ -233,7 +240,7 @@ static void notdirty_mem_write(target_phys_addr_t ram_addr, uint64_t val, unsign target_ulong iovaddr = g_sqi.mem.read_mem_io_vaddr(1); tlb_set_dirty(cpu_single_env, iovaddr); #else - tlb_set_dirty(cpu_single_env, cpu_single_env->mem_io_vaddr); + tlb_set_dirty(cpu_single_env, env_cpu(cpu_single_env)->mem_io_vaddr); #endif } } diff --git a/libcpu/src/softmmu_template.h b/libcpu/src/softmmu_template.h index ff6641673..ccd1664b9 100644 --- a/libcpu/src/softmmu_template.h +++ b/libcpu/src/softmmu_template.h @@ -94,7 +94,7 @@ #define INSTR_FORK_AND_CONCRETIZE(val, max) (val) #define SE_SET_MEM_IO_VADDR(env, addr, reset) \ - env->mem_io_vaddr = addr; + env_cpu(env)->mem_io_vaddr = addr; #endif // SYMBEX_LLVM_LIB @@ -115,7 +115,7 @@ #define SE_RAM_OBJECT_MASK TARGET_PAGE_MASK #define SE_RAM_OBJECT_DIFF 0 -#define SE_SET_MEM_IO_VADDR(env, addr, reset) env->mem_io_vaddr = addr; +#define SE_SET_MEM_IO_VADDR(env, addr, reset) env_cpu(env)->mem_io_vaddr = addr; #endif // CONFIG_SYMBEX @@ -164,7 +164,7 @@ DATA_TYPE glue(glue(io_read, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_ } #endif - env->mem_io_pc = (uintptr_t) retaddr; + env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; SE_SET_MEM_IO_VADDR(env, addr, 0); #if SHIFT <= 2 @@ -206,7 +206,7 @@ DATA_TYPE glue(glue(io_read_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_p target_ulong naddr = (physaddr & TARGET_PAGE_MASK) + addr; // If it is not DMA, then check if it is normal memory - env->mem_io_pc = (uintptr_t) retaddr; + env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; SE_SET_MEM_IO_VADDR(env, addr, 0); #if SHIFT <= 2 @@ -438,7 +438,7 @@ void glue(glue(io_write, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr #endif SE_SET_MEM_IO_VADDR(env, addr, 0); - env->mem_io_pc = (uintptr_t) retaddr; + env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; #if SHIFT <= 2 ops->write(physaddr, val, 1 << SHIFT); #else @@ -475,7 +475,7 @@ void glue(glue(io_write_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_ physaddr = (physaddr & TARGET_PAGE_MASK) + addr; SE_SET_MEM_IO_VADDR(env, addr, 0); - env->mem_io_pc = (uintptr_t) retaddr; + env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; #if SHIFT <= 2 if (se_ismemfunc(ops, 1)) { uintptr_t pa = se_notdirty_mem_write(physaddr, 1 << SHIFT); diff --git a/libcpu/src/target-i386/cpu.h b/libcpu/src/target-i386/cpu.h index 3a0ab9759..462dd7a65 100644 --- a/libcpu/src/target-i386/cpu.h +++ b/libcpu/src/target-i386/cpu.h @@ -280,7 +280,7 @@ static inline void cpu_x86_load_seg_cache_sipi(CPUX86State *env, int sipi_vector env->eip = 0; cpu_x86_load_seg_cache(env, R_CS, sipi_vector << 8, sipi_vector << 12, env->segs[R_CS].limit, env->segs[R_CS].flags); - env->halted = 0; + env_cpu(env)->halted = 0; } int cpu_x86_get_descr_debug(CPUX86State *env, unsigned int selector, target_ulong *base, unsigned int *limit, diff --git a/libcpu/src/target-i386/helper.c b/libcpu/src/target-i386/helper.c index a3525d9bd..fed652b00 100644 --- a/libcpu/src/target-i386/helper.c +++ b/libcpu/src/target-i386/helper.c @@ -158,11 +158,12 @@ void cpu_state_reset(CPUX86State *env) { int i; if (libcpu_loglevel_mask(CPU_LOG_RESET)) { - libcpu_log("CPU Reset (CPU %d)\n", env->cpu_index); + libcpu_log("CPU Reset (CPU %d)\n", env_cpu(env)->cpu_index); log_cpu_state(env, X86_DUMP_FPU | X86_DUMP_CCOP); } - memset(env, 0, offsetof(CPUX86State, breakpoints)); + memset(env, 0, offsetof(CPUX86State, size)); + cpu_common_reset(env_cpu(env)); cpu_init_fp_statuses(env); @@ -350,7 +351,7 @@ void cpu_dump_state(CPUX86State *env, FILE *f, fprintf_function cpu_fprintf, int eflags & CC_O ? 'O' : '-', eflags & CC_S ? 'S' : '-', eflags & CC_Z ? 'Z' : '-', eflags & CC_A ? 'A' : '-', eflags & CC_P ? 'P' : '-', eflags & CC_C ? 'C' : '-', env->hflags & HF_CPL_MASK, (env->hflags >> HF_INHIBIT_IRQ_SHIFT) & 1, (env->a20_mask >> 20) & 1, - (env->hflags >> HF_SMM_SHIFT) & 1, env->halted); + (env->hflags >> HF_SMM_SHIFT) & 1, env_cpu(env)->halted); } else #endif { @@ -365,7 +366,7 @@ void cpu_dump_state(CPUX86State *env, FILE *f, fprintf_function cpu_fprintf, int eflags, eflags & DF_MASK ? 'D' : '-', eflags & CC_O ? 'O' : '-', eflags & CC_S ? 'S' : '-', eflags & CC_Z ? 'Z' : '-', eflags & CC_A ? 'A' : '-', eflags & CC_P ? 'P' : '-', eflags & CC_C ? 'C' : '-', env->hflags & HF_CPL_MASK, (env->hflags >> HF_INHIBIT_IRQ_SHIFT) & 1, - (env->a20_mask >> 20) & 1, (env->hflags >> HF_SMM_SHIFT) & 1, env->halted); + (env->a20_mask >> 20) & 1, (env->hflags >> HF_SMM_SHIFT) & 1, env_cpu(env)->halted); } } @@ -615,7 +616,7 @@ int cpu_x86_handle_mmu_fault(CPUX86State *env, target_ulong addr, int is_write1, sext = (int64_t) addr >> 47; if (sext != 0 && sext != -1) { env->error_code = 0; - env->exception_index = EXCP0D_GPF; + env_cpu(env)->exception_index = EXCP0D_GPF; return 1; } @@ -848,7 +849,7 @@ int cpu_x86_handle_mmu_fault(CPUX86State *env, target_ulong addr, int is_write1, env->cr[2] = addr; } env->error_code = error_code; - env->exception_index = EXCP0E_PAGE; + env_cpu(env)->exception_index = EXCP0E_PAGE; return 1; } @@ -1011,16 +1012,16 @@ static CPUDebugExcpHandler *prev_debug_excp_handler; static void breakpoint_handler(CPUX86State *env) { CPUBreakpoint *bp; - if (env->watchpoint_hit) { - if (env->watchpoint_hit->flags & BP_CPU) { - env->watchpoint_hit = NULL; + if (env_cpu(env)->watchpoint_hit) { + if (env_cpu(env)->watchpoint_hit->flags & BP_CPU) { + env_cpu(env)->watchpoint_hit = NULL; if (check_hw_breakpoints(env, 0)) raise_exception(env, EXCP01_DB); else cpu_resume_from_signal(env, NULL); } } else { - QTAILQ_FOREACH (bp, &env->breakpoints, entry) + QTAILQ_FOREACH (bp, &env_cpu(env)->breakpoints, entry) if (bp->pc == env->eip) { if (bp->flags & BP_CPU) { check_hw_breakpoints(env, 1); @@ -1093,7 +1094,7 @@ CPUX86State *cpu_x86_init(const cpuid_t *cpuid) { env->cpuid = *cpuid; - env->cpuid.cpuid_apic_id = env->cpu_index; + env->cpuid.cpuid_apic_id = env_cpu(env)->cpu_index; mce_init(env); qemu_init_vcpu(env); @@ -1104,17 +1105,17 @@ CPUX86State *cpu_x86_init(const cpuid_t *cpuid) { void do_cpu_init(CPUX86State *env1) { extern CPUX86State *env; env = env1; - int sipi = env->interrupt_request & CPU_INTERRUPT_SIPI; + int sipi = env_cpu(env)->interrupt_request & CPU_INTERRUPT_SIPI; uint64_t pat = env->pat; cpu_state_reset(env); - env->interrupt_request = sipi; + env_cpu(env)->interrupt_request = sipi; env->pat = pat; - env->halted = !cpu_is_bsp(env); + env_cpu(env)->halted = !cpu_is_bsp(env); } int cpu_is_bsp(CPUX86State *env) { - return env->cpu_index == 0; + return env_cpu(env)->cpu_index == 0; } const void *helper_lookup_tb_ptr(CPUArchState *env) { diff --git a/libcpu/src/target-i386/op_helper.c b/libcpu/src/target-i386/op_helper.c index edbb70f00..f76ddd51a 100644 --- a/libcpu/src/target-i386/op_helper.c +++ b/libcpu/src/target-i386/op_helper.c @@ -1567,7 +1567,7 @@ void do_interrupt(CPUX86State *env) { /* simulate a real cpu exception. On i386, it can trigger new exceptions, but we do not handle double or triple faults yet. */ - do_interrupt_all(env->exception_index, env->exception_is_int, env->error_code, env->exception_next_eip, 0); + do_interrupt_all(env_cpu(env)->exception_index, env->exception_is_int, env->error_code, env->exception_next_eip, 0); /* successfully delivered */ env->old_exception = -1; } @@ -1629,7 +1629,7 @@ static void LIBCPU_NORETURN raise_interrupt2(CPUX86State *env, int intno, int is helper_svm_check_intercept_param(SVM_EXIT_SWINT, 0); } - env->exception_index = intno; + env_cpu(env)->exception_index = intno; env->error_code = error_code; env->exception_is_int = is_int; env->exception_next_eip = env->eip + next_eip_addend; @@ -4815,8 +4815,8 @@ void helper_idivq_EAX(target_ulong t0) { static void do_hlt(void) { env->hflags &= ~HF_INHIBIT_IRQ_MASK; /* needed if sti is just before */ - env->halted = 1; - env->exception_index = EXCP_HLT; + env_cpu(env)->halted = 1; + env_cpu(env)->exception_index = EXCP_HLT; cpu_loop_exit(env); } @@ -4841,7 +4841,7 @@ void helper_mwait(int next_eip_addend) { EIP += next_eip_addend; /* XXX: not complete but not completely erroneous */ - if (env->cpu_index != 0 || env->next_cpu != NULL) { + if (env_cpu(env)->cpu_index != 0) { /* more than one CPU: do not sleep because another CPU may wake this one */ } else { @@ -4850,7 +4850,7 @@ void helper_mwait(int next_eip_addend) { } void helper_debug(void) { - env->exception_index = EXCP_DEBUG; + env_cpu(env)->exception_index = EXCP_DEBUG; cpu_loop_exit(env); } @@ -4999,7 +4999,7 @@ void tlb_fill(CPUX86State *env1, target_ulong addr, target_ulong page_addr, int /* In symbex mode, pass page address instead of addr to cpu_x86_handle_mmu_fault, since the latter can be symbolic while the former is always concrete. To compensate, we reset fault address here. */ - if (env->exception_index == EXCP0E_PAGE) { + if (env_cpu(env)->exception_index == EXCP0E_PAGE) { if (env->intercept_exceptions & (1 << EXCP0E_PAGE)) stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), addr); else @@ -5012,7 +5012,7 @@ void tlb_fill(CPUX86State *env1, target_ulong addr, target_ulong page_addr, int g_sqi.events.on_page_fault(addr, is_write, retaddr); } #endif - raise_exception_err_ra(env, env->exception_index, env->error_code, (uintptr_t) retaddr); + raise_exception_err_ra(env, env_cpu(env)->exception_index, env->error_code, (uintptr_t) retaddr); } } #endif @@ -5159,7 +5159,7 @@ void helper_vmrun(int aflag, int next_eip_addend) { env->hflags2 |= HF2_GIF_MASK; if (int_ctl & V_IRQ_MASK) { - env->interrupt_request |= CPU_INTERRUPT_VIRQ; + env_cpu(env)->interrupt_request |= CPU_INTERRUPT_VIRQ; } #if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) @@ -5179,7 +5179,7 @@ void helper_vmrun(int aflag, int next_eip_addend) { /* FIXME: need to implement valid_err */ switch (event_inj & SVM_EVTINJ_TYPE_MASK) { case SVM_EVTINJ_TYPE_INTR: - env->exception_index = vector; + env_cpu(env)->exception_index = vector; env->error_code = event_inj_err; env->exception_is_int = 0; env->exception_next_eip = -1; @@ -5188,7 +5188,7 @@ void helper_vmrun(int aflag, int next_eip_addend) { do_interrupt_all(vector, 0, 0, 0, 1); break; case SVM_EVTINJ_TYPE_NMI: - env->exception_index = EXCP02_NMI; + env_cpu(env)->exception_index = EXCP02_NMI; env->error_code = event_inj_err; env->exception_is_int = 0; env->exception_next_eip = EIP; @@ -5196,7 +5196,7 @@ void helper_vmrun(int aflag, int next_eip_addend) { cpu_loop_exit(env); break; case SVM_EVTINJ_TYPE_EXEPT: - env->exception_index = vector; + env_cpu(env)->exception_index = vector; env->error_code = event_inj_err; env->exception_is_int = 0; env->exception_next_eip = -1; @@ -5204,7 +5204,7 @@ void helper_vmrun(int aflag, int next_eip_addend) { cpu_loop_exit(env); break; case SVM_EVTINJ_TYPE_SOFT: - env->exception_index = vector; + env_cpu(env)->exception_index = vector; env->error_code = event_inj_err; env->exception_is_int = 1; env->exception_next_eip = EIP; @@ -5212,7 +5212,7 @@ void helper_vmrun(int aflag, int next_eip_addend) { cpu_loop_exit(env); break; } - libcpu_log_mask(CPU_LOG_TB_IN_ASM, " %#x %#x\n", env->exception_index, env->error_code); + libcpu_log_mask(CPU_LOG_TB_IN_ASM, " %#x %#x\n", env_cpu(env)->exception_index, env->error_code); } } @@ -5437,7 +5437,7 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1) { int_ctl = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl)); int_ctl &= ~(V_TPR_MASK | V_IRQ_MASK); int_ctl |= (cpu_apic_get_tpr(env) >> 4) & V_TPR_MASK; - if (env->interrupt_request & CPU_INTERRUPT_VIRQ) + if (env_cpu(env)->interrupt_request & CPU_INTERRUPT_VIRQ) int_ctl |= V_IRQ_MASK; stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl), int_ctl); @@ -5454,7 +5454,7 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1) { env->hflags &= ~HF_SVMI_MASK; env->intercept = 0; env->intercept_exceptions = 0; - env->interrupt_request &= ~CPU_INTERRUPT_VIRQ; + env_cpu(env)->interrupt_request &= ~CPU_INTERRUPT_VIRQ; env->tsc_offset = 0; env->gdt.base = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.base)); @@ -5523,7 +5523,7 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1) { #GP fault is delivered inside the host.) */ /* remove any pending exception */ - env->exception_index = -1; + env_cpu(env)->exception_index = -1; env->error_code = 0; env->old_exception = -1; diff --git a/libcpu/src/target-i386/translate.c b/libcpu/src/target-i386/translate.c index 74b47d437..9286b3516 100644 --- a/libcpu/src/target-i386/translate.c +++ b/libcpu/src/target-i386/translate.c @@ -7714,7 +7714,8 @@ static inline void gen_tb_start(TranslationBlock *tb) { tcg_ctx->exitreq_label = gen_new_label(); exit_request = tcg_temp_new_i32(); - tcg_gen_ld_i32(exit_request, tcg_env, offsetof(CPUArchState, exit_request)); + tcg_gen_ld_i32(exit_request, tcg_env, + (int) offsetof(ArchCPU, parent_obj.exit_request) - (int) offsetof(ArchCPU, env)); tcg_gen_brcondi_i32(TCG_COND_NE, exit_request, 0, tcg_ctx->exitreq_label); } @@ -7757,7 +7758,7 @@ static inline void gen_intermediate_code_internal(CPUX86State *env, TranslationB dc->cpl = (flags >> HF_CPL_SHIFT) & 3; dc->iopl = (flags >> IOPL_SHIFT) & 3; dc->tf = (flags >> TF_SHIFT) & 1; - dc->singlestep_enabled = env->singlestep_enabled; + dc->singlestep_enabled = env_cpu(env)->singlestep_enabled; dc->cc_op = CC_OP_DYNAMIC; dc->cs_base = cs_base; dc->tb = tb; @@ -7779,7 +7780,7 @@ static inline void gen_intermediate_code_internal(CPUX86State *env, TranslationB dc->code64 = (flags >> HF_CS64_SHIFT) & 1; #endif dc->flags = flags; - dc->jmp_opt = !(dc->tf || env->singlestep_enabled || (flags & HF_INHIBIT_IRQ_MASK) + dc->jmp_opt = !(dc->tf || env_cpu(env)->singlestep_enabled || (flags & HF_INHIBIT_IRQ_MASK) #ifndef CONFIG_SOFTMMU || (flags & HF_SOFTMMU_MASK) #endif @@ -7822,7 +7823,8 @@ static inline void gen_intermediate_code_internal(CPUX86State *env, TranslationB temporary one in case we regenerate LLVM bitcode */ #ifndef STATIC_TRANSLATOR tcg_gen_movi_i64(cpu_tmp1_i64, (uint64_t) tb); - tcg_gen_st_i64(cpu_tmp1_i64, tcg_env, offsetof(CPUArchState, se_current_tb)); + tcg_gen_st_i64(cpu_tmp1_i64, tcg_env, + (int) offsetof(ArchCPU, parent_obj.se_current_tb) - (int) offsetof(ArchCPU, env)); if (unlikely(*g_sqi.events.on_translate_block_start_signals_count && dc->instrument)) { g_sqi.events.on_translate_block_start(dc, tb, pc_start); @@ -7831,8 +7833,8 @@ static inline void gen_intermediate_code_internal(CPUX86State *env, TranslationB #endif for (;;) { - if (unlikely(!QTAILQ_EMPTY(&env->breakpoints))) { - QTAILQ_FOREACH (bp, &env->breakpoints, entry) { + if (unlikely(!QTAILQ_EMPTY(&env_cpu(env)->breakpoints))) { + QTAILQ_FOREACH (bp, &env_cpu(env)->breakpoints, entry) { if (bp->pc == pc_ptr && !((bp->flags & BP_CPU) && (tb->flags & HF_RF_MASK))) { gen_debug(dc, pc_ptr - dc->cs_base); break; @@ -7884,7 +7886,8 @@ static inline void gen_intermediate_code_internal(CPUX86State *env, TranslationB /* if irq were inhibited with HF_INHIBIT_IRQ_MASK, we clear the flag and abort the translation to give the irqs a change to be happen */ - if (dc->tf || dc->singlestep_enabled || (flags & HF_INHIBIT_IRQ_MASK) || env->translate_single_instruction) { + if (dc->tf || dc->singlestep_enabled || (flags & HF_INHIBIT_IRQ_MASK) || + env_cpu(env)->translate_single_instruction) { gen_jmp_im(dc, pc_ptr - dc->cs_base); #ifdef CONFIG_SYMBEX gen_eob_event(dc, 1, pc_ptr - dc->cs_base); diff --git a/libcpu/src/translate-all.c b/libcpu/src/translate-all.c index 4f13bb4b0..49319b8fd 100644 --- a/libcpu/src/translate-all.c +++ b/libcpu/src/translate-all.c @@ -111,7 +111,7 @@ static void cpu_gen_init(TCGContext *ctx) { #ifdef CONFIG_SYMBEX ctx->tlbe_offset_symbex_addend = offsetof(CPUTLBEntry, se_addend); - ctx->env_offset_se_tb_abort = offsetof(CPUArchState, se_tb_abort); + ctx->env_offset_se_tb_abort = (int) offsetof(ArchCPU, parent_obj.se_tb_abort) - (int) offsetof(ArchCPU, env); #endif ctx->target_page_bits = TARGET_PAGE_BITS; @@ -243,7 +243,7 @@ int cpu_gen_code(CPUArchState *env, TranslationBlock *tb) { tb->tc.size = gen_code_size; #if defined(CONFIG_SYMBEX_MP) || defined(STATIC_TRANSLATOR) - if (env->generate_llvm) { + if (env_cpu(env)->generate_llvm) { assert(tb->llvm_function == NULL); tb->llvm_function = tcg_llvm_gen_code(tcg_llvm_translator, s, tb); g_sqi.tb.set_tb_function(tb->se_tb, tb->llvm_function); diff --git a/libcpu/tlb-update.md b/libcpu/tlb-update.md index 5b56953a3..d7468761a 100644 --- a/libcpu/tlb-update.md +++ b/libcpu/tlb-update.md @@ -21,6 +21,13 @@ import a drop-in. Estimated effort: 1.5-2 weeks. +**Status: landed.** Steps 0, 1, 2, 4 and 6 are in the tree. Steps 3 and 5 are +test-only and were not run. The follow-up that section 1 defers to +`PORTING.md` phase 4, moving the per-state execution fields out of +`CPUX86State`, has landed as well: `CPUState` now holds them ahead of the +caches, libs2ecore registers them as a separate snapshotted object, and the +`se_common_start` / `se_common_end` window is gone. + ## 1. Target shape @@ -75,11 +82,13 @@ Two KLEE objects over the CPU, as today, plus one for the caches: | `[env + offsetof(eip), env + sizeof(CPUX86State))` | shared concrete | yes (explicit memcpy) | | `[&g_cpu, &g_cpu.env)`, the caches | shared concrete | **no** | -During this work `CPUState` holds *only* the caches. When the port later moves -per-state execution fields (`interrupt_request`, `exception_index`, `halted`, -`jmp_env`) into the slim `CPUState`, they must not silently inherit this -never-snapshotted region; the snapshot boundary has to be revisited at that -point (`PORTING.md` phase 4). +During this work `CPUState` held *only* the caches. The per-state execution +fields (`interrupt_request`, `exception_index`, `halted`, `jmp_env`, ...) +followed afterwards, and they did not inherit the never-snapshotted region: +`CPUState` is now split at `neg` into a fourth object, +`[&g_cpu, &g_cpu.parent_obj.neg)`, shared concrete and snapshotted by the same +explicit memcpy as the concrete registers, with the caches keeping the row +above. **The caches must stay KLEE-visible even though they are never snapshotted.** `use-fast-helpers` defaults to *off*, so `replaceExternalFunctionsWithSpecialHandlers()` @@ -250,13 +259,13 @@ Exit: testsuite green. ### Step 6: Cleanups this enables (half a day) -- `compareArchitecturalConcreteState()` currently does two `memcmp`s to skip the - `se_common_start` .. `se_common_end` window. That window does *not* exist only - for the caches: it also hides `current_tb`, `jmp_env`, the breakpoint and - watchpoint list heads, `opaque`, `temp_buf` and friends, which remain in - `CPUX86State` after this work. The window shrinks, but the two-`memcmp` shape - and the marker fields stay; they can only be deleted once the full port moves - the rest of `CPU_COMMON` into the slim `CPUState`. +- `compareArchitecturalConcreteState()` did two `memcmp`s to skip the + `se_common_start` .. `se_common_end` window. That window did *not* exist only + for the caches: it also hid `current_tb`, `jmp_env`, the breakpoint and + watchpoint list heads, `opaque`, `temp_buf` and friends. With the rest of + `CPU_COMMON` moved into the slim `CPUState`, the window and the marker + fields are gone and the comparison is a single `memcmp` over + `[eip, sizeof(CPUX86State))`. - State merging becomes strictly more permissive as a side effect: it stops comparing cache contents that were never architecturally meaningful. (The `tlb_flush(env, 1)` that `MergingSearcher` performs before merging becomes diff --git a/libs2e/src/s2e-kvm-io.cpp b/libs2e/src/s2e-kvm-io.cpp index 36b20c18d..e3da7cdb1 100644 --- a/libs2e/src/s2e-kvm-io.cpp +++ b/libs2e/src/s2e-kvm-io.cpp @@ -58,19 +58,19 @@ static void signal_ioeventfd(int fd) { // an I/O operation (e.g., VAPIC emulation). static void abort_and_retranslate_if_needed() { #ifdef ENABLE_RETRANSLATE - if (env->se_current_tb->icount == 1) { + if (env_cpu(env)->se_current_tb->icount == 1) { return; } - if (cpu_restore_state(env->se_current_tb, env, env->mem_io_pc)) { + if (cpu_restore_state(env_cpu(env)->se_current_tb, env, env_cpu(env)->mem_io_pc)) { abort(); } libcpu_log("Aborting and retranslating at eip=%#lx\n", (uint64_t) env->eip); - env->translate_single_instruction = 1; - env->exception_index = -1; - tb_phys_invalidate(env->se_current_tb, -1); + env_cpu(env)->translate_single_instruction = 1; + env_cpu(env)->exception_index = -1; + tb_phys_invalidate(env_cpu(env)->se_current_tb, -1); cpu_loop_exit(env); #endif } diff --git a/libs2e/src/s2e-kvm-vcpu.cpp b/libs2e/src/s2e-kvm-vcpu.cpp index 2a43548ba..6f552e5d6 100644 --- a/libs2e/src/s2e-kvm-vcpu.cpp +++ b/libs2e/src/s2e-kvm-vcpu.cpp @@ -69,19 +69,19 @@ int cpu_get_pic_interrupt(CPUX86State *env) { // The interrupt injected by the kvm client goes first, like in KVM. // An interrupt of the lapic keeps its own request and is taken next. if (env->kvm_irq >= 0) { - assert(env->interrupt_request & CPU_INTERRUPT_HARD_EXT); + assert(env_cpu(env)->interrupt_request & CPU_INTERRUPT_HARD_EXT); auto irq = env->kvm_irq; env->kvm_irq = -1; - env->interrupt_request &= ~CPU_INTERRUPT_HARD_EXT; + env_cpu(env)->interrupt_request &= ~CPU_INTERRUPT_HARD_EXT; return irq; } - assert(!(env->interrupt_request & CPU_INTERRUPT_HARD_EXT)); + assert(!(env_cpu(env)->interrupt_request & CPU_INTERRUPT_HARD_EXT)); auto vcpu = s2e::kvm::VCPU::current(); if (auto apic = vcpu->lapic()) { // The vector moves to ISR, which masks what is left in IRR until the EOI - env->interrupt_request &= ~CPU_INTERRUPT_HARD_APIC; + env_cpu(env)->interrupt_request &= ~CPU_INTERRUPT_HARD_APIC; return apic->get_interrupt(); } @@ -327,7 +327,7 @@ void VCPU::coroutineFcn(void *opaque) { libcpu_run_all_timers(); - assert(env->current_tb == NULL); + assert(env_cpu(env)->current_tb == NULL); env->kvm_request_interrupt_window |= buffer->request_interrupt_window; @@ -335,9 +335,9 @@ void VCPU::coroutineFcn(void *opaque) { cpu_x86_exec(env); vcpu->m_cpuStateIsPrecise = true; - assert(env->current_tb == NULL); + assert(env_cpu(env)->current_tb == NULL); - env->exception_index = 0; + env_cpu(env)->exception_index = 0; coroutine_yield(); } } @@ -444,7 +444,7 @@ int VCPU::run(int vcpu_fd) { m_cpuBuffer->exit_reason == KVM_EXIT_IOAPIC_EOI; // Might not be NULL if resuming from an interrupted I/O - // assert(env->current_tb == NULL); + // assert(env_cpu(env)->current_tb == NULL); m_cpuBuffer->if_flag = (m_env->mflags & IF_MASK) != 0; m_cpuBuffer->apic_base = get_apic_base(); @@ -453,7 +453,7 @@ int VCPU::run(int vcpu_fd) { m_cpuBuffer->ready_for_interrupt_injection = ready_for_interrupt_injection(); if (m_cpuBuffer->exit_reason == -1) { - if (m_env->halted) { + if (env_cpu(m_env)->halted) { m_cpuBuffer->exit_reason = KVM_EXIT_HLT; } else if (m_cpuBuffer->ready_for_interrupt_injection) { m_cpuBuffer->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN; @@ -565,21 +565,21 @@ int VCPU::interrupt(kvm_interrupt *interrupt) { return -EEXIST; } - assert(!(m_env->interrupt_request & CPU_INTERRUPT_HARD_EXT)); + assert(!(env_cpu(m_env)->interrupt_request & CPU_INTERRUPT_HARD_EXT)); // External interrupts are not subject to the tpr of the in-kernel lapic if (!m_lapic && (m_env->cr[0] & CR0_PE_MASK)) { assert(interrupt->irq > get_tpr()); } - m_env->interrupt_request |= CPU_INTERRUPT_HARD_EXT; + env_cpu(m_env)->interrupt_request |= CPU_INTERRUPT_HARD_EXT; m_env->kvm_irq = interrupt->irq; return 0; } int VCPU::nmi() { - m_env->interrupt_request |= CPU_INTERRUPT_NMI; + env_cpu(m_env)->interrupt_request |= CPU_INTERRUPT_NMI; return 0; } @@ -1004,9 +1004,9 @@ void VCPU::interrupt(int mask, bool reset) { assert(!(mask & CPU_INTERRUPT_HARD_EXT)); if (reset) { - m_env->interrupt_request &= ~mask; + env_cpu(m_env)->interrupt_request &= ~mask; } else { - m_env->interrupt_request |= mask; + env_cpu(m_env)->interrupt_request |= mask; } } } // namespace kvm diff --git a/libs2ecore/include/s2e/S2EExecutionStateRegisters.h b/libs2ecore/include/s2e/S2EExecutionStateRegisters.h index 03ee226b7..6d60e3289 100644 --- a/libs2ecore/include/s2e/S2EExecutionStateRegisters.h +++ b/libs2ecore/include/s2e/S2EExecutionStateRegisters.h @@ -61,15 +61,23 @@ class S2EExecutionStateRegisters { static klee::ObjectKey s_symbolicRegs; static klee::ObjectKey s_concreteRegs; - // The CPU caches (TLB, RAM TLB, TB jump cache), i.e., the CPUState part - // of the global ArchCPU that precedes CPUX86State (see cpu/state.h). - // The region is registered so that the bitcode softmmu fast path can - // resolve it, but it is never snapshotted: the active state owns the - // global copy and doStateSwitch() flushes it on every switch. + // The CPUState that precedes CPUX86State in the global ArchCPU is split + // in two objects (see cpu/state.h). + // + // The execution fields (exception_index, interrupt_request, the current + // TB, ...) are per-state and snapshotted together with the concrete + // registers. + static klee::ObjectKey s_cpuExecState; + + // The CPU caches (TLB, RAM TLB, TB jump cache) are registered so that + // the bitcode softmmu fast path can resolve them, but never snapshotted: + // the active state owns the global copy and doStateSwitch() flushes it + // on every switch. static klee::ObjectKey s_cpuCaches; klee::ObjectStatePtr m_symbolicRegs; klee::ObjectStatePtr m_concreteRegs; + klee::ObjectStatePtr m_cpuExecState; const bool *m_active; const bool *m_runningConcrete; @@ -109,7 +117,8 @@ class S2EExecutionStateRegisters { m_concretizer(concretizer) {}; void initialize(klee::AddressSpace &addressSpace, const klee::ObjectStatePtr &symbolicRegs, - const klee::ObjectStatePtr &concreteRegs, const klee::ObjectStatePtr &cpuCaches); + const klee::ObjectStatePtr &concreteRegs, const klee::ObjectStatePtr &cpuExecState, + const klee::ObjectStatePtr &cpuCaches); void update(klee::AddressSpace &addressSpace, const bool *active, const bool *running_concrete, klee::IAddressSpaceNotification *notification, klee::IConcretizer *concretizer); @@ -118,12 +127,17 @@ class S2EExecutionStateRegisters { int compareArchitecturalConcreteState(const S2EExecutionStateRegisters &other); + /// Copies the concrete registers and the CPU execution fields of the + /// active state into this state's snapshot buffers. inline void saveConcreteState() { memcpy((void *) m_concreteRegs->getConcreteBuffer(), (void *) s_concreteRegs.address, s_concreteRegs.size); + memcpy((void *) m_cpuExecState->getConcreteBuffer(), (void *) s_cpuExecState.address, s_cpuExecState.size); } + /// Copies this state's snapshot buffers back into the global CPU. inline void restoreConcreteState() { memcpy((void *) s_concreteRegs.address, (void *) m_concreteRegs->getConcreteBuffer(), s_concreteRegs.size); + memcpy((void *) s_cpuExecState.address, (void *) m_cpuExecState->getConcreteBuffer(), s_cpuExecState.size); } bool addressSpaceChange(const klee::ObjectKey &key, const klee::ObjectStateConstPtr &oldState, @@ -133,6 +147,10 @@ class S2EExecutionStateRegisters { return s_concreteRegs; } + static const klee::ObjectKey &getCpuExecStateKey() { + return s_cpuExecState; + } + static const klee::ObjectKey &getCpuCachesKey() { return s_cpuCaches; } @@ -145,9 +163,15 @@ class S2EExecutionStateRegisters { /// the global CPUState object if active. CPUX86State *getCpuState() const; - /// Returns a pointer to the global CPU caches (the CPUState part of - /// ArchCPU). Only the active state has a TLB, so this aborts when the - /// state is inactive. + /// Returns a pointer to the CPU execution fields (CPUState). For the + /// active state this is the global CPU; for an inactive state it is the + /// snapshot buffer, which only covers the fields before neg. The caches + /// are reachable through getCpuCaches() only. + CPUState *getCpu() const; + + /// Returns a pointer to the global CPU caches (the neg part of CPUState). + /// Only the active state has a TLB, so this aborts when the state is + /// inactive. CPUState *getCpuCaches() const; bool allConcrete() const { diff --git a/libs2ecore/src/CorePluginInterface.cpp b/libs2ecore/src/CorePluginInterface.cpp index 923f448b9..e073ed323 100644 --- a/libs2ecore/src/CorePluginInterface.cpp +++ b/libs2ecore/src/CorePluginInterface.cpp @@ -74,7 +74,7 @@ void helper_s2e_tcg_execution_handler(void *signal, uint64_t pc) { s->emit(g_s2e_state.get(), pc); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -85,7 +85,7 @@ void helper_s2e_tcg_custom_instruction_handler(uint64_t arg) { try { g_s2e->getCorePlugin()->onCustomInstruction.emit(g_s2e_state.get(), arg); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -129,7 +129,7 @@ void s2e_on_translate_soft_interrupt_start(void *context, TranslationBlock *tb, se_tb->executionSignals.push_back(new ExecutionSignal); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -148,7 +148,7 @@ void s2e_on_translate_block_start(void *context, TranslationBlock *tb, uint64_t se_tb->executionSignals.push_back(new ExecutionSignal); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -162,7 +162,7 @@ void s2e_on_translate_block_end(TranslationBlock *tb, uint64_t insPc, int static try { g_s2e->getCorePlugin()->onTranslateBlockEnd.emit(signal, g_s2e_state.get(), tb, insPc, staticTarget, targetPc); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } if (!signal->empty()) { @@ -177,7 +177,7 @@ void s2e_on_translate_block_complete(TranslationBlock *tb, uint64_t pc) { try { g_s2e->getCorePlugin()->onTranslateBlockComplete.emit(g_s2e_state.get(), tb, pc); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -196,7 +196,7 @@ void s2e_on_translate_instruction_start(void *context, TranslationBlock *tb, uin se_tb->executionSignals.push_back(new ExecutionSignal); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -221,7 +221,7 @@ void s2e_on_translate_special_instruction_end(void *context, TranslationBlock *t se_tb->executionSignals.push_back(new ExecutionSignal); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -240,7 +240,7 @@ void s2e_on_translate_jump_start(void *context, TranslationBlock *tb, uint64_t p se_tb->executionSignals.push_back(new ExecutionSignal); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -259,7 +259,7 @@ void s2e_on_translate_indirect_cti_start(void *context, TranslationBlock *tb, ui se_tb->executionSignals.push_back(new ExecutionSignal); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -279,7 +279,7 @@ void s2e_on_translate_lea_rip_relative(void *context, TranslationBlock *tb, uint se_tb->executionSignals.push_back(new ExecutionSignal); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -300,7 +300,7 @@ void s2e_on_translate_instruction_end(void *context, TranslationBlock *tb, uint6 se_tb->executionSignals.push_back(new ExecutionSignal); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -321,7 +321,7 @@ void s2e_on_translate_register_access(TranslationBlock *tb, uint64_t pc, uint64_ se_tb->executionSignals.push_back(new ExecutionSignal); } } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -331,7 +331,7 @@ void s2e_on_exception(unsigned intNb) { try { g_s2e->getCorePlugin()->onException.emit(g_s2e_state.get(), intNb, g_s2e_state->regs()->getPc()); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -356,7 +356,7 @@ void s2e_init_timers() { // The location may be imprecise if called from a helper //(retaddr will be set to null there) void s2e_after_memory_access(uint64_t vaddr, uint64_t value, unsigned size, unsigned flags, uintptr_t retaddr) { - if (retaddr && env->se_current_tb) { + if (retaddr && env_cpu(env)->se_current_tb) { cpu_restore_state(env, (uintptr_t) retaddr); flags |= MEM_TRACE_FLAG_PRECISE; } @@ -364,31 +364,31 @@ void s2e_after_memory_access(uint64_t vaddr, uint64_t value, unsigned size, unsi try { g_s2e->getCorePlugin()->onConcreteDataMemoryAccess.emit(g_s2e_state.get(), vaddr, value, size, flags); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } void s2e_on_page_fault(uint64_t addr, int is_write, void *retaddr) { - if (retaddr && env->se_current_tb) { + if (retaddr && env_cpu(env)->se_current_tb) { cpu_restore_state(env, (uintptr_t) retaddr); } try { g_s2e->getCorePlugin()->onPageFault.emit(g_s2e_state.get(), addr, (bool) is_write); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } void s2e_on_tlb_miss(uint64_t addr, int is_write, void *retaddr) { - if (retaddr && env->se_current_tb) { + if (retaddr && env_cpu(env)->se_current_tb) { cpu_restore_state(env, (uintptr_t) retaddr); } try { g_s2e->getCorePlugin()->onTlbMiss.emit(g_s2e_state.get(), addr, (bool) is_write); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -405,7 +405,7 @@ void s2e_trace_port_access(uint64_t port, uint64_t value, unsigned size, int isW g_s2e->getCorePlugin()->onPortAccess.emit(g_s2e_state.get(), klee::ConstantExpr::create(port, 64), klee::ConstantExpr::create(value, size), isWrite); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } diff --git a/libs2ecore/src/MMUFunctionHandlers.cpp b/libs2ecore/src/MMUFunctionHandlers.cpp index 48e6a4829..acada2c80 100644 --- a/libs2ecore/src/MMUFunctionHandlers.cpp +++ b/libs2ecore/src/MMUFunctionHandlers.cpp @@ -61,7 +61,7 @@ static void io_write_chk(S2EExecutionState *state, CPUArchState *env, target_phy physaddr = (physaddr & TARGET_PAGE_MASK) + addr; state->setMemIoVaddr(ConstantExpr::create(addr, sizeof(target_ulong) * 8)); - env->mem_io_pc = (uintptr_t) retaddr; + env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; if (width <= Expr::Int32) { if (se_ismemfunc(ops, 1)) { @@ -118,7 +118,7 @@ static ref io_read_chk(S2EExecutionState *state, const CPUTLBEntry &tlb, t target_ulong naddr = (physaddr & TARGET_PAGE_MASK) + addr; - env->mem_io_pc = (uintptr_t) retaddr; + env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; state->setMemIoVaddr(ConstantExpr::create(addr, sizeof(target_ulong) * 8)); if (is_notdirty_ops(ops)) { diff --git a/libs2ecore/src/S2EExecutionState.cpp b/libs2ecore/src/S2EExecutionState.cpp index a27ae106b..0f2269b06 100644 --- a/libs2ecore/src/S2EExecutionState.cpp +++ b/libs2ecore/src/S2EExecutionState.cpp @@ -116,10 +116,10 @@ ExecutionStatePtr S2EExecutionState::clone() { // stale on state restore. If a signal occurs while restoring the state, // its handler will try to unlink a stale tb, which could cause a hang // or a crash. - auto old_tb = env->current_tb; - env->current_tb = nullptr; + auto old_tb = env_cpu(env)->current_tb; + env_cpu(env)->current_tb = nullptr; m_registers.saveConcreteState(); - env->current_tb = old_tb; + env_cpu(env)->current_tb = old_tb; cpu_disable_ticks(); s2e_kvm_save_device_state(); @@ -312,7 +312,7 @@ bool S2EExecutionState::getReturnAddress(uint64_t *retAddr) { } TranslationBlock *S2EExecutionState::getTb() const { - return (TranslationBlock *) s2e_read_register_concrete_fast(CPU_OFFSET(se_current_tb)); + return regs()->getCpu()->se_current_tb; } /***/ @@ -477,7 +477,7 @@ void S2EExecutionState::jumpToSymbolic() { g_s2e->getExecutor()->updateConcreteFastPath(this); // XXX: what about regs_to_env ? - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } bool S2EExecutionState::needToJumpToSymbolic() const { @@ -490,7 +490,7 @@ void S2EExecutionState::yield() { setYieldState(true); // Stop current execution - regs()->write(CPU_OFFSET(exception_index), EXCP_SE); + regs()->getCpu()->exception_index = EXCP_SE; throw CpuExitException(); } @@ -654,7 +654,7 @@ uint64_t S2EExecutionState::readMemIoVaddr(bool masked) { klee::ref result; if (!m_memIoVaddr) { - return env->mem_io_vaddr; + return env_cpu(env)->mem_io_vaddr; } if (masked) { diff --git a/libs2ecore/src/S2EExecutionStateRegisters.cpp b/libs2ecore/src/S2EExecutionStateRegisters.cpp index abe90ed10..4041526d5 100644 --- a/libs2ecore/src/S2EExecutionStateRegisters.cpp +++ b/libs2ecore/src/S2EExecutionStateRegisters.cpp @@ -43,18 +43,22 @@ using namespace klee; ObjectKey S2EExecutionStateRegisters::s_concreteRegs; ObjectKey S2EExecutionStateRegisters::s_symbolicRegs; +ObjectKey S2EExecutionStateRegisters::s_cpuExecState; ObjectKey S2EExecutionStateRegisters::s_cpuCaches; void S2EExecutionStateRegisters::initialize(klee::AddressSpace &addressSpace, const klee::ObjectStatePtr &symbolicRegs, const klee::ObjectStatePtr &concreteRegs, + const klee::ObjectStatePtr &cpuExecState, const klee::ObjectStatePtr &cpuCaches) { - assert(!s_concreteRegs.address && !s_symbolicRegs.address && !s_cpuCaches.address); + assert(!s_concreteRegs.address && !s_symbolicRegs.address && !s_cpuExecState.address && !s_cpuCaches.address); s_concreteRegs = concreteRegs->getKey(); s_symbolicRegs = symbolicRegs->getKey(); + s_cpuExecState = cpuExecState->getKey(); s_cpuCaches = cpuCaches->getKey(); symbolicRegs->setName("SymbolicCpuRegisters"); concreteRegs->setName("ConcreteCpuRegisters"); + cpuExecState->setName("CpuExecutionState"); cpuCaches->setName("CpuCaches"); /* The fast path in the cpu loop relies on this */ @@ -68,9 +72,11 @@ void S2EExecutionStateRegisters::update(klee::AddressSpace &addressSpace, const klee::IConcretizer *concretizer) { auto concreteState = addressSpace.findObject(s_concreteRegs.address); auto symbolicState = addressSpace.findObject(s_symbolicRegs.address); + auto cpuExecState = addressSpace.findObject(s_cpuExecState.address); m_symbolicRegs = addressSpace.getWriteable(symbolicState); m_concreteRegs = addressSpace.getWriteable(concreteState); + m_cpuExecState = addressSpace.getWriteable(cpuExecState); if (active && running_concrete) { m_runningConcrete = running_concrete; @@ -104,11 +110,17 @@ CPUX86State *S2EExecutionStateRegisters::getCpuState() const { return cpu; } +CPUState *S2EExecutionStateRegisters::getCpu() const { + return *m_active ? (CPUState *) s_cpuExecState.address : (CPUState *) m_cpuExecState->getConcreteBuffer(true); +} + CPUState *S2EExecutionStateRegisters::getCpuCaches() const { if (!*m_active) { pabort("CPU caches accessed from an inactive state"); } - return (CPUState *) s_cpuCaches.address; + // The object starts at the neg member, so step back to the CPUState + // base; callers address the caches as cpu->neg. + return (CPUState *) (s_cpuCaches.address - offsetof(CPUState, neg)); } bool S2EExecutionStateRegisters::addressSpaceChange(const klee::ObjectKey &key, @@ -126,6 +138,10 @@ bool S2EExecutionStateRegisters::addressSpaceChange(const klee::ObjectKey &key, m_symbolicRegs = newState; assert(newState); return true; + } else if (key == s_cpuExecState) { + m_cpuExecState = newState; + assert(newState); + return true; } else if (key == s_cpuCaches) { // The caches are never snapshotted, so there is no per-state // reference to patch. The object is only reported as handled @@ -364,32 +380,22 @@ bool S2EExecutionStateRegisters::getRegionType(unsigned offset, unsigned size, b } } -/// Compares the concrete registers of two states, skipping the execution -/// fields that are not architectural state. +/// Compares the concrete registers of two states. /// -/// The concrete region of CPUX86State holds, between the se_common_start -/// and se_common_end markers, the fields that CPU_COMMON leaves in the -/// structure: the current TB, the softmmu IO context, the breakpoint and -/// watchpoint lists, jmp_env, the code generator's temporary buffer and -/// the opaque pointer. Two states that agree on every register can differ -/// there without being different for the guest, so this function compares -/// the two ranges on either side of the markers. The CPU caches live in -/// CPUState and are not compared at all: only the active state has them. +/// The concrete region of CPUX86State holds only architectural state. The +/// execution fields that are not (the current TB, the softmmu IO context, +/// the breakpoint and watchpoint lists, jmp_env, ...) live in CPUState, as +/// do the CPU caches, and neither is compared: two states that agree on +/// every register can differ there without being different for the guest. /// /// @param other the state to compare against /// @return zero when the architectural registers are identical, and the -/// result of memcmp() on the first differing range otherwise +/// result of memcmp() otherwise int S2EExecutionStateRegisters::compareArchitecturalConcreteState(const S2EExecutionStateRegisters &other) { CPUX86State *a = getCpuState(); CPUX86State *b = other.getCpuState(); - int ret = memcmp(&a->eip, &b->eip, CPU_OFFSET(se_common_start) - CPU_OFFSET(eip)); - if (ret) { - return ret; - } - - ret = memcmp(&a->se_common_end, &b->se_common_end, sizeof(CPUX86State) - CPU_OFFSET(se_common_end)); - return ret; + return memcmp(&a->eip, &b->eip, sizeof(CPUX86State) - CPU_OFFSET(eip)); } /***/ diff --git a/libs2ecore/src/S2EExecutor.cpp b/libs2ecore/src/S2EExecutor.cpp index 4269023ff..b6d2878c5 100644 --- a/libs2ecore/src/S2EExecutor.cpp +++ b/libs2ecore/src/S2EExecutor.cpp @@ -543,15 +543,25 @@ void S2EExecutor::registerCpu(S2EExecutionState *initialState, CPUX86State *cpuE /* isReadOnly = */ false, /* isSharedConcrete = */ true); - /* Add the CPU caches (TLB, RAM TLB, TB jump cache) that precede the env - inside ArchCPU. The softmmu fast path runs as bitcode inside KLEE and - reads the TLB through this object. See cpu/state.h. */ - auto cpuCaches = initialState->addExternalObject(env_cpu(cpuEnv), offsetof(ArchCPU, env), + /* The CPUState that precedes the env inside ArchCPU is registered as two + objects (see cpu/state.h). The execution fields (exception_index, + interrupt_request, the current TB, ...) are snapshotted per state like + the concrete registers. The caches (TLB, RAM TLB, TB jump cache) are + not: only the active state has a TLB. Both are shared-concrete so that + helpers and the softmmu fast path can reach them as bitcode. */ + CPUState *cpu = env_cpu(cpuEnv); + auto cpuExecState = initialState->addExternalObject(cpu, offsetof(CPUState, neg), + /* isReadOnly = */ false, + /* isSharedConcrete = */ true); + + auto cpuCaches = initialState->addExternalObject(&cpu->neg, offsetof(ArchCPU, env) - offsetof(CPUState, neg), /* isReadOnly = */ false, /* isSharedConcrete = */ true); - initialState->m_registers.initialize(initialState->addressSpace(), symbolicRegs, concreteRegs, cpuCaches); + initialState->m_registers.initialize(initialState->addressSpace(), symbolicRegs, concreteRegs, cpuExecState, + cpuCaches); klee::ExecutionState::s_ignoredMergeObjects.insert(initialState->m_registers.getConcreteRegs()); + klee::ExecutionState::s_ignoredMergeObjects.insert(initialState->m_registers.getCpuExecStateKey()); klee::ExecutionState::s_ignoredMergeObjects.insert(initialState->m_registers.getCpuCachesKey()); } @@ -700,7 +710,7 @@ void S2EExecutor::doLoadBalancing() { void S2EExecutor::stateSwitchTimerCallback(void *opaque) { S2EExecutor *c = (S2EExecutor *) opaque; - assert(env->current_tb == nullptr); + assert(env_cpu(env)->current_tb == nullptr); if (g_s2e_state) { c->doLoadBalancing(); @@ -787,12 +797,15 @@ void S2EExecutor::doStateSwitch(S2EExecutionStatePtr oldState, S2EExecutionState *g_sqi.exec.clock_scaling_factor = timers_state.cpu_clock_scale_factor; } + // jmp_env belongs to the host call stack that is performing the + // switch, not to the incoming state, so it is carried across the + // restore of the CPU execution fields. jmp_buf jmp_env; - memcpy(&jmp_env, &env->jmp_env, sizeof(jmp_buf)); + memcpy(&jmp_env, &env_cpu(env)->jmp_env, sizeof(jmp_buf)); newState->m_registers.restoreConcreteState(); - memcpy(&env->jmp_env, &jmp_env, sizeof(jmp_buf)); + memcpy(&env_cpu(env)->jmp_env, &jmp_env, sizeof(jmp_buf)); newState->m_active = true; @@ -816,7 +829,7 @@ void S2EExecutor::doStateSwitch(S2EExecutionStatePtr oldState, S2EExecutionState se_tb_safe_flush(); } - assert(env->current_tb == nullptr); + assert(env_cpu(env)->current_tb == nullptr); g_se_disable_tlb_flush = 0; @@ -1018,7 +1031,7 @@ void S2EExecutor::updateConcreteFastPath(S2EExecutionState *state) { g_s2e_running_exception_emulation_code = (char *) &state->m_runningExceptionEmulationCode; if (g_s2e_fast_concrete_invocation) { - env->generate_llvm = 0; + env_cpu(env)->generate_llvm = 0; } updateClockScaling(); @@ -1059,7 +1072,7 @@ uintptr_t S2EExecutor::executeTranslationBlockConcrete(S2EExecutionState *state, uintptr_t ret = 0; S2EExternalDispatcher::saveJmpBuf(); - if (setjmp(env->jmp_env)) { + if (setjmp(env_cpu(env)->jmp_env)) { S2EExternalDispatcher::restoreJmpBuf(); throw CpuExitException(); } else { @@ -1075,7 +1088,7 @@ uintptr_t S2EExecutor::executeTranslationBlockSlow(struct CPUX86State *env1, str uintptr_t ret = g_s2e->getExecutor()->executeTranslationBlock(g_s2e_state.get(), tb); return ret; } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } @@ -1107,7 +1120,7 @@ uintptr_t S2EExecutor::executeTranslationBlock(S2EExecutionState *state, Transla executeKlee |= (state->regs()->getPc() == state->m_startSymbexAtPC); if (executeKlee && !tb->llvm_function) { - env->generate_llvm = 1; + env_cpu(env)->generate_llvm = 1; return 0; } @@ -1120,7 +1133,7 @@ uintptr_t S2EExecutor::executeTranslationBlock(S2EExecutionState *state, Transla auto pair = std::make_pair(state->regs()->getPc(), state->regs()->getPageDir()); if (state->m_toRunSymbolically.find(pair) != state->m_toRunSymbolically.end()) { if (!tb->llvm_function) { - env->generate_llvm = 1; + env_cpu(env)->generate_llvm = 1; return 0; } state->m_toRunSymbolically.erase(pair); @@ -1138,7 +1151,7 @@ uintptr_t S2EExecutor::executeTranslationBlock(S2EExecutionState *state, Transla } if (executeKlee && !tb->llvm_function) { - env->generate_llvm = 1; + env_cpu(env)->generate_llvm = 1; return 0; } @@ -1149,7 +1162,7 @@ uintptr_t S2EExecutor::executeTranslationBlock(S2EExecutionState *state, Transla return executeTranslationBlockKlee(state, tb); } else { - env->generate_llvm = 0; + env_cpu(env)->generate_llvm = 0; if (!state->isRunningConcrete()) { state->switchToConcrete(); @@ -1629,7 +1642,7 @@ void S2EExecutor::terminateState(ExecutionStatePtr s) { // No need for exiting the loop if we kill another state. if (!m_inLoadBalancing && (state == g_s2e_state)) { - state->regs()->write(CPU_OFFSET(exception_index), EXCP_SE); + state->regs()->getCpu()->exception_index = EXCP_SE; throw CpuExitException(); } } @@ -1649,7 +1662,7 @@ inline void S2EExecutor::setCCOpEflags(S2EExecutionState *state) { executeFunction(state, "helper_set_cc_op_eflags"); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } } else { @@ -1684,7 +1697,7 @@ inline void S2EExecutor::doInterrupt(S2EExecutionState *state, int intno, int is try { executeFunction(state, "se_do_interrupt_all", args); } catch (s2e::CpuExitException &) { - longjmp(env->jmp_env, 1); + longjmp(env_cpu(env)->jmp_env, 1); } } } diff --git a/libs2ecore/src/S2EExternalDispatcher.cpp b/libs2ecore/src/S2EExternalDispatcher.cpp index 7647ab396..e36761d64 100644 --- a/libs2ecore/src/S2EExternalDispatcher.cpp +++ b/libs2ecore/src/S2EExternalDispatcher.cpp @@ -45,7 +45,7 @@ bool S2EExternalDispatcher::call(external_fcn_t targetFunction, const Arguments saveJmpBuf(); - if (setjmp(env->jmp_env)) { + if (setjmp(env_cpu(env)->jmp_env)) { restoreJmpBuf(); throw CpuExitException(); } else { @@ -58,10 +58,10 @@ bool S2EExternalDispatcher::call(external_fcn_t targetFunction, const Arguments } void S2EExternalDispatcher::saveJmpBuf() { - memcpy(s2e_cpuExitJmpBuf, env->jmp_env, sizeof(env->jmp_env)); + memcpy(s2e_cpuExitJmpBuf, env_cpu(env)->jmp_env, sizeof(env_cpu(env)->jmp_env)); } void S2EExternalDispatcher::restoreJmpBuf() { - memcpy(env->jmp_env, s2e_cpuExitJmpBuf, sizeof(env->jmp_env)); + memcpy(env_cpu(env)->jmp_env, s2e_cpuExitJmpBuf, sizeof(env_cpu(env)->jmp_env)); } } // namespace s2e diff --git a/libtcg/include/tcg/tcg.h b/libtcg/include/tcg/tcg.h index 1fadb1915..d98de1cc8 100644 --- a/libtcg/include/tcg/tcg.h +++ b/libtcg/include/tcg/tcg.h @@ -582,7 +582,8 @@ struct TCGContext { #ifdef CONFIG_SYMBEX unsigned tlbe_offset_symbex_addend; - unsigned env_offset_se_tb_abort; + /* Signed: se_tb_abort lives in CPUState, below env (S2E). */ + int env_offset_se_tb_abort; #endif unsigned target_page_bits; From 03e51a6310ec93d355b96e194209cefd76ca5dbe Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 18:20:01 +0200 Subject: [PATCH 31/52] libtcg: updated memopidx.h to qemu 11.1 The header was still at its 8.1.2 content, with the mmu index in the low 4 bits of MemOpIdx. Upstream uses 5 bits since 10.2. The softmmu template and the mmu function handlers now extract the index with get_mmuidx() instead of a hard-coded mask. Co-Authored-By: Claude Opus 5.5 --- libcpu/src/softmmu_template.h | 4 +-- libs2ecore/src/MMUFunctionHandlers.cpp | 2 +- libtcg/include/tcg/tcg-memopidx.h | 47 ++++++++++---------------- 3 files changed, 20 insertions(+), 33 deletions(-) diff --git a/libcpu/src/softmmu_template.h b/libcpu/src/softmmu_template.h index ccd1664b9..c14561fce 100644 --- a/libcpu/src/softmmu_template.h +++ b/libcpu/src/softmmu_template.h @@ -260,7 +260,7 @@ glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(CPUArchState *env, target target_phys_addr_t ioaddr; CPUTLBEntry *tlb_entry; - mmu_idx = mmu_idx & 0xf; + mmu_idx = get_mmuidx(mmu_idx); /* test if there is match for unaligned or IO access */ /* XXX: could done more in memory macro in a non portable way */ @@ -514,7 +514,7 @@ void glue(glue(glue(HELPER_PREFIX, st), SUFFIX), MMUSUFFIX)(CPUArchState *env, t target_ulong object_index, index; CPUTLBEntry *tlb_entry; - mmu_idx = mmu_idx & 0xf; + mmu_idx = get_mmuidx(mmu_idx); #ifdef CONFIG_SYMBEX_MP INSTR_BEFORE_MEMORY_ACCESS(addr, val, DATA_SIZE, 1); diff --git a/libs2ecore/src/MMUFunctionHandlers.cpp b/libs2ecore/src/MMUFunctionHandlers.cpp index acada2c80..a856f1d8a 100644 --- a/libs2ecore/src/MMUFunctionHandlers.cpp +++ b/libs2ecore/src/MMUFunctionHandlers.cpp @@ -210,7 +210,7 @@ static ref handle_ldst_mmu(Executor *executor, ExecutionState *state, klee ref constantAddress = handleForkAndConcretizeNative(executor, state, target, symbAddress); ref mmuIdxExpr = args[isWrite ? 3 : 2]; - unsigned mmu_idx = dyn_cast(mmuIdxExpr)->getZExtValue() & 0xf; + unsigned mmu_idx = get_mmuidx(dyn_cast(mmuIdxExpr)->getZExtValue()); // XXX: determine this by looking at the instruction that called us Expr::Width width = data_size * 8; diff --git a/libtcg/include/tcg/tcg-memopidx.h b/libtcg/include/tcg/tcg-memopidx.h index 7ceb4a0f1..2f5f4194c 100644 --- a/libtcg/include/tcg/tcg-memopidx.h +++ b/libtcg/include/tcg/tcg-memopidx.h @@ -1,33 +1,17 @@ /* - * Tiny Code Generator for QEMU + * Combine the MemOp and mmu_idx parameters into a single value. * - * Copyright (c) 2008 Fabrice Bellard + * Authors: + * Richard Henderson * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. */ -#ifndef TCG_MEMOPIDX - -#define TCG_MEMOPIDX +#ifndef EXEC_MEMOPIDX_H +#define EXEC_MEMOPIDX_H -#include -#include +#include #include "tcg-memop.h" @@ -35,7 +19,6 @@ extern "C" { #endif -/* Combine the MemOp and mmu_idx parameters into a single value. */ typedef uint32_t MemOpIdx; /** @@ -46,8 +29,11 @@ typedef uint32_t MemOpIdx; * Encode these values into a single parameter. */ static inline MemOpIdx make_memop_idx(MemOp op, unsigned idx) { - assert(idx <= 15); - return (op << 4) | idx; +#ifdef CONFIG_DEBUG_TCG + assert(idx <= 31); + assert(clz32(op) >= 5); +#endif + return (op << 5) | idx; } /** @@ -57,7 +43,8 @@ static inline MemOpIdx make_memop_idx(MemOp op, unsigned idx) { * Extract the memory operation from the combined value. */ static inline MemOp get_memop(MemOpIdx oi) { - return (MemOp) (oi >> 4); + /* The cast is required to compile this header as C++ (tcg-llvm.cpp). */ + return (MemOp) (oi >> 5); } /** @@ -67,11 +54,11 @@ static inline MemOp get_memop(MemOpIdx oi) { * Extract the mmu index from the combined value. */ static inline unsigned get_mmuidx(MemOpIdx oi) { - return oi & 15; + return oi & 31; } #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif From 1cbc1d0f2dfef7ec324006d01f118881491bab8c Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:22:40 +0200 Subject: [PATCH 32/52] libcpu,libtcg,tools: removed the static translator Deleted the translator headers in tools and the STATIC_TRANSLATOR code paths that supported them in libcpu and libtcg. Nothing in the build defined STATIC_TRANSLATOR. Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/se_libcpu_config.h | 2 - libcpu/include/cpu/softmmu_defs.h | 2 +- libcpu/src/exec-all.h | 5 - libcpu/src/softmmu_header.h | 27 +- libcpu/src/softmmu_template.h | 25 +- libcpu/src/target-i386/op_helper.c | 134 +--- libcpu/src/target-i386/translate.c | 31 +- libcpu/src/translate-all.c | 9 +- libtcg/include/tcg/tb.h | 4 - tools/include/Translator/Translator.h | 290 -------- tools/include/Translator/TranslatorInternal.h | 587 --------------- tools/include/Translator/TranslatorWrapper.h | 43 -- .../Translator/TranslatorWrapperInternal.h | 696 ------------------ 13 files changed, 50 insertions(+), 1805 deletions(-) delete mode 100644 tools/include/Translator/Translator.h delete mode 100644 tools/include/Translator/TranslatorInternal.h delete mode 100644 tools/include/Translator/TranslatorWrapper.h delete mode 100644 tools/include/Translator/TranslatorWrapperInternal.h diff --git a/libcpu/include/cpu/se_libcpu_config.h b/libcpu/include/cpu/se_libcpu_config.h index 9723e3a9a..b802e36cf 100644 --- a/libcpu/include/cpu/se_libcpu_config.h +++ b/libcpu/include/cpu/se_libcpu_config.h @@ -52,10 +52,8 @@ extern "C" { /** Whether to compile softmmu with memory tracing enabled. */ /** Can be disabled for debugging purposes. */ -#if !defined(STATIC_TRANSLATOR) #define SE_ENABLE_MEM_TRACING #define TCG_ENABLE_MEM_TRACING -#endif #ifdef CONFIG_SYMBEX_MP #define SE_ENABLE_PHYSRAM_TLB diff --git a/libcpu/include/cpu/softmmu_defs.h b/libcpu/include/cpu/softmmu_defs.h index cff6410cf..1f39cd6a7 100644 --- a/libcpu/include/cpu/softmmu_defs.h +++ b/libcpu/include/cpu/softmmu_defs.h @@ -36,7 +36,7 @@ uintptr_t se_notdirty_mem_write(target_phys_addr_t ram_addr, int size); uintptr_t se_notdirty_mem_read(target_phys_addr_t ram_addr); #endif -#if defined(CONFIG_SYMBEX_MP) || defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX_MP) uint8_t helper_ldb_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); void helper_stb_mmu_symb(CPUArchState *env, target_ulong addr, uint8_t val, int mmu_idx, void *retaddr); uint16_t helper_ldw_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); diff --git a/libcpu/src/exec-all.h b/libcpu/src/exec-all.h index e9bc56a92..0a22e677b 100644 --- a/libcpu/src/exec-all.h +++ b/libcpu/src/exec-all.h @@ -43,12 +43,7 @@ extern struct cpu_stats_t g_cpu_stats; #define DISAS_UPDATE 2 /* cpu state was modified dynamically */ #define DISAS_TB_JUMP 3 /* only pc was modified statically */ -#ifdef STATIC_TRANSLATOR -/* Accomodate large TBs */ -#define OPC_BUF_SIZE 640000 -#else #define OPC_BUF_SIZE 640 -#endif #define OPC_MAX_SIZE (OPC_BUF_SIZE - MAX_OP_PER_INSTR) diff --git a/libcpu/src/softmmu_header.h b/libcpu/src/softmmu_header.h index 0f7ce68ab..6a7d1926b 100644 --- a/libcpu/src/softmmu_header.h +++ b/libcpu/src/softmmu_header.h @@ -76,7 +76,7 @@ #include // clang-format off -#if defined(SYMBEX_LLVM_LIB) && !defined(STATIC_TRANSLATOR) +#if defined(SYMBEX_LLVM_LIB) #define SMHINLINE #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) \ if (*g_sqi.events.before_memory_access_signals_count) tcg_llvm_before_memory_access(vaddr, value, size, flags); @@ -86,7 +86,7 @@ tcg_llvm_fork_and_concretize(val, 0, max, 0) #else // SYMBEX_LLVM_LIB #define SMHINLINE inline - #if defined(SE_ENABLE_MEM_TRACING) && !defined(STATIC_TRANSLATOR) + #if defined(SE_ENABLE_MEM_TRACING) #if defined(SE_NO_TRACE) #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags) @@ -120,27 +120,6 @@ #endif // CONFIG_SYMBEX -#ifdef STATIC_TRANSLATOR - -#define CPU_PREFIX -#define HELPER_PREFIX __ - -// The static translator uses QEMU's translator as a library and redirects all memory accesses -// to its custom routines. -// Here we simply declare the functions -RES_TYPE glue(glue(ld, USUFFIX), MEMSUFFIX)(CPUArchState *env, target_ulong ptr); - -#if DATA_SIZE <= 2 -int glue(glue(lds, SUFFIX), MEMSUFFIX)(CPUArchState *env, target_ulong ptr); -#endif - -#if ACCESS_TYPE != (NB_MMU_MODES + 1) -/* generic store macro */ -void glue(glue(st, SUFFIX), MEMSUFFIX)(CPUArchState *env, target_ulong ptr, RES_TYPE v); -#endif - -#else // STATIC_TRANSLATOR - #define CPU_PREFIX cpu_ #define HELPER_PREFIX helper_ @@ -279,8 +258,6 @@ static SMHINLINE void glue(glue(glue(CPU_PREFIX, st), SUFFIX), MEMSUFFIX)(CPUArc #endif /* ACCESS_TYPE != (NB_MMU_MODES + 1) */ -#endif // STATIC_TRANSLATOR - #if ACCESS_TYPE != (NB_MMU_MODES + 1) #if DATA_SIZE == 8 diff --git a/libcpu/src/softmmu_template.h b/libcpu/src/softmmu_template.h index c14561fce..7d25d7fab 100644 --- a/libcpu/src/softmmu_template.h +++ b/libcpu/src/softmmu_template.h @@ -67,7 +67,7 @@ #include // clang-format off -#if defined(SYMBEX_LLVM_LIB) && !defined(STATIC_TRANSLATOR) +#if defined(SYMBEX_LLVM_LIB) #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) \ if (*g_sqi.events.before_memory_access_signals_count) tcg_llvm_before_memory_access(vaddr, value, size, flags); #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags, retaddr) \ @@ -77,7 +77,7 @@ #define SE_SET_MEM_IO_VADDR(env, addr, reset) \ tcg_llvm_write_mem_io_vaddr(addr, reset) #else // SYMBEX_LLVM_LIB - #if defined(SE_ENABLE_MEM_TRACING) && !defined(STATIC_TRANSLATOR) + #if defined(SE_ENABLE_MEM_TRACING) #ifdef SOFTMMU_CODE_ACCESS #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags, retaddr) @@ -125,13 +125,7 @@ static DATA_TYPE glue(glue(slow_ld, SUFFIX), MMUSUFFIX)(CPUArchState *env, targe DATA_TYPE glue(glue(io_read, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -#if defined(STATIC_TRANSLATOR) -DATA_TYPE glue(glue(io_read_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, - void *retaddr) { - assert(false && "Cannot run statically"); -} - -#elif !defined(SYMBEX_LLVM_LIB) +#if !defined(SYMBEX_LLVM_LIB) DATA_TYPE glue(glue(io_read, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr) { DATA_TYPE res; @@ -249,7 +243,6 @@ DATA_TYPE glue(glue(io_read_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_p #endif -#ifndef STATIC_TRANSLATOR /* handle all cases except unaligned access which span two pages */ DATA_TYPE glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, int mmu_idx, @@ -331,8 +324,6 @@ glue(glue(glue(TCG_HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(CPUArchState *env, ta return (TCG_DATA_TYPE) glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(env, addr, mmu_idx, retaddr); } -#endif /* STATIC_TRANSLATOR */ - /* handle all unaligned cases */ static DATA_TYPE glue(glue(slow_ld, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr) { @@ -404,13 +395,7 @@ static void glue(glue(slow_st, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulo void glue(glue(io_write, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, DATA_TYPE val, target_ulong addr, void *retaddr); -#if defined(STATIC_TRANSLATOR) -void glue(glue(io_write_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, DATA_TYPE val, - target_ulong addr, void *retaddr) { - assert(false && "Cannot run statically"); -} - -#elif !defined(SYMBEX_LLVM_LIB) +#if !defined(SYMBEX_LLVM_LIB) void glue(glue(io_write, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, DATA_TYPE val, target_ulong addr, void *retaddr) { @@ -506,7 +491,6 @@ void glue(glue(io_write_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_ #endif -#ifndef STATIC_TRANSLATOR void glue(glue(glue(HELPER_PREFIX, st), SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, DATA_TYPE val, int mmu_idx, void *retaddr) { target_phys_addr_t ioaddr; @@ -578,7 +562,6 @@ void glue(glue(glue(HELPER_PREFIX, st), SUFFIX), MMUSUFFIX)(CPUArchState *env, t goto redo; } } -#endif /* STATIC_TRANSLATOR */ /* handles all unaligned cases */ static void glue(glue(slow_st, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, DATA_TYPE val, int mmu_idx, diff --git a/libcpu/src/target-i386/op_helper.c b/libcpu/src/target-i386/op_helper.c index f76ddd51a..a36fccab6 100644 --- a/libcpu/src/target-i386/op_helper.c +++ b/libcpu/src/target-i386/op_helper.c @@ -145,7 +145,7 @@ uint32_t compute_eflags(void) { return ((uint32_t) env->mflags) | helper_cc_compute_all(CC_OP) | (DF & DF_MASK) | 2; } -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && !defined(STATIC_TRANSLATOR) && defined(CONFIG_SYMBEX_MP) +#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) static inline void se_load_eflags(void *mgr, void *eflags, int update_mask) { void *symb_flags = g_sqi.expr.andc(mgr, eflags, CFLAGS_MASK); g_sqi.expr.write_cpu(symb_flags, offsetof(CPUX86State, cc_src), sizeof(env->cc_src)); @@ -202,7 +202,7 @@ static inline void cpu_load_efer(CPUX86State *env, uint64_t val) { } } -#if !defined(SYMBEX_LLVM_LIB) || defined(STATIC_TRANSLATOR) +#if !defined(SYMBEX_LLVM_LIB) const uint8_t parity_table[256] = { CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0, 0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P, 0, CC_P, CC_P, @@ -242,7 +242,7 @@ extern const uint8_t rclb_table[32]; #define floatx80_l2t make_floatx80(0x4000, 0xd49a784bcd1b8afeLL) /* broken thread support */ -#if !defined(SYMBEX_LLVM_LIB) || defined(STATIC_TRANSLATOR) +#if !defined(SYMBEX_LLVM_LIB) // static spinlock_t global_cpu_lock = SPIN_LOCK_UNLOCKED; /** @@ -252,15 +252,11 @@ extern const uint8_t rclb_table[32]; * We don't need locking on single cpu anyway. */ void helper_lock(void) { -#ifndef STATIC_TRANSLATOR -// spin_lock(&global_cpu_lock); -#endif + // spin_lock(&global_cpu_lock); } void helper_unlock(void) { -#ifndef STATIC_TRANSLATOR -// spin_unlock(&global_cpu_lock); -#endif + // spin_unlock(&global_cpu_lock); } #endif /* SYMBEX_LLVM_LIB */ @@ -420,7 +416,7 @@ static void switch_tss(CPUX86State *env, int tss_selector, uint32_t e1, uint32_t int index; target_ulong ptr; -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) int cpl = env->hflags & HF_CPL_MASK; #endif @@ -615,7 +611,7 @@ static void switch_tss(CPUX86State *env, int tss_selector, uint32_t e1, uint32_t env->ldt.limit = 0; env->ldt.flags = 0; -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(cpl, dpl); } @@ -700,33 +696,6 @@ void helper_check_iol(uint32_t t0) { check_io(env, t0, 4, GETPC()); } -#ifdef STATIC_TRANSLATOR -void helper_outb(uint32_t port, uint32_t data) { - assert(0); -} - -target_ulong helper_inb(uint32_t port) { - assert(0); -} - -void helper_outw(uint32_t port, uint32_t data) { - assert(0); -} - -target_ulong helper_inw(uint32_t port) { - assert(0); -} - -void helper_outl(uint32_t port, uint32_t data) { - assert(0); -} - -target_ulong helper_inl(uint32_t port) { - assert(0); -} - -#else - #ifdef SYMBEX_LLVM_LIB /** * We bypass the call to the handlers in case of writes to symbolic ports to @@ -803,7 +772,7 @@ target_ulong helper_inl(uint32_t port) { #else void helper_outb(uint32_t port, uint32_t data) { -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (g_sqi.mem.is_port_symbolic(port)) { g_sqi.exec.switch_to_symbolic((void *) GETPC()); } @@ -815,13 +784,13 @@ void helper_outb(uint32_t port, uint32_t data) { } target_ulong helper_inb(uint32_t port) { -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (g_sqi.mem.is_port_symbolic(port)) { g_sqi.exec.switch_to_symbolic((void *) GETPC()); } #endif target_ulong res = cpu_inb(port); -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (*g_sqi.events.on_port_access_signals_count) { g_sqi.events.trace_port_access(port, res, 8, 0, (void *) GETPC()); } @@ -830,7 +799,7 @@ target_ulong helper_inb(uint32_t port) { } void helper_outw(uint32_t port, uint32_t data) { -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (g_sqi.mem.is_port_symbolic(port)) { g_sqi.exec.switch_to_symbolic((void *) GETPC()); } @@ -842,13 +811,13 @@ void helper_outw(uint32_t port, uint32_t data) { } target_ulong helper_inw(uint32_t port) { -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (g_sqi.mem.is_port_symbolic(port)) { g_sqi.exec.switch_to_symbolic((void *) GETPC()); } #endif target_ulong res = cpu_inw(port); -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (*g_sqi.events.on_port_access_signals_count) { g_sqi.events.trace_port_access(port, res, 16, 0, (void *) GETPC()); } @@ -857,7 +826,7 @@ target_ulong helper_inw(uint32_t port) { } void helper_outl(uint32_t port, uint32_t data) { -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (g_sqi.mem.is_port_symbolic(port)) { g_sqi.exec.switch_to_symbolic((void *) GETPC()); } @@ -870,13 +839,13 @@ void helper_outl(uint32_t port, uint32_t data) { } target_ulong helper_inl(uint32_t port) { -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (g_sqi.mem.is_port_symbolic(port)) { g_sqi.exec.switch_to_symbolic((void *) GETPC()); } #endif target_ulong res = cpu_inl(port); -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (*g_sqi.events.on_port_access_signals_count) { g_sqi.events.trace_port_access(port, res, 32, 0, (void *) GETPC()); } @@ -886,8 +855,6 @@ target_ulong helper_inl(uint32_t port) { #endif -#endif /* STATIC_TRANSLATOR */ - static inline unsigned int get_sp_mask(unsigned int e2) { if (e2 & DESC_B_MASK) return 0xffffffff; @@ -1162,7 +1129,7 @@ static void do_interrupt_protected(CPUX86State *env, int intno, int is_int, int } env->mflags &= ~(TF_MASK | VM_MASK | RF_MASK | NT_MASK); -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(cpl, dpl); } @@ -1325,7 +1292,7 @@ static void do_interrupt64(CPUX86State *env, int intno, int is_int, int error_co void helper_syscall(int next_eip_addend) { int selector; -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) int old_cpl = env->hflags & HF_CPL_MASK; #endif @@ -1372,7 +1339,7 @@ void helper_syscall(int next_eip_addend) { WR_se_eip(env, (uint32_t) env->star); } -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(old_cpl, 0); } @@ -1384,7 +1351,7 @@ void helper_syscall(int next_eip_addend) { void helper_sysret(int dflag) { int cpl, selector; -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) int old_cpl = env->hflags & HF_CPL_MASK; #endif @@ -1429,7 +1396,7 @@ void helper_sysret(int dflag) { cpu_x86_set_cpl(env, 3); } -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(old_cpl, 3); } @@ -1618,7 +1585,7 @@ static int check_exception(int intno, int *error_code) { */ static void LIBCPU_NORETURN raise_interrupt2(CPUX86State *env, int intno, int is_int, int error_code, int next_eip_addend, uintptr_t retaddr) { -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) g_sqi.expr.mgr_clear(); #endif @@ -2756,7 +2723,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip, int shift, int nex EIP = offset; WR_se_eip(env, offset); -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(cpl, dpl); } @@ -2823,7 +2790,7 @@ static inline void validate_seg(int seg_reg, int cpl) { /* protected mode iret */ static inline void helper_ret_protected(CPUX86State *env, int shift, int is_iret, int addend, uintptr_t ra) { -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && !defined(STATIC_TRANSLATOR) && defined(CONFIG_SYMBEX_MP) +#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) void *mgr = NULL; void *symb_new_eflags = NULL; #endif @@ -2850,7 +2817,7 @@ static inline void helper_ret_protected(CPUX86State *env, int shift, int is_iret POPQ(sp, new_cs); new_cs &= 0xffff; if (is_iret) { -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && !defined(STATIC_TRANSLATOR) && defined(CONFIG_SYMBEX_MP) +#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) mgr = g_sqi.expr.mgr(); POPQ_S(mgr, sp, symb_new_eflags); #else @@ -2865,7 +2832,7 @@ static inline void helper_ret_protected(CPUX86State *env, int shift, int is_iret POPL_T(ssp, sp, sp_mask, new_cs); new_cs &= 0xffff; if (is_iret) { -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && !defined(STATIC_TRANSLATOR) && defined(CONFIG_SYMBEX_MP) +#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) mgr = g_sqi.expr.mgr(); POPL_T_S(mgr, ssp, sp, sp_mask, symb_new_eflags); if (g_sqi.expr.to_constant(g_sqi.expr.andc(mgr, symb_new_eflags, VM_MASK))) @@ -2992,7 +2959,7 @@ static inline void helper_ret_protected(CPUX86State *env, int shift, int is_iret if (shift == 0) eflags_mask &= 0xffff; -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && !defined(STATIC_TRANSLATOR) && defined(CONFIG_SYMBEX_MP) +#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) if (symb_new_eflags == NULL) { // 16-bit case no one cares about, let it be concrete load_eflags(new_eflags, eflags_mask); } else { @@ -3004,7 +2971,7 @@ static inline void helper_ret_protected(CPUX86State *env, int shift, int is_iret #endif } -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (cpl != rpl && unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(cpl, rpl); } @@ -3021,7 +2988,7 @@ static inline void helper_ret_protected(CPUX86State *env, int shift, int is_iret POPL(ssp, sp, sp_mask, new_gs); /* modify processor state */ -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && !defined(STATIC_TRANSLATOR) && defined(CONFIG_SYMBEX_MP) +#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) se_load_eflags(mgr, symb_new_eflags, TF_MASK | AC_MASK | ID_MASK | IF_MASK | IOPL_MASK | VM_MASK | NT_MASK | VIF_MASK | VIP_MASK); @@ -3043,7 +3010,7 @@ static inline void helper_ret_protected(CPUX86State *env, int shift, int is_iret WR_se_eip(env, new_eip); ESP_W(new_esp); -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(cpl, 3); } @@ -3081,7 +3048,7 @@ void helper_lret_protected(int shift, int addend) { } void helper_sysenter(void) { -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) int cpl = env->hflags & HF_CPL_MASK; #endif @@ -3109,7 +3076,7 @@ void helper_sysenter(void) { EIP = env->sysenter_eip; WR_se_eip(env, EIP); -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(cpl, 0); } @@ -3146,7 +3113,7 @@ void helper_sysexit(int dflag) { EIP = EDX; WR_se_eip(env, EIP); -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(cpl, 3); } @@ -4858,7 +4825,6 @@ void helper_reset_rf(void) { env->mflags &= ~RF_MASK; } -#ifndef STATIC_TRANSLATOR void helper_raise_interrupt(int intno, int next_eip_addend) { raise_interrupt(env, intno, 1, 0, next_eip_addend); } @@ -4866,21 +4832,6 @@ void helper_raise_interrupt(int intno, int next_eip_addend) { void helper_raise_exception(int exception_index) { raise_exception(env, exception_index); } -#else -/** - * In static mode, interrupts are emulated by the - * run-time library. They behave like normal function calls. - */ -#ifndef SYMBEX_LLVM_LIB -void helper_raise_interrupt(int intno, int next_eip_addend) { - assert(false && "Can't be called"); -} - -void helper_raise_exception(int exception_index) { - assert(false && "Can't be called"); -} -#endif -#endif void helper_cli(void) { env->mflags &= ~IF_MASK; @@ -4967,14 +4918,6 @@ void helper_boundl(target_ulong a0, int v) { #undef _raw #endif -#ifdef STATIC_TRANSLATOR -void tlb_fill(CPUX86State *env1, target_ulong addr, target_ulong page_addr, int is_write, int mmu_idx, void *retaddr) { - assert(false); -} - -#endif - -#if !defined(STATIC_TRANSLATOR) /* try to fill the TLB and return an exception if error. If retaddr is NULL, it means that the function was called in C code (i.e. not from generated code or from helper.c) */ @@ -5015,7 +4958,6 @@ void tlb_fill(CPUX86State *env1, target_ulong addr, target_ulong page_addr, int raise_exception_err_ra(env, env_cpu(env)->exception_index, env->error_code, (uintptr_t) retaddr); } } -#endif /* Secure Virtual Machine helpers */ static inline void svm_save_seg(target_phys_addr_t addr, const SegmentCache *sc) { @@ -5046,7 +4988,7 @@ void helper_vmrun(int aflag, int next_eip_addend) { uint32_t event_inj; uint32_t int_ctl; -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) int cpl = env->hflags & HF_CPL_MASK; #endif @@ -5162,7 +5104,7 @@ void helper_vmrun(int aflag, int next_eip_addend) { env_cpu(env)->interrupt_request |= CPU_INTERRUPT_VIRQ; } -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(cpl, dpl); } @@ -5405,7 +5347,7 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1) { libcpu_log_mask(CPU_LOG_TB_IN_ASM, "vmexit(%08x, %016" PRIx64 ", %016" PRIx64 ", " TARGET_FMT_lx ")!\n", exit_code, exit_info_1, ldq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2)), EIP); -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) int cpl = env->hflags & HF_CPL_MASK; #endif @@ -5527,7 +5469,7 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1) { env->error_code = 0; env->old_exception = -1; -#if defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_privilege_change_signals_count)) { g_sqi.events.on_privilege_change(cpl, dpl); } @@ -5930,7 +5872,7 @@ __attribute__((weak)) void helper_se_ret(target_ulong pc, int retim_value) { } #endif -#if !defined(CONFIG_SYMBEX) && !defined(STATIC_TRANSLATOR) +#if !defined(CONFIG_SYMBEX) #if defined(CONFIG_SYMBEX_OPCODES) #include diff --git a/libcpu/src/target-i386/translate.c b/libcpu/src/target-i386/translate.c index 9286b3516..b2a0328b0 100644 --- a/libcpu/src/target-i386/translate.c +++ b/libcpu/src/target-i386/translate.c @@ -2352,10 +2352,6 @@ static inline void gen_goto_tb(DisasContext *s, int tb_num, target_ulong eip) { pc = s->cs_base + eip; tb = s->tb; -#ifdef STATIC_TRANSLATOR - gen_jmp_im(s, eip); - tcg_gen_exit_tb(tb, eip); -#else /* NOTE: we handle the case where the TB spans two pages here */ if ((pc & TARGET_PAGE_MASK) == (tb->pc & TARGET_PAGE_MASK) || (pc & TARGET_PAGE_MASK) == ((s->pc - 1) & TARGET_PAGE_MASK)) { @@ -2377,7 +2373,6 @@ static inline void gen_goto_tb(DisasContext *s, int tb_num, target_ulong eip) { #endif gen_eob(s); } -#endif } static inline void gen_jcc(DisasContext *s, int b, target_ulong val, target_ulong next_eip) { @@ -4637,9 +4632,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start) { next_eip = s->pc - s->cs_base; gen_movtl_T1_im(next_eip); -#if !defined(STATIC_TRANSLATOR) tcg_gen_st_tl(cpu_T[1], tcg_env, offsetof(CPUArchState, return_address)); -#endif gen_push_T1(s); gen_op_jmp_T0(s); @@ -6281,9 +6274,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start) { tval &= 0xffffffff; SET_TB_CALL_EIP(tval); gen_movtl_T0_im(next_eip); -#if !defined(STATIC_TRANSLATOR) tcg_gen_st_tl(cpu_T[0], tcg_env, offsetof(CPUArchState, return_address)); -#endif gen_push_T0(s); gen_jmp(s, tval); } break; @@ -6446,11 +6437,9 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start) { } gen_pop_update(s); s->cc_op = CC_OP_EFLAGS; -/* abort translation because TF flag may change */ -#ifndef STATIC_TRANSLATOR + /* abort translation because TF flag may change */ gen_jmp_im(s, s->pc - s->cs_base); gen_eob(s); -#endif } break; case 0x9e: /* sahf */ @@ -7807,9 +7796,7 @@ static inline void gen_intermediate_code_internal(CPUX86State *env, TranslationB if (max_insns == 0) max_insns = TCG_MAX_INSNS; -#ifndef STATIC_TRANSLATOR gen_tb_start(tb); -#endif #ifdef CONFIG_SYMBEX dc->instrument = 1; @@ -7819,9 +7806,8 @@ static inline void gen_intermediate_code_internal(CPUX86State *env, TranslationB tb->se_tb_type = TB_DEFAULT; tb->se_tb_call_eip = 0; -/* Make sure to refer to the original TB instead of the - temporary one in case we regenerate LLVM bitcode */ -#ifndef STATIC_TRANSLATOR + /* Make sure to refer to the original TB instead of the + temporary one in case we regenerate LLVM bitcode */ tcg_gen_movi_i64(cpu_tmp1_i64, (uint64_t) tb); tcg_gen_st_i64(cpu_tmp1_i64, tcg_env, (int) offsetof(ArchCPU, parent_obj.se_current_tb) - (int) offsetof(ArchCPU, env)); @@ -7829,7 +7815,6 @@ static inline void gen_intermediate_code_internal(CPUX86State *env, TranslationB if (unlikely(*g_sqi.events.on_translate_block_start_signals_count && dc->instrument)) { g_sqi.events.on_translate_block_start(dc, tb, pc_start); } -#endif #endif for (;;) { @@ -7905,19 +7890,9 @@ static inline void gen_intermediate_code_internal(CPUX86State *env, TranslationB gen_eob(dc); break; } - -#if defined(CONFIG_SYMBEX) && defined(STATIC_TRANSLATOR) - if (tb->last_pc && dc->insPc == tb->last_pc) { - gen_jmp_im(dc, pc_ptr - dc->cs_base); - gen_eob(dc); - break; - } -#endif } -#ifndef STATIC_TRANSLATOR gen_tb_end(tb); -#endif #ifdef CONFIG_SYMBEX if (dc->invalid_instr) { diff --git a/libcpu/src/translate-all.c b/libcpu/src/translate-all.c index 49319b8fd..164e5ca1f 100644 --- a/libcpu/src/translate-all.c +++ b/libcpu/src/translate-all.c @@ -37,7 +37,7 @@ #include "cpu.h" #include "timer.h" -#if defined(CONFIG_SYMBEX_MP) || defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX_MP) #include #endif @@ -69,11 +69,6 @@ static void *qemu_st_helpers[(MO_SIZE | MO_BSWAP) + 1] = {[MO_UB] = helper_stb_m [MO_LEUW] = helper_stw_mmu_symb, [MO_LEUL] = helper_stl_mmu_symb, [MO_LEUQ] = helper_stq_mmu_symb}; -#elif defined(STATIC_TRANSLATOR) - -static void *qemu_ld_helpers[(MO_SIZE | MO_BSWAP) + 1] = {0}; -static void *qemu_st_helpers[(MO_SIZE | MO_BSWAP) + 1] = {0}; - #else tcg_target_ulong tcg_helper_ldb_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); tcg_target_ulong tcg_helper_ldw_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); @@ -242,7 +237,7 @@ int cpu_gen_code(CPUArchState *env, TranslationBlock *tb) { tb->tc.size = gen_code_size; -#if defined(CONFIG_SYMBEX_MP) || defined(STATIC_TRANSLATOR) +#if defined(CONFIG_SYMBEX_MP) if (env_cpu(env)->generate_llvm) { assert(tb->llvm_function == NULL); tb->llvm_function = tcg_llvm_gen_code(tcg_llvm_translator, s, tb); diff --git a/libtcg/include/tcg/tb.h b/libtcg/include/tcg/tb.h index 09ea0cc97..9f3acec58 100644 --- a/libtcg/include/tcg/tb.h +++ b/libtcg/include/tcg/tb.h @@ -152,10 +152,6 @@ struct TranslationBlock { /* Indicates whether there are execution handlers attached */ int instrumented; -#ifdef STATIC_TRANSLATOR - /* pc after which to stop the translation */ - target_ulong last_pc; -#endif #endif }; diff --git a/tools/include/Translator/Translator.h b/tools/include/Translator/Translator.h deleted file mode 100644 index 20e8c91a7..000000000 --- a/tools/include/Translator/Translator.h +++ /dev/null @@ -1,290 +0,0 @@ -/// -/// Copyright (C) 2016, Dependable Systems Laboratory, EPFL -/// Copyright (C) 2014-2017, Cyberhaven -/// -/// Permission is hereby granted, free of charge, to any person obtaining a copy -/// of this software and associated documentation files (the "Software"), to deal -/// in the Software without restriction, including without limitation the rights -/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -/// copies of the Software, and to permit persons to whom the Software is -/// furnished to do so, subject to the following conditions: -/// -/// The above copyright notice and this permission notice shall be included in all -/// copies or substantial portions of the Software. -/// -/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -/// SOFTWARE. -/// - -#ifndef STATIC_X86TRANSLATOR_H - -#define STATIC_X86TRANSLATOR_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include "lib/Utils/Log.h" - -class TCGLLVMTranslator; - -namespace s2etools { - -class InvalidAddressException { - uintptr_t m_address; - unsigned m_size; - -public: - InvalidAddressException(uintptr_t address, unsigned size) { - m_address = address; - m_size = size; - } - - uintptr_t getAddress() const { - return m_address; - } -}; - -class TranslatorNotInitializedException {}; - -class TranslatorException { - std::string m_message; - -public: - TranslatorException(const std::string &msg) { - m_message = msg; - } -}; - -enum ETranslatedBlockType { - BB_DEFAULT = 0, - BB_JMP, - BB_JMP_IND, - BB_COND_JMP, - BB_REP, - BB_COND_JMP_IND, - BB_CALL, - BB_CALL_IND, - BB_RET, - BB_EXCP -}; - -/** - * This holds a translated block of machine code to LLVM. - * The block may correspond to one machine instruction or - * contain the translation for several instructions, depending - * on the translation mode. - */ -class TranslatedBlock { -public: - typedef llvm::SmallVector Successors; - typedef llvm::SmallVector Stores; - -private: - static LogKey TAG; - - /* Linear address of the instruction */ - uint64_t m_address; - - /* Address of the last instruction */ - uint64_t m_lastAddress; - - /* Raw LLVM representation of the instruction */ - llvm::Function *m_function; - - /* Successors */ - Successors m_successors; - - /* Last instructions that assign the program counter */ - Stores m_lastPcAssignments; - - /* Type of the instruction determined by the translator */ - ETranslatedBlockType m_type; - - /* Size of the machine instruction */ - unsigned m_size; - -public: - TranslatedBlock() { - m_address = 0; - m_lastAddress = 0; - m_size = 0; - m_function = NULL; - m_type = BB_DEFAULT; - } - - TranslatedBlock(uint64_t address, uint64_t lastAddress, unsigned size, llvm::Function *f, ETranslatedBlockType type, - const Successors &succs, const Stores &pcstores) { - m_address = address; - m_lastAddress = lastAddress; - m_size = size; - m_function = f; - m_type = type; - m_successors = succs; - m_lastPcAssignments = pcstores; - } - - bool isIndirectJump() const { - return m_type == BB_JMP_IND || m_type == BB_COND_JMP_IND; - } - - bool isCallInstruction() const { - return m_type == BB_CALL || m_type == BB_CALL_IND; - } - - bool operator<(const TranslatedBlock &bb) const { - return m_address + m_size <= bb.m_address; - } - - uint64_t getAddress() const { - return m_address; - } - - uint64_t getLastAddress() const { - return m_lastAddress; - } - - unsigned getSize() const { - return m_size; - } - - llvm::Function *getFunction() const { - return m_function; - } - - // Must not be used after the TB is created - void setFunction(llvm::Function *func) { - m_function = func; - } - - ETranslatedBlockType getType() const { - return m_type; - } - - const Successors &getSuccessors() const { - return m_successors; - } - - const Stores &getLastPcAssignments() const { - return m_lastPcAssignments; - } - - llvm::StoreInst *getLastPcAssignment() const { - assert(m_lastPcAssignments.size() >= 1); - return m_lastPcAssignments.back(); - } - - inline uint64_t getSuccessor(unsigned i) const { - return m_successors[i]; - } - - void print(llvm::raw_ostream &os) const; -}; - -class Translator { -public: - struct RegisterMask { - uint64_t rmask, wmask, accesses_mem; - }; - - typedef llvm::SmallVector MemoryWrappers; - -private: - static LogKey TAG; - std::shared_ptr m_binary; - static bool s_translatorInited; - bool m_singlestep; - std::unique_ptr m_module; - -protected: - TCGLLVMTranslator *m_ctx; - -public: - Translator(const std::string &bitcodeLibrary, const std::shared_ptr binary); - - virtual ~Translator(); - - const std::shared_ptr getBinaryFile() const { - return m_binary; - } - - virtual TranslatedBlock *translate(uint64_t address, uint64_t lastAddress) = 0; - - bool isInitialized() { - return s_translatorInited; - } - - virtual bool isSingleStep() const { - return m_singlestep; - } - - virtual void setSingleStep(bool b) { - m_singlestep = b; - } - - static void getRetInstructions(llvm::Function *f, llvm::SmallVector &ret); - - llvm::Module *getModule() const; - - llvm::Function *createTbFunction(const std::string &name) const; - llvm::FunctionType *getTbType() const; - - static unsigned getTargetPtrSizeInBytes(); - static bool isGpRegister(llvm::Value *gep, unsigned reg); - static bool isGpRegister(llvm::Value *gep, unsigned *regIndex = NULL); - static bool isPcRegister(llvm::Value *gep); - - static void getWrappers(llvm::Module &M, MemoryWrappers &wrappers, const char **names); - static void getStoreWrappers(llvm::Module &M, MemoryWrappers &wrappers); - static void getLoadWrappers(llvm::Module &M, MemoryWrappers &wrappers); - - static llvm::Value *getPcPtr(llvm::IRBuilder<> &builder); - - static RegisterMask getRegisterMaskForHelper(llvm::Function *helper); - static uint64_t getRegisterBitMask(llvm::Value *gep); -}; - -class X86Translator : public Translator { -public: -private: - static LogKey TAG; - static const char *s_regNames[8]; - llvm::legacy::FunctionPassManager *m_functionPasses; - llvm::legacy::FunctionPassManager *m_functionOptPasses; - -public: - X86Translator(const std::string &bitcodeLibrary, const std::shared_ptr binary); - virtual ~X86Translator(); - - virtual TranslatedBlock *translate(uint64_t address, uint64_t lastAddress); - - enum Registers { - // REG_ prevents collisions with QEMU - REG_EAX = 0, - REG_ECX = 1, - REG_EDX = 2, - REG_EBX = 3, - REG_ESP = 4, - REG_EBP = 5, - REG_ESI = 6, - REG_EDI = 7 - }; - - static std::string getRegisterName(unsigned reg) { - assert(reg < 8); - return s_regNames[reg]; - } -}; -} // namespace s2etools - -#endif diff --git a/tools/include/Translator/TranslatorInternal.h b/tools/include/Translator/TranslatorInternal.h deleted file mode 100644 index 75709c6de..000000000 --- a/tools/include/Translator/TranslatorInternal.h +++ /dev/null @@ -1,587 +0,0 @@ -/// -/// Copyright (C) 2016, Dependable Systems Laboratory, EPFL -/// Copyright (C) 2014-2017, Cyberhaven -/// -/// Permission is hereby granted, free of charge, to any person obtaining a copy -/// of this software and associated documentation files (the "Software"), to deal -/// in the Software without restriction, including without limitation the rights -/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -/// copies of the Software, and to permit persons to whom the Software is -/// furnished to do so, subject to the following conditions: -/// -/// The above copyright notice and this permission notice shall be included in all -/// copies or substantial portions of the Software. -/// -/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -/// SOFTWARE. -/// - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Translator.h" - -#include "lib/Utils/Log.h" -#include "lib/Utils/Utils.h" - -#include - -#include - -extern "C" { -#include -#include -#include -#include -} - -using namespace llvm; -namespace s2etools { - -std::shared_ptr s_currentBinary; -bool Translator::s_translatorInited = false; -LogKey TranslatedBlock::TAG = LogKey("TranslatedBlock"); -LogKey Translator::TAG = LogKey("Translator"); -LogKey X86Translator::TAG = LogKey("X86Translator"); - -/***************************************************************************** - * The following functions are invoked by the QEMU translator to read code. - * This library redirects them to the binary file - *****************************************************************************/ -template static T read_binary(off64_t offset) { - T buf; - if (s_currentBinary->read(&buf, sizeof(T), offset) != sizeof(T)) { - throw InvalidAddressException(offset, sizeof(T)); - } - return buf; -} - -extern "C" { - -int cpu_ldsb_code(CPUX86State *env, target_ulong ptr) { - return (int) read_binary(ptr); -} - -uint32_t cpu_ldub_code(CPUX86State *env, target_ulong ptr) { - return read_binary(ptr); -} - -uint32_t cpu_lduw_code(CPUX86State *env, target_ulong ptr) { - return read_binary(ptr); -} - -int cpu_ldsw_code(CPUX86State *env, target_ulong ptr) { - return (int) (int16_t) read_binary(ptr); -} - -uint32_t cpu_ldl_code(CPUX86State *env, target_ulong ptr) { - return read_binary(ptr); -} - -uint64_t cpu_ldq_code(CPUX86State *env, target_ulong ptr) { - return read_binary(ptr); -} - -uint8_t helper_ldb_mmu_symb(CPUX86State *env, target_ulong addr, int mmu_idx, void *retaddr) { - abort(); -} - -void helper_stb_mmu_symb(CPUX86State *env, target_ulong addr, uint8_t val, int mmu_idx, void *retaddr) { - abort(); -} - -uint16_t helper_ldw_mmu_symb(CPUX86State *env, target_ulong addr, int mmu_idx, void *retaddr) { - abort(); -} - -void helper_stw_mmu_symb(CPUX86State *env, target_ulong addr, uint16_t val, int mmu_idx, void *retaddr) { - abort(); -} - -uint32_t helper_ldl_mmu_symb(CPUX86State *env, target_ulong addr, int mmu_idx, void *retaddr) { - abort(); -} - -void helper_stl_mmu_symb(CPUX86State *env, target_ulong addr, uint32_t val, int mmu_idx, void *retaddr) { - abort(); -} - -uint64_t helper_ldq_mmu_symb(CPUX86State *env, target_ulong addr, int mmu_idx, void *retaddr) { - abort(); -} - -void helper_stq_mmu_symb(CPUX86State *env, target_ulong addr, uint64_t val, int mmu_idx, void *retaddr) { - abort(); -} -} - -/*****************************************************************************/ -void TranslatedBlock::print(llvm::raw_ostream &os) const { - os << "TB at 0x" << hexval(m_address) << " type=0x" << m_type << " size=0x" << m_size << '\n'; - - unsigned i = 0; - for (auto const &successor : m_successors) { - os << "succ[" << i << "]=0x" << hexval(successor) << '\n'; - ++i; - } - os << *m_function << '\n'; -} - -/*****************************************************************************/ - -using namespace llvm; - -extern "C" { -void optimize_flags_init(void); -} - -Translator::Translator(const std::string &bitcodeLibrary, const std::shared_ptr binary) { - m_binary = binary; - s_currentBinary = binary; - m_singlestep = false; - - if (s_translatorInited) { - return; - } - - tcg_exec_init(0); - optimize_flags_init(); - - m_ctx = TCGLLVMTranslator::create(bitcodeLibrary); - - s_translatorInited = true; -} - -Translator::~Translator() { - if (s_translatorInited) { - delete m_ctx; - s_translatorInited = false; - } -} - -llvm::Module *Translator::getModule() const { - return m_ctx->getModule(); -} - -llvm::Function *Translator::createTbFunction(const std::string &name) const { - return m_ctx->createTbFunction(name); -} - -llvm::FunctionType *Translator::getTbType() const { - return m_ctx->tbType(); -} - -void Translator::getRetInstructions(llvm::Function *f, llvm::SmallVector &ret) { - foreach2 (it, f->begin(), f->end()) { - BasicBlock &bb = *it; - ReturnInst *ti = dyn_cast(bb.getTerminator()); - if (ti) { - ret.push_back(ti); - } - } -} - -unsigned Translator::getTargetPtrSizeInBytes() { - return sizeof(target_ulong); -} - -bool Translator::isGpRegister(llvm::Value *gepv, unsigned *regIndex) { - if (!dyn_cast(gepv)) { - ConstantExpr *ce = dyn_cast(gepv); - if (!ce || (ce->getOpcode() != Instruction::GetElementPtr)) { - return false; - } - } - - User *gep = dyn_cast(gepv); - - if (gep->getNumOperands() != 4) { - return false; - } - - ConstantInt *c1 = dyn_cast(gep->getOperand(1)); - ConstantInt *c2 = dyn_cast(gep->getOperand(2)); - ConstantInt *c3 = dyn_cast(gep->getOperand(3)); - if (!c1 || !c2 || !c3) { - return false; - } - - bool isGp = !c1->getZExtValue() && !c2->getZExtValue(); - - if (regIndex) { - *regIndex = c3->getZExtValue(); - } - - return isGp; -} - -bool Translator::isGpRegister(Value *gep, unsigned reg) { - unsigned ret; - bool b = isGpRegister(gep, &ret); - if (!b) { - return false; - } - return ret == reg; -} - -bool Translator::isPcRegister(Value *gepv) { - if (!dyn_cast(gepv)) { - ConstantExpr *ce = dyn_cast(gepv); - if (!ce || (ce->getOpcode() != Instruction::GetElementPtr)) { - return false; - } - } - - User *gep = dyn_cast(gepv); - - if (gep->getNumOperands() != 3) { - return false; - } - - ConstantInt *c1 = dyn_cast(gep->getOperand(1)); - ConstantInt *c2 = dyn_cast(gep->getOperand(2)); - if (!c1 || !c2) { - return false; - } - - return !c1->getZExtValue() && c2->getZExtValue() == 5; -} - -void Translator::getWrappers(llvm::Module &M, MemoryWrappers &wrappers, const char **names) { - for (unsigned i = 0; i < 4; ++i) { - Function *f = M.getFunction(names[i]); - assert(f); - wrappers.push_back(f); - } -} - -void Translator::getStoreWrappers(llvm::Module &M, MemoryWrappers &wrappers) { - const char *names[] = {"helper_stb_mmu", "helper_stw_mmu", "helper_stl_mmu", "helper_stq_mmu"}; - getWrappers(M, wrappers, names); -} - -void Translator::getLoadWrappers(llvm::Module &M, MemoryWrappers &wrappers) { - const char *names[] = {"helper_ldb_mmu", "helper_ldw_mmu", "helper_ldl_mmu", "helper_ldq_mmu"}; - getWrappers(M, wrappers, names); -} - -Value *Translator::getPcPtr(IRBuilder<> &builder) { - Module *m = builder.GetInsertBlock()->getParent()->getParent(); - LLVMContext &ctx = m->getContext(); - GlobalVariable *v = m->getGlobalVariable("myenv"); - Value *arg = builder.Insert(GetElementPtrInst::Create(nullptr, v, ConstantInt::get(ctx, APInt(64, 0)))); - - SmallVector gepElements; - gepElements.push_back(ConstantInt::get(m->getContext(), APInt(32, 0))); - gepElements.push_back(ConstantInt::get(m->getContext(), APInt(32, 5))); - return builder.CreateGEP(arg->getType()->getPointerElementType(), arg, - ArrayRef(gepElements.begin(), gepElements.end())); -} - -Translator::RegisterMask Translator::getRegisterMaskForHelper(llvm::Function *helper) { - Translator::RegisterMask mask; - mask.rmask = -1; - mask.wmask = -1; - mask.accesses_mem = 1; - return mask; -} - -uint64_t Translator::getRegisterBitMask(llvm::Value *gepv) { - if (!isGpRegister(gepv)) { - return -1; - } - - User *gep = dyn_cast(gepv); - - ConstantInt *c1, *c2, *c3; - c1 = c2 = c3 = NULL; - - c1 = dyn_cast(gep->getOperand(1)); - assert(c1 && c1->getZExtValue() == 0); - - c2 = dyn_cast(gep->getOperand(2)); - assert(c2); - - c3 = dyn_cast(gep->getOperand(3)); - - if (c2->getZExtValue() == 0 && c3) { - /* General purpose register */ - return 1LL << (c3->getZExtValue() + 5); - } - - if (!c3 && c2->getZExtValue() < 5) { - /* cc_op .. cc_tmp */ - return 1LL << (c2->getZExtValue() - 1); - } - - assert(false && "Unsupported gep instruction"); - return 0; -} - -/*****************************************************************************/ - -const char *X86Translator::s_regNames[8] = {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"}; - -X86Translator::X86Translator(const std::string &bitcodeLibrary, const std::shared_ptr binary) - : Translator(bitcodeLibrary, binary) { - m_functionPasses = new legacy::FunctionPassManager(m_ctx->getModule()); - m_functionPasses->add(createCFGSimplificationPass()); - - // We need this passes to simplify the translation of the instruction. - // The code is quite bulky, the fewer instructions, the better. - m_functionOptPasses = new legacy::FunctionPassManager(m_ctx->getModule()); - // m_functionOptPasses->add(createVerifierPass()); - m_functionOptPasses->add(createDeadCodeEliminationPass()); - m_functionOptPasses->add(createGVNPass()); -} - -X86Translator::~X86Translator() { - delete m_functionPasses; - delete m_functionOptPasses; -} - -static const uint64_t I486_FEATURES = (CPUID_FP87 | CPUID_VME | CPUID_PSE); - -static const uint64_t PENTIUM_FEATURES = - (I486_FEATURES | CPUID_DE | CPUID_TSC | CPUID_MSR | CPUID_MCE | CPUID_CX8 | CPUID_MMX | CPUID_APIC); - -static const uint64_t PENTIUM2_FEATURES = (PENTIUM_FEATURES | CPUID_PAE | CPUID_SEP | CPUID_MTRR | CPUID_PGE | - CPUID_MCA | CPUID_CMOV | CPUID_PAT | CPUID_PSE36 | CPUID_FXSR); - -static const uint64_t PENTIUM3_FEATURES = (PENTIUM2_FEATURES | CPUID_SSE); - -static const uint64_t PPRO_FEATURES = - (CPUID_FP87 | CPUID_DE | CPUID_PSE | CPUID_TSC | CPUID_MSR | CPUID_MCE | CPUID_CX8 | CPUID_PGE | CPUID_CMOV | - CPUID_PAT | CPUID_FXSR | CPUID_MMX | CPUID_SSE | CPUID_SSE2 | CPUID_PAE | CPUID_SEP | CPUID_APIC); - -static const uint64_t EXT2_FEATURE_MASK = 0x0183F3FF; - -static const uint64_t TCG_FEATURES = - (CPUID_FP87 | CPUID_DE | CPUID_PSE | CPUID_TSC | CPUID_MSR | CPUID_PAE | CPUID_MCE | CPUID_CX8 | CPUID_APIC | - CPUID_SEP | CPUID_MTRR | CPUID_PGE | CPUID_MCA | CPUID_CMOV | CPUID_PAT | CPUID_PSE36 | CPUID_CLFLUSH | - CPUID_ACPI | CPUID_MMX | CPUID_FXSR | CPUID_SSE | CPUID_SSE2 | CPUID_SS); -/* partly implemented: -CPUID_MTRR, CPUID_MCA, CPUID_CLFLUSH (needed for Win64) -CPUID_PSE36 (needed for Solaris) */ -/* missing: -CPUID_VME, CPUID_DTS, CPUID_SS, CPUID_HT, CPUID_TM, CPUID_PBE */ - -static const uint64_t TCG_EXT_FEATURES = - (CPUID_EXT_SSE3 | CPUID_EXT_MONITOR | CPUID_EXT_CX16 | CPUID_EXT_POPCNT | CPUID_EXT_HYPERVISOR); -/* missing: -CPUID_EXT_DTES64, CPUID_EXT_DSCPL, CPUID_EXT_VMX, CPUID_EXT_EST, -CPUID_EXT_TM2, CPUID_EXT_XTPR, CPUID_EXT_PDCM, CPUID_EXT_XSAVE */ - -static const uint64_t TCG_EXT2_FEATURES = ((TCG_FEATURES & EXT2_FEATURE_MASK) | CPUID_EXT2_NX | CPUID_EXT2_MMXEXT | - CPUID_EXT2_RDTSCP | CPUID_EXT2_3DNOW | CPUID_EXT2_3DNOWEXT); -/* missing: -CPUID_EXT2_PDPE1GB */ -static const uint64_t TCG_EXT3_FEATURES = - (CPUID_EXT3_LAHF_LM | CPUID_EXT3_SVM | CPUID_EXT3_CR8LEG | CPUID_EXT3_ABM | CPUID_EXT3_SSE4A); - -TranslatedBlock *X86Translator::translate(uint64_t address, uint64_t lastAddress) { - static uint8_t s_dummyBuffer[10 * 1024 * 1024]; - CPUArchState env; - TranslationBlock *tb; - - if (!isInitialized()) { - throw TranslatorNotInitializedException(); - } - - memset(&env, 0, sizeof(env)); - - tb = tcg_tb_alloc(tcg_ctx); - if (unlikely(tb == NULL)) { - abort(); - } - - memset(tb, 0, sizeof(*tb)); - - QTAILQ_INIT(&env.breakpoints); - QTAILQ_INIT(&env.watchpoints); - - int codeSize; - - // We translate only one instruction at a time. - // It is much easier to rebuild basic blocks this way. - env.singlestep_enabled = isSingleStep(); - - env.cpuid.cpuid_features = PPRO_FEATURES | CPUID_MTRR | CPUID_CLFLUSH | CPUID_MCA | CPUID_PSE36; - - env.cpuid.cpuid_ext_features = CPUID_EXT_SSE3 | CPUID_EXT_CX16 | CPUID_EXT_POPCNT; - - env.cpuid.cpuid_ext2_features = - (PPRO_FEATURES & EXT2_FEATURE_MASK) | CPUID_EXT2_LM | CPUID_EXT2_SYSCALL | CPUID_EXT2_NX; - - env.cpuid.cpuid_ext3_features = CPUID_EXT3_LAHF_LM | CPUID_EXT3_SVM | CPUID_EXT3_ABM | CPUID_EXT3_SSE4A; - - env.generate_llvm = 1; - - env.eip = address; - tb->pc = env.eip; - tb->last_pc = lastAddress; - tb->cs_base = 0; - tb->tc.ptr = s_dummyBuffer; - - /* init jump list */ - tb->jmp_lock = SPIN_LOCK_UNLOCKED; - tb->jmp_list_head = (uintptr_t) NULL; - tb->jmp_list_next[0] = (uintptr_t) NULL; - tb->jmp_list_next[1] = (uintptr_t) NULL; - tb->jmp_dest[0] = (uintptr_t) NULL; - tb->jmp_dest[1] = (uintptr_t) NULL; - - switch (getBinaryFile()->getPointerSize()) { - case 4: - tb->flags = (1 << HF_PE_SHIFT) | (1 << HF_CS32_SHIFT) | (1 << HF_SS32_SHIFT); - break; - - case 8: - tb->flags = (1 << HF_PE_SHIFT) | (1 << HF_CS32_SHIFT) | (1 << HF_SS32_SHIFT) | (1 << HF_CS64_SHIFT) | - (1 << HF_LMA_SHIFT); - break; - default: - assert(false && "not implemented"); - break; - } - - tb->flags |= 3 | HF_SOFTMMU_MASK | HF_OSFXSR_MASK; // CPL=3 - - // May throw InvalidAddressException - cpu_gen_code(&env, tb); - - LOGDEBUG(*(Function *) tb->llvm_function); - - LOGDEBUG("tb type: " << hexval(tb->se_tb_type) << "\n"); - - ETranslatedBlockType bbType; - switch (tb->se_tb_type) { - case TB_DEFAULT: - bbType = BB_DEFAULT; - break; - case TB_JMP: - bbType = BB_JMP; - break; - case TB_JMP_IND: - bbType = BB_JMP_IND; - break; - case TB_COND_JMP: - bbType = BB_COND_JMP; - break; - case TB_COND_JMP_IND: - bbType = BB_COND_JMP_IND; - break; - case TB_CALL: - bbType = BB_CALL; - break; - case TB_CALL_IND: - bbType = BB_CALL_IND; - break; - case TB_REP: - bbType = BB_REP; - break; - case TB_RET: - bbType = BB_RET; - break; - case TB_EXCP: - bbType = BB_EXCP; - break; - case TB_INTERRUPT: - bbType = BB_DEFAULT; - break; - default: - assert(false && "Unsupported translation block type"); - } - - TCGLLVMTBInfo info = m_ctx->getTbInfo(); - - /// Check if TB type matches number of static targets. - /// Sometimes, we have things like mov eax, constant; jmp eax, - /// which is reported as indirect jump, but really is a direct - /// one. Need to handle this case. - switch (tb->se_tb_type) { - case TB_DEFAULT: - case TB_JMP: - case TB_CALL: - if (info.staticBranchTargets.size() != 1) { - LOGERROR("TB " << hexval(address) << " static targets mismatch TB type\n"); - return NULL; - } - break; - - case TB_COND_JMP: - case TB_REP: - if (info.staticBranchTargets.size() != 2) { - LOGERROR("TB " << hexval(address) << " static targets mismatch TB type\n"); - return NULL; - } - break; - - case TB_JMP_IND: - case TB_COND_JMP_IND: - case TB_CALL_IND: - - case TB_RET: - case TB_IRET: - case TB_EXCP: - case TB_SYSENTER: - if (info.staticBranchTargets.size() != 0) { - LOGERROR("TB " << hexval(address) << " static targets mismatch TB type\n"); - return NULL; - } - break; - - case TB_INTERRUPT: - info.staticBranchTargets.clear(); - info.staticBranchTargets.push_back(tb->pc + tb->size); - break; - - default: - abort(); - } - - /* Make sure that we don't ask to translate a block that is actually shorter */ - if (tb->pcOfLastInstr != lastAddress) { - /* XXX: sometimes TBs may be to big, QEMU stops translating when - it runs out of buffer space. Could split the BB in multiple chunks. */ - LOGERROR("Translation didn't finish at bb end (" << hexval(tb->pcOfLastInstr) << " instead of " - << hexval(lastAddress) << ")\n"); - - return NULL; - } - assert(tb->pcOfLastInstr == lastAddress); - - /* Handle call $+5 instructions, used to push the address of the next instruction */ - if (tb->se_tb_type == TB_CALL) { - uint64_t target = info.staticBranchTargets[0]; - if (target == address + tb->size) { - bbType = BB_DEFAULT; - info.staticBranchTargets.clear(); - } - } - - TranslatedBlock *ret = new TranslatedBlock(address, lastAddress, tb->size, (Function *) tb->llvm_function, bbType, - info.staticBranchTargets, info.pcAssignments); - - m_functionPasses->run(*ret->getFunction()); - - for (auto const &branchTarget : info.staticBranchTargets) { - LOGDEBUG("Branch target: " << hexval(branchTarget) << "\n"); - } - - return ret; -} -} // namespace s2etools diff --git a/tools/include/Translator/TranslatorWrapper.h b/tools/include/Translator/TranslatorWrapper.h deleted file mode 100644 index 8be4d9372..000000000 --- a/tools/include/Translator/TranslatorWrapper.h +++ /dev/null @@ -1,43 +0,0 @@ -/// -/// Copyright (C) 2014-2017, Cyberhaven -/// -/// Permission is hereby granted, free of charge, to any person obtaining a copy -/// of this software and associated documentation files (the "Software"), to deal -/// in the Software without restriction, including without limitation the rights -/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -/// copies of the Software, and to permit persons to whom the Software is -/// furnished to do so, subject to the following conditions: -/// -/// The above copyright notice and this permission notice shall be included in all -/// copies or substantial portions of the Software. -/// -/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -/// SOFTWARE. -/// - -#ifndef STATIC_X86TRANSLATOR_WRAPPER_H - -#define STATIC_X86TRANSLATOR_WRAPPER_H - -namespace s2e { -class S2E {}; - -class S2EExecutionState {}; -} // namespace s2e - -#ifdef __cplusplus -extern "C" { -#endif - -struct TranslationBlock; -struct CPUX86State; -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/include/Translator/TranslatorWrapperInternal.h b/tools/include/Translator/TranslatorWrapperInternal.h deleted file mode 100644 index 9817eeb39..000000000 --- a/tools/include/Translator/TranslatorWrapperInternal.h +++ /dev/null @@ -1,696 +0,0 @@ -/// -/// Copyright (C) 2016, Dependable Systems Laboratory, EPFL -/// Copyright (C) 2014-2017, Cyberhaven -/// -/// Permission is hereby granted, free of charge, to any person obtaining a copy -/// of this software and associated documentation files (the "Software"), to deal -/// in the Software without restriction, including without limitation the rights -/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -/// copies of the Software, and to permit persons to whom the Software is -/// furnished to do so, subject to the following conditions: -/// -/// The above copyright notice and this permission notice shall be included in all -/// copies or substantial portions of the Software. -/// -/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -/// SOFTWARE. -/// - -#include -#include -#include -#include -#include - -#include - -extern "C" { -#include -#include -#include -} - -#include "TranslatorWrapper.h" - -s2e::S2EExecutionStatePtr g_s2e_state = NULL; -s2e::S2E *g_s2e = NULL; - -extern "C" { - -static unsigned s_count = 0; - -int g_s2e_fork_on_symbolic_address = 0; -int g_s2e_allow_custom_instructions = 0; - -int execute_llvm = 0; -int kvm_allowed = 0; - -int singlestep = 0; -int loglevel = 0; -int use_icount = 0; -int64_t qemu_icount = 0; -FILE *logfile = stdout; -CPUArchState *first_cpu; -CPUArchState *cpu_single_env; - -CPUInterruptHandler cpu_interrupt_handler; - -#define code_gen_section __attribute__((aligned(32))) -uint8_t code_gen_prologue[1024] code_gen_section; - -// CPUWriteMemoryFunc *io_mem_write[IO_MEM_NB_ENTRIES][4]; -// CPUReadMemoryFunc *io_mem_read[IO_MEM_NB_ENTRIES][4]; -// void *io_mem_opaque[IO_MEM_NB_ENTRIES]; - -static int is_tb_instrumented(void *se_tb) { - return 0; -} - -static void set_tb_function(void *se_tb, void *llvmFunction) { - return; -} - -static void on_privilege_change(unsigned previous, unsigned current) { - return; -} - -static void on_page_directory_change(uint64_t previous, uint64_t current) { - return; -} - -static void on_page_fault(uint64_t addr, int is_write, void *retaddr) { - return; -} - -static void on_tlb_miss(uint64_t addr, int is_write, void *retaddr) { - return; -} - -static void after_memory_access(uint64_t vaddr, uint64_t value, unsigned size, unsigned flags, uintptr_t retaddr) { - return; -} - -static void trace_port_access(uint64_t port, uint64_t value, unsigned bits, int isWrite, void *retaddr) { - return; -} - -static void tcg_execution_handler(void *signal, uint64_t pc) { - return; -} - -static void tcg_custom_instruction_handler(uint64_t arg) { - return; -} - -static void tcg_emit_custom_instruction(uint64_t arg) { - return; -} - -static void on_translate_soft_interrupt_start(void *context, struct TranslationBlock *tb, uint64_t pc, - unsigned vector) { - return; -} - -static void on_translate_block_start(void *context, struct TranslationBlock *tb, uint64_t pc) { - return; -} - -static void on_translate_block_end(struct TranslationBlock *tb, uint64_t insPc, int staticTarget, uint64_t targetPc) { - return; -} - -static void on_translate_block_complete(struct TranslationBlock *tb, uint64_t pc) { - return; -} - -static void on_translate_instruction_start(void *context, struct TranslationBlock *tb, uint64_t pc) { - return; -} - -static void on_translate_special_instruction_end(void *context, struct TranslationBlock *tb, uint64_t pc, - enum special_instruction_t type, - const special_instruction_data_t *data, int update_pc) { - return; -} - -static void on_translate_instruction_end(void *context, struct TranslationBlock *tb, uint64_t pc, uint64_t nextpc) { - return; -} - -static void on_translate_jump_start(void *context, struct TranslationBlock *tb, uint64_t pc, int jump_type) { - return; -} - -static void on_translate_indirect_cti_start(void *context, struct TranslationBlock *tb, uint64_t pc, int rm, int op, - int offset) { - return; -} - -static void on_translate_lea_rip_relative(void *context, struct TranslationBlock *tb, uint64_t pc, uint64_t addr) { - return; -} - -static void on_translate_register_access(struct TranslationBlock *tb, uint64_t pc, uint64_t readMask, - uint64_t writeMask, int isMemoryAccess) { - return; -} - -static int on_call_return_translate(uint64_t pc, int isCall) { - return 0; -} - -// clang-format off -struct se_libcpu_interface_t g_sqi = { - .tb = { - .set_tb_function = set_tb_function, - .is_tb_instrumented = is_tb_instrumented, - }, - .events = { - .before_memory_access_signals_count = &s_count, - .after_memory_access_signals_count = &s_count, - .on_translate_soft_interrupt_signals_count = &s_count, - .on_translate_block_start_signals_count = &s_count, - .on_translate_block_end_signals_count = &s_count, - .on_translate_block_complete_signals_count = &s_count, - .on_translate_instruction_start_signals_count = &s_count, - .on_translate_special_instruction_end_signals_count = &s_count, - .on_translate_jump_start_signals_count = &s_count, - .on_translate_lea_rip_relative_signals_count = &s_count, - .on_translate_instruction_end_signals_count = &s_count, - .on_translate_register_access_signals_count = &s_count, - .on_exception_signals_count = &s_count, - .on_page_fault_signals_count = &s_count, - .on_tlb_miss_signals_count = &s_count, - .on_port_access_signals_count = &s_count, - .on_privilege_change_signals_count = &s_count, - .on_page_directory_change_signals_count = &s_count, - .on_call_return_signals_count = &s_count, - - .on_privilege_change = on_privilege_change, - .on_page_directory_change = on_page_directory_change, - .on_page_fault = on_page_fault, - .on_tlb_miss = on_tlb_miss, - .after_memory_access = after_memory_access, - .trace_port_access = trace_port_access, - .tcg_execution_handler = tcg_execution_handler, - .tcg_custom_instruction_handler = tcg_custom_instruction_handler, - .tcg_emit_custom_instruction = tcg_emit_custom_instruction, - - .on_translate_soft_interrupt_start = on_translate_soft_interrupt_start, - .on_translate_block_start = on_translate_block_start, - .on_translate_block_end = on_translate_block_end, - .on_translate_block_complete = on_translate_block_complete, - .on_translate_instruction_start = on_translate_instruction_start, - .on_translate_special_instruction_end = on_translate_special_instruction_end, - .on_translate_instruction_end = on_translate_instruction_end, - .on_translate_jump_start = on_translate_jump_start, - .on_translate_indirect_cti_start = on_translate_indirect_cti_start, - .on_translate_lea_rip_relative = on_translate_lea_rip_relative, - .on_translate_register_access = on_translate_register_access, - .on_call_return_translate = on_call_return_translate, - } -}; -// clang-format on - -void *qemu_malloc(size_t s) { - return malloc(s); -} - -void *qemu_mallocz(size_t size) { - void *ptr; - ptr = qemu_malloc(size); - memset(ptr, 0, size); - return ptr; -} - -void *qemu_realloc(void *ptr, size_t size) { - return realloc(ptr, size); -} - -void qemu_free(void *ptr) { - free(ptr); -} - -void qemu_init_vcpu(void *_env) { -} - -extern "C" { -void target_disas(void *env, FILE *out, target_ulong code, target_ulong size, int flags) { - assert(false && "Not usable statically"); -} - -void disas(void *env, FILE *out, void *code, unsigned long size) { - assert(false && "Not usable statically"); -} - -void host_disas(FILE *out, void *pc, size_t size) { - assert(false && "Not usable statically"); -} - -const char *lookup_symbol(target_ulong orig_addr) { - assert(false && "Not usable statically"); - return NULL; -} - -void tb_reset_jump(TranslationBlock *tb, int n) { - assert(false && "Not usable statically"); -} - -void LIBCPU_NORETURN cpu_loop_exit_restore(CPUArchState *env1, uintptr_t ra) { - assert(false && "Not usable statically"); -} - -void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr) { - assert(false && "Not usable statically"); -} -} - -int s2e_is_tb_instrumented(void *tb) { - return 0; -} - -int s2e_is_running_concrete() { - return 0; -} - -void s2e_set_tb_function(TranslationBlock *tb) { -} - -void s2e_tcg_emit_custom_instruction(uint64_t arg) { - assert(false && "Not usable statically"); -} - -void s2e_trace_port_access(uint64_t port, uint64_t value, unsigned bits, int isWrite, void *retaddr) { - assert(false && "Not usable statically"); -} - -int s2e_is_port_symbolic(uint64_t port) { - assert(false && "Not usable statically"); - return 0; -} - -int se_is_mmio_symbolic(struct MemoryDesc *mr, uint64_t address, uint64_t size) { - assert(false && "Not usable statically"); - return 0; -} - -int se_is_mmio_symbolic_b(struct MemoryDesc *mr, uint64_t address) { - assert(false && "Not usable statically"); - return 0; -} - -int se_is_mmio_symbolic_w(struct MemoryDesc *mr, uint64_t address) { - assert(false && "Not usable statically"); - return 0; -} - -int se_is_mmio_symbolic_l(struct MemoryDesc *mr, uint64_t address) { - assert(false && "Not usable statically"); - return 0; -} - -int se_is_mmio_symbolic_q(struct MemoryDesc *mr, uint64_t address) { - assert(false && "Not usable statically"); - return 0; -} - -void s2e_on_translate_block_start(void *context, struct TranslationBlock *tb, uint64_t pc) { -} - -void s2e_on_translate_block_end(struct TranslationBlock *tb, uint64_t insPc, int staticTarget, uint64_t targetPc) { -} - -void s2e_on_translate_block_complete(struct TranslationBlock *tb, uint64_t pc) { -} - -void s2e_on_translate_jump_start(void *context, struct TranslationBlock *tb, uint64_t pc, int jump_type) { -} - -void s2e_on_translate_indirect_cti_start(void *context, TranslationBlock *tb, uint64_t pc, int rm, int op, int offset) { -} - -void s2e_on_translate_instruction_start(void *context, struct TranslationBlock *tb, uint64_t pc) { -} - -void s2e_on_translate_instruction_end(void *context, struct TranslationBlock *tb, uint64_t pc, uint64_t nextpc) { -} - -void s2e_on_translate_lea_rip_relative(void *context, struct TranslationBlock *tb, uint64_t pc, uint64_t addr) { -} - -void s2e_on_translate_special_instruction_end(void *context, struct TranslationBlock *tb, uint64_t pc, - enum special_instruction_t type, const special_instruction_data_t *data, - int update_pc) { -} - -void s2e_on_translate_register_access(struct TranslationBlock *tb, uint64_t pc, uint64_t readMask, uint64_t writeMask, - int isMemoryAccess) { -} - -void s2e_on_translate_soft_interrupt_start(void *context, struct TranslationBlock *tb, uint64_t pc, unsigned vector) { -} - -void s2e_on_page_fault(uint64_t addr, int is_write, void *retaddr) { - assert(false && "Not usable statically"); -} - -void s2e_on_page_directory_change(uint64_t previous, uint64_t current) { -} - -void s2e_on_tlb_miss(uint64_t addr, int is_write, void *retaddr) { - assert(false && "Not usable statically"); -} - -void s2e_after_memory_access(uint64_t vaddr, uint64_t value, unsigned size, unsigned flags, uintptr_t retaddr) { - assert(false && "Not usable statically"); -} - -void s2e_read_register_concrete(unsigned offset, uint8_t *buf, unsigned size) { - assert(false && "Not usable statically"); -} - -void s2e_write_register_concrete(unsigned offset, uint8_t *buf, unsigned size) { - assert(false && "Not usable statically"); -} - -void s2e_write_ram_concrete(uint64_t host_address, const uint8_t *buf, uint64_t size) { - assert(false && "Not usable statically"); -} - -void s2e_read_ram_concrete(uint64_t host_address, void *buf, uint64_t size) { - assert(false && "Not usable statically"); -} - -void s2e_switch_to_symbolic(void *retaddr) { - assert(false && "Not usable statically"); -} - -void s2e_read_ram_concrete_check(uint64_t host_address, uint8_t *buf, uint64_t size) { - assert(false && "Not usable statically"); -} - -int s2e_on_call_return_translate(uint64_t pc, int isCall) { - assert(false && "Not usable statically"); -} - -/***** CPU-RELATED WRAPPERS *****/ -void cpu_outb(uint32_t addr, uint8_t val) { - assert(false && "Not usable statically"); -} - -void cpu_outw(uint32_t addr, uint16_t val) { - assert(false && "Not usable statically"); -} - -void cpu_outl(uint32_t addr, uint32_t val) { - assert(false && "Not usable statically"); -} - -uint8_t cpu_inb(uint32_t addr) { - assert(false && "Not usable statically"); - return 0; -} - -uint16_t cpu_inw(uint32_t addr) { - assert(false && "Not usable statically"); - return 0; -} - -uint32_t cpu_inl(uint32_t addr) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_breakpoint_insert(CPUX86State *env, target_ulong pc, int flags, CPUBreakpoint **breakpoint) { - assert(false && "Not usable statically"); -} - -int cpu_breakpoint_remove(CPUArchState *env, target_ulong pc, int flags) { - assert(false && "Not usable statically"); -} - -void cpu_breakpoint_remove_all(CPUArchState *env, int mask) { - assert(false && "Not usable statically"); -} - -void cpu_breakpoint_remove_by_ref(CPUArchState *env, CPUBreakpoint *breakpoint) { - assert(false && "Not usable statically"); -} - -int cpu_watchpoint_insert(CPUArchState *env, target_ulong addr, target_ulong len, int flags, - CPUWatchpoint **watchpoint) { - assert(false && "Not usable statically"); -} - -void cpu_watchpoint_remove_all(CPUArchState *env, int mask) { - assert(false && "Not usable statically"); -} - -void cpu_watchpoint_remove_by_ref(CPUArchState *env, CPUWatchpoint *watchpoint) { - assert(false && "Not usable statically"); -} - -void cpu_io_recompile(CPUArchState *env, void *retaddr) { - assert(false && "Not usable statically"); -} - -uint64_t cpu_get_tsc(CPUX86State *env) { - assert(false && "Not usable statically"); -} - -void cpu_loop_exit(CPUArchState *env) { - assert(false && "Not usable statically"); -} - -void cpu_exit(CPUArchState *env) { - assert(false && "Not usable statically"); -} - -void cpu_resume_from_signal(CPUArchState *env1, void *puc) { - assert(false && "Not usable statically"); -} - -CPUDebugExcpHandler *cpu_set_debug_excp_handler(CPUDebugExcpHandler *handler) { - assert(false && "Not usable statically"); -} - -void cpu_abort(CPUArchState *env, const char *fmt, ...) { - assert(false && "Not usable statically"); -} - -int cpu_memory_rw_debug(CPUArchState *env, target_ulong addr, uint8_t *buf, int len, int is_write) { - assert(false && "Not usable statically"); -} - -void cpu_exec_init(CPUArchState *env) { - assert(false && "Not usable statically"); -} - -extern "C" { - -/* Memory operations */ -void stq_phys(target_phys_addr_t addr, uint64_t val) { - assert(false && "Not usable statically"); -} - -void stl_phys(target_phys_addr_t addr, uint32_t val) { - assert(false && "Not usable statically"); -} - -void stl_phys_notdirty(target_phys_addr_t addr, uint32_t val) { -} - -void stw_phys(target_phys_addr_t addr, uint32_t val) { - assert(false && "Not usable statically"); -} - -void stb_phys(target_phys_addr_t addr, uint32_t val) { - assert(false && "Not usable statically"); -} - -uint64_t ldq_phys(target_phys_addr_t addr) { - assert(false && "Not usable statically"); - return 0; -} - -uint64_t ldq_kernel(target_phys_addr_t addr) { - assert(false && "Not usable statically"); - return 0; -} - -uint32_t ldl_phys(target_phys_addr_t addr) { - assert(false && "Not usable statically"); - return 0; -} - -uint32_t lduw_phys(target_phys_addr_t addr) { - assert(false && "Not usable statically"); - return 0; -} - -uint32_t ldub_phys(target_phys_addr_t addr) { - assert(false && "Not usable statically"); - return 0; -} - -uint64_t __ldq_cmmu(target_ulong addr, int mmu_idx) { - assert(false && "Not usable statically"); - return 0; -} - -uint32_t __ldl_cmmu(target_ulong addr, int mmu_idx) { - assert(false && "Not usable statically"); - return 0; -} - -uint16_t __ldw_cmmu(target_ulong addr, int mmu_idx) { - assert(false && "Not usable statically"); - return 0; -} - -uint8_t __ldb_cmmu(target_ulong addr, int mmu_idx) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_ldsb_data(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_ldub_data(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_ldub_kernel(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_lduw_data(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_lduw_kernel(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int lduw_kernel_s2e_trace(target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_ldsw_data(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_ldl_data(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_ldl_kernel(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -uint64_t cpu_ldq_kernel(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int ldl_kernel_s2e_trace(target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -int cpu_ldq_data(CPUArchState *env, target_ulong ptr) { - assert(false && "Not usable statically"); - return 0; -} - -void cpu_stb_data(CPUArchState *env, target_ulong ptr, uint8_t data) { - assert(false && "Not usable statically"); -} - -void cpu_stb_kernel(CPUArchState *env, target_ulong ptr, uint8_t data) { - assert(false && "Not usable statically"); -} - -void cpu_stw_data(CPUArchState *env, target_ulong ptr, uint16_t data) { - assert(false && "Not usable statically"); -} - -void cpu_stw_kernel(CPUArchState *env, target_ulong ptr, uint16_t data) { - assert(false && "Not usable statically"); -} - -void cpu_stl_data(CPUArchState *env, target_ulong ptr, uint32_t data) { - assert(false && "Not usable statically"); -} - -void cpu_stl_kernel(CPUArchState *env, target_ulong ptr, uint32_t data) { - assert(false && "Not usable statically"); -} - -void cpu_stq_kernel(CPUArchState *env, target_ulong ptr, uint32_t data) { - assert(false && "Not usable statically"); -} - -void cpu_stq_data(CPUArchState *env, target_ulong ptr, uint32_t data) { - assert(false && "Not usable statically"); -} -} - -/*******************/ -void tlb_flush_page(CPUArchState *env, target_ulong addr) { -} - -int tlb_set_page_exec(CPUArchState *env, target_ulong vaddr, target_phys_addr_t paddr, int prot, int mmu_idx, - int is_softmmu) { - return 0; -} - -void tlb_flush(CPUArchState *env, int flush_global) { -} - -void helper_register_symbol(const char *name, void *address) { - llvm::sys::DynamicLibrary::AddSymbol(name, address); -} - -void run_on_cpu(CPUArchState *env, void (*func)(void *data), void *data) { -} - -bool tcg_enabled(void) { - return true; -} - -void kvm_cpu_synchronize_state(CPUArchState *env) { -} - -void do_interrupt_all(int intno, int is_int, int error_code, target_ulong next_eip, int is_hw) { -} - -void tlb_set_page(CPUArchState *env, target_ulong vaddr, target_phys_addr_t paddr, int prot, int mmu_idx, - target_ulong size) { -} - -int cpu_x86_register(cpuid_t *cpuid, const char *cpu_model, int is64) { -} - -void cpu_x86_cpuid(cpuid_t *cpuid, uint32_t index, uint32_t count, uint32_t *eax, uint32_t *ebx, uint32_t *ecx, - uint32_t *edx) { -} - -void s2e_on_privilege_change(unsigned previous, unsigned current) { -} -} From 6419f47abd10b41d9f21f7e95831ef3f2b121c22 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:33:00 +0200 Subject: [PATCH 33/52] libcpu: moved the breakpoint flags to cpu/common.h Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/common.h | 9 +++++++++ libcpu/src/cpu-all.h | 9 --------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/libcpu/include/cpu/common.h b/libcpu/include/cpu/common.h index 9e7f72ace..6317834d2 100644 --- a/libcpu/include/cpu/common.h +++ b/libcpu/include/cpu/common.h @@ -29,6 +29,15 @@ extern "C" { #endif +/* Breakpoint/watchpoint flags */ +#define BP_MEM_READ 0x01 +#define BP_MEM_WRITE 0x02 +#define BP_MEM_ACCESS (BP_MEM_READ | BP_MEM_WRITE) +#define BP_STOP_BEFORE_ACCESS 0x04 +#define BP_WATCHPOINT_HIT 0x08 +#define BP_GDB 0x10 +#define BP_CPU 0x20 + typedef struct CPUBreakpoint { target_ulong pc; int flags; /* BP_* */ diff --git a/libcpu/src/cpu-all.h b/libcpu/src/cpu-all.h index 97ae4acbf..cf761cb77 100644 --- a/libcpu/src/cpu-all.h +++ b/libcpu/src/cpu-all.h @@ -287,15 +287,6 @@ static inline void cpu_interrupt(CPUArchState *s, int mask) { void cpu_reset_interrupt(CPUArchState *env, int mask); -/* Breakpoint/watchpoint flags */ -#define BP_MEM_READ 0x01 -#define BP_MEM_WRITE 0x02 -#define BP_MEM_ACCESS (BP_MEM_READ | BP_MEM_WRITE) -#define BP_STOP_BEFORE_ACCESS 0x04 -#define BP_WATCHPOINT_HIT 0x08 -#define BP_GDB 0x10 -#define BP_CPU 0x20 - int cpu_breakpoint_insert(CPUArchState *env, target_ulong pc, int flags, CPUBreakpoint **breakpoint); int cpu_breakpoint_remove(CPUArchState *env, target_ulong pc, int flags); void cpu_breakpoint_remove_by_ref(CPUArchState *env, CPUBreakpoint *breakpoint); From 05c4d97a15997ce879f68421cfe8b302966d4ff0 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:33:13 +0200 Subject: [PATCH 34/52] libcpu: renamed cpu_mmu_index to x86_mmu_index Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/i386/cpu.h | 4 +++- libcpu/src/exec.c | 2 +- libcpu/src/softmmu_header.h | 4 ++-- libs2ecore/src/ExprInterface.cpp | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/libcpu/include/cpu/i386/cpu.h b/libcpu/include/cpu/i386/cpu.h index 0e68f8f71..48a95ac82 100644 --- a/libcpu/include/cpu/i386/cpu.h +++ b/libcpu/include/cpu/i386/cpu.h @@ -221,7 +221,9 @@ static inline bool cpu_has_work(CPUX86State *env) { target_ulong cpu_get_eflags(CPUX86State *env); void cpu_restore_eflags(CPUX86State *env); -static inline int cpu_mmu_index(CPUX86State *env) { +/* MMU index of the current privilege level. cpu_mmu_index() in + cpu/accel/cpu-mmu-index.h is the CPUState version. */ +static inline int x86_mmu_index(CPUX86State *env) { return (env->hflags & HF_CPL_MASK) == 3 ? 1 : 0; } diff --git a/libcpu/src/exec.c b/libcpu/src/exec.c index 64a71a888..66a610102 100644 --- a/libcpu/src/exec.c +++ b/libcpu/src/exec.c @@ -542,7 +542,7 @@ tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr) { void *p; page_index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); - mmu_idx = cpu_mmu_index(env1); + mmu_idx = x86_mmu_index(env1); if (unlikely(env_tlb(env1)->f[mmu_idx].table[page_index].addr_code != (addr & TARGET_PAGE_MASK))) { cpu_ldub_code(env1, addr); } diff --git a/libcpu/src/softmmu_header.h b/libcpu/src/softmmu_header.h index 6a7d1926b..674ce8a91 100644 --- a/libcpu/src/softmmu_header.h +++ b/libcpu/src/softmmu_header.h @@ -45,12 +45,12 @@ #elif ACCESS_TYPE == (NB_MMU_MODES) -#define CPU_MMU_INDEX (cpu_mmu_index(env)) +#define CPU_MMU_INDEX (x86_mmu_index(env)) #define MMUSUFFIX _mmu #elif ACCESS_TYPE == (NB_MMU_MODES + 1) -#define CPU_MMU_INDEX (cpu_mmu_index(env)) +#define CPU_MMU_INDEX (x86_mmu_index(env)) #define MMUSUFFIX _cmmu #else diff --git a/libs2ecore/src/ExprInterface.cpp b/libs2ecore/src/ExprInterface.cpp index ddeab218a..c9a9db778 100644 --- a/libs2ecore/src/ExprInterface.cpp +++ b/libs2ecore/src/ExprInterface.cpp @@ -183,7 +183,7 @@ template static inline bool s2e_fast_read_mem(uint64_t addr, T *res object_index = addr >> SE_RAM_OBJECT_BITS; page_index = object_index & (CPU_TLB_SIZE - 1); - mmu_idx = cpu_mmu_index(env); + mmu_idx = x86_mmu_index(env); CPUTLBEntry *tlb_entry = &env_tlb(env)->f[mmu_idx].table[page_index]; if (unlikely(env_tlb(env)->f[mmu_idx].table[page_index].addr_read != (addr & (TARGET_PAGE_MASK | (sizeof(*res) - 1))))) { From 684d60eca9510663825e7314e92fbaef27d0912c Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:33:13 +0200 Subject: [PATCH 35/52] libcpu: added the upstream names for addresses and memory regions Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/memory.h | 22 ++++++++++++++++++++++ libcpu/include/cpu/types.h | 7 +++++++ libcpu/src/memory.c | 6 ++++++ 3 files changed, 35 insertions(+) diff --git a/libcpu/include/cpu/memory.h b/libcpu/include/cpu/memory.h index 1c9727568..d28ada118 100644 --- a/libcpu/include/cpu/memory.h +++ b/libcpu/include/cpu/memory.h @@ -37,6 +37,21 @@ struct MemoryDescOps { mem_write_t write; }; +struct MemoryDesc; + +/// What the softmmu (src/accel/cputlb.c) sees of a memory region. Upstream has +/// a full memory API behind these two names. libcpu only needs to tell RAM +/// from MMIO, so a region is a pointer to its MemoryDesc, which is null for +/// MMIO, and a section is a region plus its read-only attribute. +typedef struct MemoryRegion { + const struct MemoryDesc *desc; +} MemoryRegion; + +typedef struct MemoryRegionSection { + MemoryRegion *mr; + bool readonly; +} MemoryRegionSection; + typedef struct MemoryDesc { struct kvm_userspace_memory_region kvm; struct MemoryDescOps ops; @@ -44,8 +59,15 @@ typedef struct MemoryDesc { // TODO: get rid of this too uint64_t ram_addr; + + /// The softmmu view of this region. mem_desc_register() fills them in. + MemoryRegion mr; + MemoryRegionSection section; } MemoryDesc; +/// The section that stands for everything that is not RAM. +extern MemoryRegionSection g_mmio_section; + const MemoryDesc *mem_desc_register(struct kvm_userspace_memory_region *kr); /// diff --git a/libcpu/include/cpu/types.h b/libcpu/include/cpu/types.h index c148294e0..b65b1b716 100644 --- a/libcpu/include/cpu/types.h +++ b/libcpu/include/cpu/types.h @@ -77,6 +77,13 @@ typedef uint64_t target_phys_addr_t; typedef uintptr_t ram_addr_t; +/* Guest physical address. Upstream name of target_phys_addr_t. */ +typedef uint64_t hwaddr; +#define HWADDR_FMT_plx "%016" PRIx64 + +/* Guest virtual address as passed to the cpu_{ld,st}*() accessors. */ +typedef uintptr_t abi_ptr; + #ifdef __cplusplus } #endif diff --git a/libcpu/src/memory.c b/libcpu/src/memory.c index 1019a39d3..315a4e83f 100644 --- a/libcpu/src/memory.c +++ b/libcpu/src/memory.c @@ -28,6 +28,9 @@ static const unsigned MEM_REGION_MAX_COUNT = 32; static MemoryDesc s_regions[MEM_REGION_MAX_COUNT]; static unsigned s_region_count = 0; +static MemoryRegion s_mmio_region = {.desc = NULL}; +MemoryRegionSection g_mmio_section = {.mr = &s_mmio_region, .readonly = false}; + static bool get_memory_access_flags(uint64_t start, uint64_t size, bool *readable, bool *writable) { bool ret = false; FILE *fp = fopen("/proc/self/maps", "r"); @@ -82,6 +85,9 @@ const MemoryDesc *mem_desc_register(struct kvm_userspace_memory_region *kr) { MemoryDesc *r = &s_regions[kr->slot]; r->kvm = *kr; r->read_only = ro; + r->mr.desc = r; + r->section.mr = &r->mr; + r->section.readonly = ro; if (s_region_count < kr->slot + 1) { s_region_count = kr->slot + 1; From cc5da1b83e98a0c2b01f6c3f0c4a658adca0ff9f Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:33:21 +0200 Subject: [PATCH 36/52] libcpu,libs2ecore,libs2e: added a tlb flush hook for one mmu index Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/se_libcpu.h | 2 ++ libs2e/src/s2e-libcpu-interface.cpp | 1 + libs2ecore/include/s2e/S2EExecutionStateTlb.h | 4 ++++ libs2ecore/include/s2e/s2e_libcpu.h | 1 + libs2ecore/src/S2EExecutionStateTlb.cpp | 12 ++++++++++++ libs2ecore/src/S2EExecutor.cpp | 4 ++++ 6 files changed, 24 insertions(+) diff --git a/libcpu/include/cpu/se_libcpu.h b/libcpu/include/cpu/se_libcpu.h index a3b601a8b..49a349049 100644 --- a/libcpu/include/cpu/se_libcpu.h +++ b/libcpu/include/cpu/se_libcpu.h @@ -95,6 +95,8 @@ struct se_libcpu_interface_t { /* TLB management */ struct tlb { void (*flush_tlb_cache)(void); + /* Drops the references to the TLB entries of one MMU index. */ + void (*flush_tlb_cache_mmuidx)(int mmu_idx); void (*flush_tlb_cache_page)(void *objectState, int mmu_idx, int index); void (*update_tlb_entry)(struct CPUX86State *env, int mmu_idx, uint64_t virtAddr, uint64_t hostAddr); } tlb; diff --git a/libs2e/src/s2e-libcpu-interface.cpp b/libs2e/src/s2e-libcpu-interface.cpp index 0421cdf09..0842ba402 100644 --- a/libs2e/src/s2e-libcpu-interface.cpp +++ b/libs2e/src/s2e-libcpu-interface.cpp @@ -62,6 +62,7 @@ void init_s2e_libcpu_interface(struct se_libcpu_interface_t *sqi) { sqi->tb.is_tb_instrumented = s2e_is_tb_instrumented; sqi->tlb.flush_tlb_cache = s2e_flush_tlb_cache; + sqi->tlb.flush_tlb_cache_mmuidx = s2e_flush_tlb_cache_mmuidx; sqi->tlb.flush_tlb_cache_page = se_flush_tlb_cache_page; sqi->tlb.update_tlb_entry = s2e_update_tlb_entry; diff --git a/libs2ecore/include/s2e/S2EExecutionStateTlb.h b/libs2ecore/include/s2e/S2EExecutionStateTlb.h index 32c1b9659..e51c333e7 100644 --- a/libs2ecore/include/s2e/S2EExecutionStateTlb.h +++ b/libs2ecore/include/s2e/S2EExecutionStateTlb.h @@ -77,6 +77,10 @@ class S2EExecutionStateTlb { void flushTlbCache(); + /// Drops the references to the TLB entries of one MMU index. libcpu calls + /// it before it invalidates all the entries of that index. + void flushTlbCacheMmuIdx(int mmu_idx); + void flushTlbCachePage(const klee::ObjectStatePtr &objectState, int mmu_idx, int index); #if defined(SE_ENABLE_PHYSRAM_TLB) diff --git a/libs2ecore/include/s2e/s2e_libcpu.h b/libs2ecore/include/s2e/s2e_libcpu.h index ef58c78ed..26c28e723 100644 --- a/libs2ecore/include/s2e/s2e_libcpu.h +++ b/libs2ecore/include/s2e/s2e_libcpu.h @@ -137,6 +137,7 @@ int s2e_is_tb_instrumented(void *se_tb); void s2e_flush_tb_cache(); void s2e_flush_tlb_cache(void); +void s2e_flush_tlb_cache_mmuidx(int mmu_idx); void se_flush_tlb_cache_page(void *objectState, int mmu_idx, int index); extern se_libcpu_tb_exec_t se_libcpu_tb_exec; diff --git a/libs2ecore/src/S2EExecutionStateTlb.cpp b/libs2ecore/src/S2EExecutionStateTlb.cpp index e84e91239..74881f66a 100644 --- a/libs2ecore/src/S2EExecutionStateTlb.cpp +++ b/libs2ecore/src/S2EExecutionStateTlb.cpp @@ -193,6 +193,18 @@ void S2EExecutionStateTlb::flushTlbCache() { m_tlbMap.clear(); } +void S2EExecutionStateTlb::flushTlbCacheMmuIdx(int mmu_idx) { + for (auto it = m_tlbMap.begin(); it != m_tlbMap.end();) { + auto &vec = it->second; + llvm::erase_if(vec, [&](const TlbCoordinates &coords) { return coords.first == (unsigned) mmu_idx; }); + if (vec.empty()) { + it = m_tlbMap.erase(it); + } else { + ++it; + } + } +} + void S2EExecutionStateTlb::flushTlbCachePage(const klee::ObjectStatePtr &objectState, int mmu_idx, int index) { if (!objectState) { return; diff --git a/libs2ecore/src/S2EExecutor.cpp b/libs2ecore/src/S2EExecutor.cpp index b6d2878c5..4df06b435 100644 --- a/libs2ecore/src/S2EExecutor.cpp +++ b/libs2ecore/src/S2EExecutor.cpp @@ -1822,6 +1822,10 @@ void s2e_flush_tlb_cache() { g_s2e_state->getTlb()->flushTlbCache(); } +void s2e_flush_tlb_cache_mmuidx(int mmu_idx) { + g_s2e_state->getTlb()->flushTlbCacheMmuIdx(mmu_idx); +} + void se_flush_tlb_cache_page(void *objectState, int mmu_idx, int index) { g_s2e_state->getTlb()->flushTlbCachePage(static_cast(objectState), mmu_idx, index); } From 5140ced058a5f1fc9f091a990f039ddd8d3b777c Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:39:13 +0200 Subject: [PATCH 37/52] libcpu: imported the softmmu from QEMU v11.1.0 The files are the output of scripts/upgrade/normalize.sh, without any change. Nothing compiles them yet. Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/accel/cpu-ldst-common.h | 100 + libcpu/include/cpu/accel/cpu-ldst.h | 357 +++ libcpu/include/cpu/accel/cpu-ops.h | 307 +++ libcpu/include/cpu/accel/probe.h | 116 + libcpu/include/cpu/exec/cputlb.h | 243 ++ libcpu/include/cpu/exec/memattrs.h | 93 + libcpu/include/cpu/exec/mmu-access-type.h | 18 + libcpu/include/cpu/exec/page-protection.h | 42 + libcpu/include/cpu/exec/tlb-flags.h | 84 + libcpu/include/cpu/exec/vaddr.h | 20 + libcpu/scripts/upgrade/BASELINE | 1 + libcpu/scripts/upgrade/mapping.tsv | 26 + libcpu/src/accel/atomic_common.c.inc | 94 + libcpu/src/accel/atomic_template.h | 316 +++ libcpu/src/accel/cputlb.c | 2618 ++++++++++++++++++++ libcpu/src/accel/ldst_atomicity.c.inc | 967 ++++++++ libcpu/src/accel/ldst_common.c.inc | 186 ++ libcpu/src/accel/tlb-bounds.h | 13 + 18 files changed, 5601 insertions(+) create mode 100644 libcpu/include/cpu/accel/cpu-ldst-common.h create mode 100644 libcpu/include/cpu/accel/cpu-ldst.h create mode 100644 libcpu/include/cpu/accel/cpu-ops.h create mode 100644 libcpu/include/cpu/accel/probe.h create mode 100644 libcpu/include/cpu/exec/cputlb.h create mode 100644 libcpu/include/cpu/exec/memattrs.h create mode 100644 libcpu/include/cpu/exec/mmu-access-type.h create mode 100644 libcpu/include/cpu/exec/page-protection.h create mode 100644 libcpu/include/cpu/exec/tlb-flags.h create mode 100644 libcpu/include/cpu/exec/vaddr.h create mode 100644 libcpu/scripts/upgrade/BASELINE create mode 100644 libcpu/scripts/upgrade/mapping.tsv create mode 100644 libcpu/src/accel/atomic_common.c.inc create mode 100644 libcpu/src/accel/atomic_template.h create mode 100644 libcpu/src/accel/cputlb.c create mode 100644 libcpu/src/accel/ldst_atomicity.c.inc create mode 100644 libcpu/src/accel/ldst_common.c.inc create mode 100644 libcpu/src/accel/tlb-bounds.h diff --git a/libcpu/include/cpu/accel/cpu-ldst-common.h b/libcpu/include/cpu/accel/cpu-ldst-common.h new file mode 100644 index 000000000..d33b9a0e8 --- /dev/null +++ b/libcpu/include/cpu/accel/cpu-ldst-common.h @@ -0,0 +1,100 @@ +/* + * Software MMU support + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifndef ACCEL_TCG_CPU_LDST_COMMON_H +#define ACCEL_TCG_CPU_LDST_COMMON_H + +#ifndef CONFIG_TCG +#error Can only include this header with TCG +#endif + +#include "exec/memopidx.h" +#include "exec/mmu-access-type.h" +#include "exec/vaddr.h" +#include "qemu/int128.h" + +uint8_t cpu_ldb_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); +uint16_t cpu_ldw_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); +uint32_t cpu_ldl_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); +uint64_t cpu_ldq_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); +Int128 cpu_ld16_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra); + +void cpu_stb_mmu(CPUArchState *env, vaddr ptr, uint8_t val, MemOpIdx oi, uintptr_t ra); +void cpu_stw_mmu(CPUArchState *env, vaddr ptr, uint16_t val, MemOpIdx oi, uintptr_t ra); +void cpu_stl_mmu(CPUArchState *env, vaddr ptr, uint32_t val, MemOpIdx oi, uintptr_t ra); +void cpu_stq_mmu(CPUArchState *env, vaddr ptr, uint64_t val, MemOpIdx oi, uintptr_t ra); +void cpu_st16_mmu(CPUArchState *env, vaddr addr, Int128 val, MemOpIdx oi, uintptr_t ra); + +uint32_t cpu_atomic_cmpxchgb_mmu(CPUArchState *env, vaddr addr, uint32_t cmpv, uint32_t newv, MemOpIdx oi, + uintptr_t retaddr); +uint32_t cpu_atomic_cmpxchgw_le_mmu(CPUArchState *env, vaddr addr, uint32_t cmpv, uint32_t newv, MemOpIdx oi, + uintptr_t retaddr); +uint32_t cpu_atomic_cmpxchgl_le_mmu(CPUArchState *env, vaddr addr, uint32_t cmpv, uint32_t newv, MemOpIdx oi, + uintptr_t retaddr); +uint64_t cpu_atomic_cmpxchgq_le_mmu(CPUArchState *env, vaddr addr, uint64_t cmpv, uint64_t newv, MemOpIdx oi, + uintptr_t retaddr); +uint32_t cpu_atomic_cmpxchgw_be_mmu(CPUArchState *env, vaddr addr, uint32_t cmpv, uint32_t newv, MemOpIdx oi, + uintptr_t retaddr); +uint32_t cpu_atomic_cmpxchgl_be_mmu(CPUArchState *env, vaddr addr, uint32_t cmpv, uint32_t newv, MemOpIdx oi, + uintptr_t retaddr); +uint64_t cpu_atomic_cmpxchgq_be_mmu(CPUArchState *env, vaddr addr, uint64_t cmpv, uint64_t newv, MemOpIdx oi, + uintptr_t retaddr); + +#define GEN_ATOMIC_HELPER(NAME, TYPE, SUFFIX) \ + TYPE cpu_atomic_##NAME##SUFFIX##_mmu(CPUArchState *env, vaddr addr, TYPE val, MemOpIdx oi, uintptr_t retaddr); + +#define GEN_ATOMIC_HELPER_ALL(NAME) \ + GEN_ATOMIC_HELPER(NAME, uint32_t, b) \ + GEN_ATOMIC_HELPER(NAME, uint32_t, w_le) \ + GEN_ATOMIC_HELPER(NAME, uint32_t, w_be) \ + GEN_ATOMIC_HELPER(NAME, uint32_t, l_le) \ + GEN_ATOMIC_HELPER(NAME, uint32_t, l_be) \ + GEN_ATOMIC_HELPER(NAME, uint64_t, q_le) \ + GEN_ATOMIC_HELPER(NAME, uint64_t, q_be) + +GEN_ATOMIC_HELPER_ALL(fetch_add) +GEN_ATOMIC_HELPER_ALL(fetch_sub) +GEN_ATOMIC_HELPER_ALL(fetch_and) +GEN_ATOMIC_HELPER_ALL(fetch_or) +GEN_ATOMIC_HELPER_ALL(fetch_xor) +GEN_ATOMIC_HELPER_ALL(fetch_smin) +GEN_ATOMIC_HELPER_ALL(fetch_umin) +GEN_ATOMIC_HELPER_ALL(fetch_smax) +GEN_ATOMIC_HELPER_ALL(fetch_umax) + +GEN_ATOMIC_HELPER_ALL(add_fetch) +GEN_ATOMIC_HELPER_ALL(sub_fetch) +GEN_ATOMIC_HELPER_ALL(and_fetch) +GEN_ATOMIC_HELPER_ALL(or_fetch) +GEN_ATOMIC_HELPER_ALL(xor_fetch) +GEN_ATOMIC_HELPER_ALL(smin_fetch) +GEN_ATOMIC_HELPER_ALL(umin_fetch) +GEN_ATOMIC_HELPER_ALL(smax_fetch) +GEN_ATOMIC_HELPER_ALL(umax_fetch) + +GEN_ATOMIC_HELPER_ALL(xchg) + +Int128 cpu_atomic_cmpxchgo_le_mmu(CPUArchState *env, vaddr addr, Int128 cmpv, Int128 newv, MemOpIdx oi, + uintptr_t retaddr); +Int128 cpu_atomic_cmpxchgo_be_mmu(CPUArchState *env, vaddr addr, Int128 cmpv, Int128 newv, MemOpIdx oi, + uintptr_t retaddr); + +GEN_ATOMIC_HELPER(xchg, Int128, o_le) +GEN_ATOMIC_HELPER(xchg, Int128, o_be) +GEN_ATOMIC_HELPER(fetch_and, Int128, o_le) +GEN_ATOMIC_HELPER(fetch_and, Int128, o_be) +GEN_ATOMIC_HELPER(fetch_or, Int128, o_le) +GEN_ATOMIC_HELPER(fetch_or, Int128, o_be) + +#undef GEN_ATOMIC_HELPER_ALL +#undef GEN_ATOMIC_HELPER + +uint8_t cpu_ldb_code_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra); +uint16_t cpu_ldw_code_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra); +uint32_t cpu_ldl_code_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra); +uint64_t cpu_ldq_code_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra); + +#endif /* ACCEL_TCG_CPU_LDST_COMMON_H */ diff --git a/libcpu/include/cpu/accel/cpu-ldst.h b/libcpu/include/cpu/accel/cpu-ldst.h new file mode 100644 index 000000000..a22819c83 --- /dev/null +++ b/libcpu/include/cpu/accel/cpu-ldst.h @@ -0,0 +1,357 @@ +/* + * Software MMU support (per-target) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +/* + * Generate inline load/store functions for all MMU modes (typically + * at least _user and _kernel) as well as _data versions, for all data + * sizes. + * + * Used by target op helpers. + * + * The syntax for the accessors is: + * + * load: cpu_ld{sign}{size}{end}_{mmusuffix}(env, ptr) + * cpu_ld{sign}{size}{end}_{mmusuffix}_ra(env, ptr, retaddr) + * cpu_ld{sign}{size}{end}_mmuidx_ra(env, ptr, mmu_idx, retaddr) + * cpu_ld{sign}{size}{end}_mmu(env, ptr, oi, retaddr) + * + * store: cpu_st{size}{end}_{mmusuffix}(env, ptr, val) + * cpu_st{size}{end}_{mmusuffix}_ra(env, ptr, val, retaddr) + * cpu_st{size}{end}_mmuidx_ra(env, ptr, val, mmu_idx, retaddr) + * cpu_st{size}{end}_mmu(env, ptr, val, oi, retaddr) + * + * sign is: + * (empty): for 32 and 64 bit sizes + * u : unsigned + * s : signed + * + * size is: + * b: 8 bits + * w: 16 bits + * l: 32 bits + * q: 64 bits + * + * end is: + * (empty): for target native endian, or for 8 bit access + * _be: for forced big endian + * _le: for forced little endian + * + * mmusuffix is one of the generic suffixes "data" or "mmuidx". + * The "mmuidx" suffix carries an extra mmu_idx argument that specifies + * the index to use; the "data" suffix take the index from cpu_mmu_index(). + * + * The "mmu" suffix carries the full MemOpIdx, with both mmu_idx and the + * MemOp including alignment requirements. The alignment will be enforced. + */ +#ifndef ACCEL_TCG_CPU_LDST_H +#define ACCEL_TCG_CPU_LDST_H + +#ifndef CONFIG_TCG +#error Can only include this header with TCG +#endif + +#include "accel/tcg/cpu-ldst-common.h" +#include "accel/tcg/cpu-mmu-index.h" +#include "exec/abi_ptr.h" +#include "exec/cpu-common.h" + +static inline uint32_t cpu_ldub_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_UB, mmu_idx); + return cpu_ldb_mmu(env, addr, oi, ra); +} + +static inline int cpu_ldsb_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + return (int8_t) cpu_ldub_mmuidx_ra(env, addr, mmu_idx, ra); +} + +static inline uint32_t cpu_lduw_be_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_BEUW | MO_UNALN, mmu_idx); + return cpu_ldw_mmu(env, addr, oi, ra); +} + +static inline int cpu_ldsw_be_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + return (int16_t) cpu_lduw_be_mmuidx_ra(env, addr, mmu_idx, ra); +} + +static inline uint32_t cpu_ldl_be_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_BEUL | MO_UNALN, mmu_idx); + return cpu_ldl_mmu(env, addr, oi, ra); +} + +static inline uint64_t cpu_ldq_be_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_BEUQ | MO_UNALN, mmu_idx); + return cpu_ldq_mmu(env, addr, oi, ra); +} + +static inline uint32_t cpu_lduw_le_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_LEUW | MO_UNALN, mmu_idx); + return cpu_ldw_mmu(env, addr, oi, ra); +} + +static inline int cpu_ldsw_le_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + return (int16_t) cpu_lduw_le_mmuidx_ra(env, addr, mmu_idx, ra); +} + +static inline uint32_t cpu_ldl_le_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_LEUL | MO_UNALN, mmu_idx); + return cpu_ldl_mmu(env, addr, oi, ra); +} + +static inline uint64_t cpu_ldq_le_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_LEUQ | MO_UNALN, mmu_idx); + return cpu_ldq_mmu(env, addr, oi, ra); +} + +static inline void cpu_stb_mmuidx_ra(CPUArchState *env, abi_ptr addr, uint32_t val, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_UB, mmu_idx); + cpu_stb_mmu(env, addr, val, oi, ra); +} + +static inline void cpu_stw_be_mmuidx_ra(CPUArchState *env, abi_ptr addr, uint32_t val, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_BEUW | MO_UNALN, mmu_idx); + cpu_stw_mmu(env, addr, val, oi, ra); +} + +static inline void cpu_stl_be_mmuidx_ra(CPUArchState *env, abi_ptr addr, uint32_t val, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_BEUL | MO_UNALN, mmu_idx); + cpu_stl_mmu(env, addr, val, oi, ra); +} + +static inline void cpu_stq_be_mmuidx_ra(CPUArchState *env, abi_ptr addr, uint64_t val, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_BEUQ | MO_UNALN, mmu_idx); + cpu_stq_mmu(env, addr, val, oi, ra); +} + +static inline void cpu_stw_le_mmuidx_ra(CPUArchState *env, abi_ptr addr, uint32_t val, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_LEUW | MO_UNALN, mmu_idx); + cpu_stw_mmu(env, addr, val, oi, ra); +} + +static inline void cpu_stl_le_mmuidx_ra(CPUArchState *env, abi_ptr addr, uint32_t val, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_LEUL | MO_UNALN, mmu_idx); + cpu_stl_mmu(env, addr, val, oi, ra); +} + +static inline void cpu_stq_le_mmuidx_ra(CPUArchState *env, abi_ptr addr, uint64_t val, int mmu_idx, uintptr_t ra) { + MemOpIdx oi = make_memop_idx(MO_LEUQ | MO_UNALN, mmu_idx); + cpu_stq_mmu(env, addr, val, oi, ra); +} + +/*--------------------------*/ + +static inline uint32_t cpu_ldub_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + return cpu_ldub_mmuidx_ra(env, addr, mmu_index, ra); +} + +static inline int cpu_ldsb_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + return (int8_t) cpu_ldub_data_ra(env, addr, ra); +} + +static inline uint32_t cpu_lduw_be_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + return cpu_lduw_be_mmuidx_ra(env, addr, mmu_index, ra); +} + +static inline int cpu_ldsw_be_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + return (int16_t) cpu_lduw_be_data_ra(env, addr, ra); +} + +static inline uint32_t cpu_ldl_be_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + return cpu_ldl_be_mmuidx_ra(env, addr, mmu_index, ra); +} + +static inline uint64_t cpu_ldq_be_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + return cpu_ldq_be_mmuidx_ra(env, addr, mmu_index, ra); +} + +static inline uint32_t cpu_lduw_le_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + return cpu_lduw_le_mmuidx_ra(env, addr, mmu_index, ra); +} + +static inline int cpu_ldsw_le_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + return (int16_t) cpu_lduw_le_data_ra(env, addr, ra); +} + +static inline uint32_t cpu_ldl_le_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + return cpu_ldl_le_mmuidx_ra(env, addr, mmu_index, ra); +} + +static inline uint64_t cpu_ldq_le_data_ra(CPUArchState *env, abi_ptr addr, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + return cpu_ldq_le_mmuidx_ra(env, addr, mmu_index, ra); +} + +static inline void cpu_stb_data_ra(CPUArchState *env, abi_ptr addr, uint32_t val, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + cpu_stb_mmuidx_ra(env, addr, val, mmu_index, ra); +} + +static inline void cpu_stw_be_data_ra(CPUArchState *env, abi_ptr addr, uint32_t val, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + cpu_stw_be_mmuidx_ra(env, addr, val, mmu_index, ra); +} + +static inline void cpu_stl_be_data_ra(CPUArchState *env, abi_ptr addr, uint32_t val, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + cpu_stl_be_mmuidx_ra(env, addr, val, mmu_index, ra); +} + +static inline void cpu_stq_be_data_ra(CPUArchState *env, abi_ptr addr, uint64_t val, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + cpu_stq_be_mmuidx_ra(env, addr, val, mmu_index, ra); +} + +static inline void cpu_stw_le_data_ra(CPUArchState *env, abi_ptr addr, uint32_t val, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + cpu_stw_le_mmuidx_ra(env, addr, val, mmu_index, ra); +} + +static inline void cpu_stl_le_data_ra(CPUArchState *env, abi_ptr addr, uint32_t val, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + cpu_stl_le_mmuidx_ra(env, addr, val, mmu_index, ra); +} + +static inline void cpu_stq_le_data_ra(CPUArchState *env, abi_ptr addr, uint64_t val, uintptr_t ra) { + int mmu_index = cpu_mmu_index(env_cpu(env), false); + cpu_stq_le_mmuidx_ra(env, addr, val, mmu_index, ra); +} + +/*--------------------------*/ + +static inline uint32_t cpu_ldub_data(CPUArchState *env, abi_ptr addr) { + return cpu_ldub_data_ra(env, addr, 0); +} + +static inline int cpu_ldsb_data(CPUArchState *env, abi_ptr addr) { + return (int8_t) cpu_ldub_data(env, addr); +} + +static inline uint32_t cpu_lduw_be_data(CPUArchState *env, abi_ptr addr) { + return cpu_lduw_be_data_ra(env, addr, 0); +} + +static inline int cpu_ldsw_be_data(CPUArchState *env, abi_ptr addr) { + return (int16_t) cpu_lduw_be_data(env, addr); +} + +static inline uint32_t cpu_ldl_be_data(CPUArchState *env, abi_ptr addr) { + return cpu_ldl_be_data_ra(env, addr, 0); +} + +static inline uint64_t cpu_ldq_be_data(CPUArchState *env, abi_ptr addr) { + return cpu_ldq_be_data_ra(env, addr, 0); +} + +static inline uint32_t cpu_lduw_le_data(CPUArchState *env, abi_ptr addr) { + return cpu_lduw_le_data_ra(env, addr, 0); +} + +static inline int cpu_ldsw_le_data(CPUArchState *env, abi_ptr addr) { + return (int16_t) cpu_lduw_le_data(env, addr); +} + +static inline uint32_t cpu_ldl_le_data(CPUArchState *env, abi_ptr addr) { + return cpu_ldl_le_data_ra(env, addr, 0); +} + +static inline uint64_t cpu_ldq_le_data(CPUArchState *env, abi_ptr addr) { + return cpu_ldq_le_data_ra(env, addr, 0); +} + +static inline void cpu_stb_data(CPUArchState *env, abi_ptr addr, uint32_t val) { + cpu_stb_data_ra(env, addr, val, 0); +} + +static inline void cpu_stw_be_data(CPUArchState *env, abi_ptr addr, uint32_t val) { + cpu_stw_be_data_ra(env, addr, val, 0); +} + +static inline void cpu_stl_be_data(CPUArchState *env, abi_ptr addr, uint32_t val) { + cpu_stl_be_data_ra(env, addr, val, 0); +} + +static inline void cpu_stq_be_data(CPUArchState *env, abi_ptr addr, uint64_t val) { + cpu_stq_be_data_ra(env, addr, val, 0); +} + +static inline void cpu_stw_le_data(CPUArchState *env, abi_ptr addr, uint32_t val) { + cpu_stw_le_data_ra(env, addr, val, 0); +} + +static inline void cpu_stl_le_data(CPUArchState *env, abi_ptr addr, uint32_t val) { + cpu_stl_le_data_ra(env, addr, val, 0); +} + +static inline void cpu_stq_le_data(CPUArchState *env, abi_ptr addr, uint64_t val) { + cpu_stq_le_data_ra(env, addr, val, 0); +} + +#ifndef TARGET_NOT_USING_LEGACY_NATIVE_ENDIAN_API +#if TARGET_BIG_ENDIAN +#define cpu_lduw_data cpu_lduw_be_data +#define cpu_ldsw_data cpu_ldsw_be_data +#define cpu_ldl_data cpu_ldl_be_data +#define cpu_ldq_data cpu_ldq_be_data +#define cpu_lduw_data_ra cpu_lduw_be_data_ra +#define cpu_ldsw_data_ra cpu_ldsw_be_data_ra +#define cpu_ldl_data_ra cpu_ldl_be_data_ra +#define cpu_ldq_data_ra cpu_ldq_be_data_ra +#define cpu_lduw_mmuidx_ra cpu_lduw_be_mmuidx_ra +#define cpu_ldsw_mmuidx_ra cpu_ldsw_be_mmuidx_ra +#define cpu_ldl_mmuidx_ra cpu_ldl_be_mmuidx_ra +#define cpu_ldq_mmuidx_ra cpu_ldq_be_mmuidx_ra +#define cpu_stw_data cpu_stw_be_data +#define cpu_stl_data cpu_stl_be_data +#define cpu_stq_data cpu_stq_be_data +#define cpu_stw_data_ra cpu_stw_be_data_ra +#define cpu_stl_data_ra cpu_stl_be_data_ra +#define cpu_stq_data_ra cpu_stq_be_data_ra +#define cpu_stw_mmuidx_ra cpu_stw_be_mmuidx_ra +#define cpu_stl_mmuidx_ra cpu_stl_be_mmuidx_ra +#define cpu_stq_mmuidx_ra cpu_stq_be_mmuidx_ra +#else +#define cpu_lduw_data cpu_lduw_le_data +#define cpu_ldsw_data cpu_ldsw_le_data +#define cpu_ldl_data cpu_ldl_le_data +#define cpu_ldq_data cpu_ldq_le_data +#define cpu_lduw_data_ra cpu_lduw_le_data_ra +#define cpu_ldsw_data_ra cpu_ldsw_le_data_ra +#define cpu_ldl_data_ra cpu_ldl_le_data_ra +#define cpu_ldq_data_ra cpu_ldq_le_data_ra +#define cpu_lduw_mmuidx_ra cpu_lduw_le_mmuidx_ra +#define cpu_ldsw_mmuidx_ra cpu_ldsw_le_mmuidx_ra +#define cpu_ldl_mmuidx_ra cpu_ldl_le_mmuidx_ra +#define cpu_ldq_mmuidx_ra cpu_ldq_le_mmuidx_ra +#define cpu_stw_data cpu_stw_le_data +#define cpu_stl_data cpu_stl_le_data +#define cpu_stq_data cpu_stq_le_data +#define cpu_stw_data_ra cpu_stw_le_data_ra +#define cpu_stl_data_ra cpu_stl_le_data_ra +#define cpu_stq_data_ra cpu_stq_le_data_ra +#define cpu_stw_mmuidx_ra cpu_stw_le_mmuidx_ra +#define cpu_stl_mmuidx_ra cpu_stl_le_mmuidx_ra +#define cpu_stq_mmuidx_ra cpu_stq_le_mmuidx_ra +#endif +#endif /* TARGET_NOT_USING_LEGACY_NATIVE_ENDIAN_API */ + +#endif /* ACCEL_TCG_CPU_LDST_H */ diff --git a/libcpu/include/cpu/accel/cpu-ops.h b/libcpu/include/cpu/accel/cpu-ops.h new file mode 100644 index 000000000..96898bb1c --- /dev/null +++ b/libcpu/include/cpu/accel/cpu-ops.h @@ -0,0 +1,307 @@ +/* + * TCG CPU-specific operations + * + * Copyright 2021 SUSE LLC + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#ifndef TCG_CPU_OPS_H +#define TCG_CPU_OPS_H + +#ifndef CONFIG_TCG +#error Can only include this header with TCG +#endif + +#include "accel/tcg/tb-cpu-state.h" +#include "exec/breakpoint.h" +#include "exec/hwaddr.h" +#include "exec/memattrs.h" +#include "exec/memop.h" +#include "exec/mmu-access-type.h" +#include "exec/vaddr.h" +#include "tcg/tcg-mo.h" + +struct TCGCPUOps { + /** + * mttcg_supported: multi-threaded TCG is supported + * + * Target (TCG frontend) supports: + * - atomic instructions + * - memory ordering primitives (barriers) + */ + bool mttcg_supported; + + /** + * @precise_smc: Stores which modify code within the current TB force + * the TB to exit; the next executed instruction will see + * the result of the store. + */ + bool precise_smc; + + /** + * @guest_default_memory_order: default barrier that is required + * for the guest memory ordering. + */ + TCGBar guest_default_memory_order; + + /** + * @initialize: Initialize TCG state + * + * Called when the first CPU is realized. + */ + void (*initialize)(void); + /** + * @translate_code: Translate guest instructions to TCGOps + * @cpu: cpu context + * @tb: translation block + * @max_insns: max number of instructions to translate + * @pc: guest virtual program counter address + * @host_pc: host physical program counter address + * + * This function must be provided by the target, which should create + * the target-specific DisasContext, and then invoke translator_loop. + */ + void (*translate_code)(CPUState *cpu, TranslationBlock *tb, int *max_insns, vaddr pc, void *host_pc); + /** + * @get_tb_cpu_state: Extract CPU state for a TCG #TranslationBlock + * + * Fill in all data required to select or compile a TranslationBlock. + */ + TCGTBCPUState (*get_tb_cpu_state)(CPUState *cs); + /** + * @synchronize_from_tb: Synchronize state from a TCG #TranslationBlock + * + * This is called when we abandon execution of a TB before starting it, + * and must set all parts of the CPU state which the previous TB in the + * chain may not have updated. + * By default, when this is NULL, a call is made to @set_pc(tb->pc). + * + * If more state needs to be restored, the target must implement a + * function to restore all the state, and register it here. + */ + void (*synchronize_from_tb)(CPUState *cpu, const TranslationBlock *tb); + /** + * @restore_state_to_opc: Synchronize state from INDEX_op_start_insn + * + * This is called when we unwind state in the middle of a TB, + * usually before raising an exception. Set all part of the CPU + * state which are tracked insn-by-insn in the target-specific + * arguments to start_insn, passed as @data. + */ + void (*restore_state_to_opc)(CPUState *cpu, const TranslationBlock *tb, const uint64_t *data); + + /** @cpu_exec_enter: Callback for cpu_exec preparation */ + void (*cpu_exec_enter)(CPUState *cpu); + /** @cpu_exec_exit: Callback for cpu_exec cleanup */ + void (*cpu_exec_exit)(CPUState *cpu); + /** @debug_excp_handler: Callback for handling debug exceptions */ + void (*debug_excp_handler)(CPUState *cpu); + + /** @mmu_index: Callback for choosing softmmu mmu index */ + int (*mmu_index)(CPUState *cpu, bool ifetch); + +#ifdef CONFIG_USER_ONLY + /** + * @fake_user_interrupt: Callback for 'fake exception' handling. + * + * Simulate 'fake exception' which will be handled outside the + * cpu execution loop (hack for x86 user mode). + */ + void (*fake_user_interrupt)(CPUState *cpu); + + /** + * record_sigsegv: + * @cpu: cpu context + * @addr: faulting guest address + * @access_type: access was read/write/execute + * @maperr: true for invalid page, false for permission fault + * @ra: host pc for unwinding + * + * We are about to raise SIGSEGV with si_code set for @maperr, + * and si_addr set for @addr. Record anything further needed + * for the signal ucontext_t. + * + * If the emulated kernel does not provide anything to the signal + * handler with anything besides the user context registers, and + * the siginfo_t, then this hook need do nothing and may be omitted. + * Otherwise, record the data and return; the caller will raise + * the signal, unwind the cpu state, and return to the main loop. + * + * If it is simpler to re-use the sysemu tlb_fill code, @ra is provided + * so that a "normal" cpu exception can be raised. In this case, + * the signal must be raised by the architecture cpu_loop. + */ + void (*record_sigsegv)(CPUState *cpu, vaddr addr, MMUAccessType access_type, bool maperr, uintptr_t ra); + /** + * record_sigbus: + * @cpu: cpu context + * @addr: misaligned guest address + * @access_type: access was read/write/execute + * @ra: host pc for unwinding + * + * We are about to raise SIGBUS with si_code BUS_ADRALN, + * and si_addr set for @addr. Record anything further needed + * for the signal ucontext_t. + * + * If the emulated kernel does not provide the signal handler with + * anything besides the user context registers, and the siginfo_t, + * then this hook need do nothing and may be omitted. + * Otherwise, record the data and return; the caller will raise + * the signal, unwind the cpu state, and return to the main loop. + * + * If it is simpler to re-use the sysemu do_unaligned_access code, + * @ra is provided so that a "normal" cpu exception can be raised. + * In this case, the signal must be raised by the architecture cpu_loop. + */ + void (*record_sigbus)(CPUState *cpu, vaddr addr, MMUAccessType access_type, uintptr_t ra); + + /** + * untagged_addr: Remove an ignored tag from an address + * @cpu: cpu context + * @addr: tagged guest address + */ + vaddr (*untagged_addr)(CPUState *cs, vaddr addr); +#else + /** @do_interrupt: Callback for interrupt handling. */ + void (*do_interrupt)(CPUState *cpu); + /** @cpu_exec_interrupt: Callback for processing interrupts in cpu_exec */ + bool (*cpu_exec_interrupt)(CPUState *cpu, int interrupt_request); + /** @cpu_exec_reset: Callback for reset in cpu_exec. */ + void (*cpu_exec_reset)(CPUState *cpu); + /** + * @cpu_exec_halt: Callback for handling halt in cpu_exec. + * + * The target CPU should do any special processing here that it needs + * to do when the CPU is in the halted state. + * + * Return true to indicate that the CPU should now leave halt, false + * if it should remain in the halted state. (This should generally + * be the same value that cpu_has_work() would return.) + * + * This method must be provided. If the target does not need to + * do anything special for halt, the same function used for its + * SysemuCPUOps::has_work method can be used here, as they have the + * same function signature. + */ + bool (*cpu_exec_halt)(CPUState *cpu); + /** + * @tlb_fill_align: Handle a softmmu tlb miss + * @cpu: cpu context + * @out: output page properties + * @addr: virtual address + * @access_type: read, write or execute + * @mmu_idx: mmu context + * @memop: memory operation for the access + * @size: memory access size, or 0 for whole page + * @probe: test only, no fault + * @ra: host return address for exception unwind + * + * If the access is valid, fill in @out and return true. + * Otherwise if probe is true, return false. + * Otherwise raise an exception and do not return. + * + * The alignment check for the access is deferred to this hook, + * so that the target can determine the priority of any alignment + * fault with respect to other potential faults from paging. + * Zero may be passed for @memop to skip any alignment check + * for non-memory-access operations such as probing. + */ + bool (*tlb_fill_align)(CPUState *cpu, CPUTLBEntryFull *out, vaddr addr, MMUAccessType access_type, int mmu_idx, + MemOp memop, int size, bool probe, uintptr_t ra); + /** + * @tlb_fill: Handle a softmmu tlb miss + * + * If the access is valid, call tlb_set_page and return true; + * if the access is invalid and probe is true, return false; + * otherwise raise an exception and do not return. + */ + bool (*tlb_fill)(CPUState *cpu, vaddr address, int size, MMUAccessType access_type, int mmu_idx, bool probe, + uintptr_t retaddr); + /** + * @pointer_wrap: + * + * We have incremented @base to @result, resulting in a page change. + * For the current cpu state, adjust @result for possible overflow. + */ + vaddr (*pointer_wrap)(CPUState *cpu, int mmu_idx, vaddr result, vaddr base); + /** + * @do_transaction_failed: Callback for handling failed memory transactions + * (ie bus faults or external aborts; not MMU faults) + */ + void (*do_transaction_failed)(CPUState *cpu, hwaddr physaddr, vaddr addr, unsigned size, MMUAccessType access_type, + int mmu_idx, MemTxAttrs attrs, MemTxResult response, uintptr_t retaddr); + /** + * @do_unaligned_access: Callback for unaligned access handling + * The callback must exit via raising an exception. + */ + G_NORETURN void (*do_unaligned_access)(CPUState *cpu, vaddr addr, MMUAccessType access_type, int mmu_idx, + uintptr_t retaddr); + + /** + * @adjust_watchpoint_address: hack for cpu_check_watchpoint (used by ARM) + */ + vaddr (*adjust_watchpoint_address)(CPUState *cpu, vaddr addr, int len); + + /** + * @debug_check_watchpoint: return true if the architectural + * watchpoint whose address has matched should really fire. + */ + bool (*debug_check_watchpoint)(CPUState *cpu, CPUWatchpoint *wp); + + /** + * @debug_check_breakpoint: return true if the architectural + * breakpoint whose PC has matched should really fire. + */ + bool (*debug_check_breakpoint)(CPUState *cpu); + + /** + * @io_recompile_replay_branch: Callback for cpu_io_recompile. + * + * The cpu has been stopped, and cpu_restore_state_from_tb has been + * called. If the faulting instruction is in a delay slot, and the + * target architecture requires re-execution of the branch, then + * adjust the cpu state as required and return true. + */ + bool (*io_recompile_replay_branch)(CPUState *cpu, const TranslationBlock *tb); + /** + * @need_replay_interrupt: Return %true if @interrupt_request + * needs to be recorded for replay purposes. + */ + bool (*need_replay_interrupt)(int interrupt_request); +#endif /* !CONFIG_USER_ONLY */ +}; + +/** + * cpu_check_watchpoint: + * @cpu: cpu context + * @addr: guest virtual address + * @len: access length + * @attrs: memory access attributes + * @flags: watchpoint access type + * @ra: unwind return address + * + * Check for a watchpoint hit in [addr, addr+len) of the type + * specified by @flags. Exit via exception with a hit. + */ +void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len, MemTxAttrs attrs, int flags, uintptr_t ra); + +/** + * cpu_watchpoint_address_matches: + * @cpu: cpu context + * @addr: guest virtual address + * @len: access length + * + * Return the watchpoint flags that apply to [addr, addr+len). + * If no watchpoint is registered for the range, the result is 0. + */ +int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len); + +/* + * Common pointer_wrap implementations. + */ +vaddr cpu_pointer_wrap_notreached(CPUState *, int, vaddr, vaddr); +vaddr cpu_pointer_wrap_uint32(CPUState *, int, vaddr, vaddr); + +#endif /* TCG_CPU_OPS_H */ diff --git a/libcpu/include/cpu/accel/probe.h b/libcpu/include/cpu/accel/probe.h new file mode 100644 index 000000000..0ec468388 --- /dev/null +++ b/libcpu/include/cpu/accel/probe.h @@ -0,0 +1,116 @@ +/* + * Probe guest virtual addresses for access permissions. + * + * Copyright (c) 2003 Fabrice Bellard + * SPDX-License-Identifier: LGPL-2.1-or-later + */ +#ifndef ACCEL_TCG_PROBE_H +#define ACCEL_TCG_PROBE_H + +#ifndef CONFIG_TCG +#error Can only include this header with TCG +#endif + +#include "exec/mmu-access-type.h" +#include "exec/vaddr.h" + +/** + * probe_access: + * @env: CPUArchState + * @addr: guest virtual address to look up + * @size: size of the access + * @access_type: read, write or execute permission + * @mmu_idx: MMU index to use for lookup + * @retaddr: return address for unwinding + * + * Look up the guest virtual address @addr. Raise an exception if the + * page does not satisfy @access_type. Raise an exception if the + * access (@addr, @size) hits a watchpoint. For writes, mark a clean + * page as dirty. + * + * Finally, return the host address for a page that is backed by RAM, + * or NULL if the page requires I/O. + */ +void *probe_access(CPUArchState *env, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, uintptr_t retaddr); + +static inline void *probe_write(CPUArchState *env, vaddr addr, int size, int mmu_idx, uintptr_t retaddr) { + return probe_access(env, addr, size, MMU_DATA_STORE, mmu_idx, retaddr); +} + +static inline void *probe_read(CPUArchState *env, vaddr addr, int size, int mmu_idx, uintptr_t retaddr) { + return probe_access(env, addr, size, MMU_DATA_LOAD, mmu_idx, retaddr); +} + +/** + * probe_access_flags: + * @env: CPUArchState + * @addr: guest virtual address to look up + * @size: size of the access + * @access_type: read, write or execute permission + * @mmu_idx: MMU index to use for lookup + * @nonfault: suppress the fault + * @phost: return value for host address + * @retaddr: return address for unwinding + * + * Similar to probe_access, loosely returning the TLB_FLAGS_MASK for + * the page, and storing the host address for RAM in @phost. + * + * If @nonfault is set, do not raise an exception but return TLB_INVALID_MASK. + * Do not handle watchpoints, but include TLB_WATCHPOINT in the returned flags. + * Do handle clean pages, so exclude TLB_NOTDIRY from the returned flags. + * For simplicity, all "mmio-like" flags are folded to TLB_MMIO. + */ +int probe_access_flags(CPUArchState *env, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, bool nonfault, + void **phost, uintptr_t retaddr); + +#ifndef CONFIG_USER_ONLY + +/** + * probe_access_full: + * Like probe_access_flags, except also return into @pfull. + * + * The CPUTLBEntryFull structure returned via @pfull is transient + * and must be consumed or copied immediately, before any further + * access or changes to TLB @mmu_idx. + * + * This function will not fault if @nonfault is set, but will + * return TLB_INVALID_MASK if the page is not mapped, or is not + * accessible with @access_type. + * + * This function will return TLB_MMIO in order to force the access + * to be handled out-of-line if plugins wish to instrument the access. + */ +int probe_access_full(CPUArchState *env, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, bool nonfault, + void **phost, CPUTLBEntryFull **pfull, uintptr_t retaddr); + +/** + * probe_access_full_mmu: + * Like probe_access_full, except: + * + * This function is intended to be used for page table accesses by + * the target mmu itself. Since such page walking happens while + * handling another potential mmu fault, this function never raises + * exceptions (akin to @nonfault true for probe_access_full). + * Likewise this function does not trigger plugin instrumentation. + */ +int probe_access_full_mmu(CPUArchState *env, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, void **phost, + CPUTLBEntryFull **pfull); + +#endif /* !CONFIG_USER_ONLY */ + +/** + * tlb_vaddr_to_host: + * @env: CPUArchState + * @addr: guest virtual address to look up + * @access_type: 0 for read, 1 for write, 2 for execute + * @mmu_idx: MMU index to use for lookup + * + * Look up the specified guest virtual index in the TCG softmmu TLB. + * If we can translate a host virtual address suitable for direct RAM + * access, without causing a guest exception, then return it. + * Otherwise (TLB entry is for an I/O access, guest software + * TLB fill required, etc) return NULL. + */ +void *tlb_vaddr_to_host(CPUArchState *env, vaddr addr, MMUAccessType access_type, int mmu_idx); + +#endif diff --git a/libcpu/include/cpu/exec/cputlb.h b/libcpu/include/cpu/exec/cputlb.h new file mode 100644 index 000000000..ab095c3a3 --- /dev/null +++ b/libcpu/include/cpu/exec/cputlb.h @@ -0,0 +1,243 @@ +/* + * Common CPU TLB handling + * + * Copyright (c) 2003 Fabrice Bellard + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ + +#ifndef CPUTLB_H +#define CPUTLB_H + +#include "exec/cpu-common.h" +#include "exec/hwaddr.h" +#include "exec/memattrs.h" +#include "exec/vaddr.h" + +#ifndef CONFIG_USER_ONLY +#include "system/ram_addr.h" + +void tlb_reset_dirty(CPUState *cpu, uintptr_t start, uintptr_t length); +void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length); +#endif + +/** + * tlb_set_page_full: + * @cpu: CPU context + * @mmu_idx: mmu index of the tlb to modify + * @addr: virtual address of the entry to add + * @full: the details of the tlb entry + * + * Add an entry to @cpu tlb index @mmu_idx. All of the fields of + * @full must be filled, except for xlat_offset & section, and + * constitute the complete description of the translated page. + * + * This is generally called by the target tlb_fill function after + * having performed a successful page table walk to find the physical + * address and attributes for the translation. + * + * At most one entry for a given virtual address is permitted. Only a + * single TARGET_PAGE_SIZE region is mapped; @full->lg_page_size is only + * used by tlb_flush_page. + */ +void tlb_set_page_full(CPUState *cpu, int mmu_idx, vaddr addr, CPUTLBEntryFull *full); + +/** + * tlb_set_page_with_attrs: + * @cpu: CPU to add this TLB entry for + * @addr: virtual address of page to add entry for + * @paddr: physical address of the page + * @attrs: memory transaction attributes + * @prot: access permissions (PAGE_READ/PAGE_WRITE/PAGE_EXEC bits) + * @mmu_idx: MMU index to insert TLB entry for + * @size: size of the page in bytes + * + * Add an entry to this CPU's TLB (a mapping from virtual address + * @addr to physical address @paddr) with the specified memory + * transaction attributes. This is generally called by the target CPU + * specific code after it has been called through the tlb_fill() + * entry point and performed a successful page table walk to find + * the physical address and attributes for the virtual address + * which provoked the TLB miss. + * + * At most one entry for a given virtual address is permitted. Only a + * single TARGET_PAGE_SIZE region is mapped; the supplied @size is only + * used by tlb_flush_page. + */ +void tlb_set_page_with_attrs(CPUState *cpu, vaddr addr, hwaddr paddr, MemTxAttrs attrs, int prot, int mmu_idx, + vaddr size); + +/** + * tlb_set_page: + * + * This function is equivalent to calling tlb_set_page_with_attrs() + * with an @attrs argument of MEMTXATTRS_UNSPECIFIED. It's provided + * as a convenience for CPUs which don't use memory transaction attributes. + */ +void tlb_set_page(CPUState *cpu, vaddr addr, hwaddr paddr, int prot, int mmu_idx, vaddr size); + +#if defined(CONFIG_TCG) && !defined(CONFIG_USER_ONLY) +/** + * tlb_flush_page: + * @cpu: CPU whose TLB should be flushed + * @addr: virtual address of page to be flushed + * + * Flush one page from the TLB of the specified CPU, for all + * MMU indexes. + */ +void tlb_flush_page(CPUState *cpu, vaddr addr); + +/** + * tlb_flush_page_all_cpus_synced: + * @cpu: src CPU of the flush + * @addr: virtual address of page to be flushed + * + * Flush one page from the TLB of all CPUs, for all + * MMU indexes. + * + * When this function returns, no CPUs will subsequently perform + * translations using the flushed TLBs. + */ +void tlb_flush_page_all_cpus_synced(CPUState *src, vaddr addr); + +/** + * tlb_flush: + * @cpu: CPU whose TLB should be flushed + * + * Flush the entire TLB for the specified CPU. Most CPU architectures + * allow the implementation to drop entries from the TLB at any time + * so this is generally safe. If more selective flushing is required + * use one of the other functions for efficiency. + */ +void tlb_flush(CPUState *cpu); + +/** + * tlb_flush_all_cpus_synced: + * @cpu: src CPU of the flush + * + * Flush the entire TLB for all CPUs, for all MMU indexes. + * + * When this function returns, no CPUs will subsequently perform + * translations using the flushed TLBs. + */ +void tlb_flush_all_cpus_synced(CPUState *src_cpu); + +/** + * tlb_flush_page_by_mmuidx: + * @cpu: CPU whose TLB should be flushed + * @addr: virtual address of page to be flushed + * @idxmap: bitmap of MMU indexes to flush + * + * Flush one page from the TLB of the specified CPU, for the specified + * MMU indexes. + */ +void tlb_flush_page_by_mmuidx(CPUState *cpu, vaddr addr, MMUIdxMap idxmap); + +/** + * tlb_flush_page_by_mmuidx_all_cpus_synced: + * @cpu: Originating CPU of the flush + * @addr: virtual address of page to be flushed + * @idxmap: bitmap of MMU indexes to flush + * + * Flush one page from the TLB of all CPUs, for the specified + * MMU indexes. + * + * When this function returns, no CPUs will subsequently perform + * translations using the flushed TLBs. + */ +void tlb_flush_page_by_mmuidx_all_cpus_synced(CPUState *cpu, vaddr addr, MMUIdxMap idxmap); + +/** + * tlb_flush_by_mmuidx: + * @cpu: CPU whose TLB should be flushed + * @wait: If true ensure synchronisation by exiting the cpu_loop + * @idxmap: bitmap of MMU indexes to flush + * + * Flush all entries from the TLB of the specified CPU, for the specified + * MMU indexes. + */ +void tlb_flush_by_mmuidx(CPUState *cpu, MMUIdxMap idxmap); + +/** + * tlb_flush_by_mmuidx_all_cpus_synced: + * @cpu: Originating CPU of the flush + * @idxmap: bitmap of MMU indexes to flush + * + * Flush all entries from the TLB of all CPUs, for the specified + * MMU indexes. + * + * When this function returns, no CPUs will subsequently perform + * translations using the flushed TLBs. + */ +void tlb_flush_by_mmuidx_all_cpus_synced(CPUState *cpu, MMUIdxMap idxmap); + +/** + * tlb_flush_page_bits_by_mmuidx + * @cpu: CPU whose TLB should be flushed + * @addr: virtual address of page to be flushed + * @idxmap: bitmap of mmu indexes to flush + * @bits: number of significant bits in address + * + * Similar to tlb_flush_page_mask, but with a bitmap of indexes. + */ +void tlb_flush_page_bits_by_mmuidx(CPUState *cpu, vaddr addr, MMUIdxMap idxmap, unsigned bits); + +/* Similarly, with broadcast and syncing. */ +void tlb_flush_page_bits_by_mmuidx_all_cpus_synced(CPUState *cpu, vaddr addr, MMUIdxMap idxmap, unsigned bits); + +/** + * tlb_flush_range_by_mmuidx + * @cpu: CPU whose TLB should be flushed + * @addr: virtual address of the start of the range to be flushed + * @len: length of range to be flushed + * @idxmap: bitmap of mmu indexes to flush + * @bits: number of significant bits in address + * + * For each mmuidx in @idxmap, flush all pages within [@addr,@addr+@len), + * comparing only the low @bits worth of each virtual page. + */ +void tlb_flush_range_by_mmuidx(CPUState *cpu, vaddr addr, vaddr len, MMUIdxMap idxmap, unsigned bits); + +/* Similarly, with broadcast and syncing. */ +void tlb_flush_range_by_mmuidx_all_cpus_synced(CPUState *cpu, vaddr addr, vaddr len, MMUIdxMap idxmap, unsigned bits); +#else +static inline void tlb_flush_page(CPUState *cpu, vaddr addr) { +} +static inline void tlb_flush_page_all_cpus_synced(CPUState *src, vaddr addr) { +} +static inline void tlb_flush(CPUState *cpu) { +} +static inline void tlb_flush_all_cpus_synced(CPUState *src_cpu) { +} +static inline void tlb_flush_page_by_mmuidx(CPUState *cpu, vaddr addr, MMUIdxMap idxmap) { +} + +static inline void tlb_flush_by_mmuidx(CPUState *cpu, MMUIdxMap idxmap) { +} +static inline void tlb_flush_page_by_mmuidx_all_cpus_synced(CPUState *cpu, vaddr addr, MMUIdxMap idxmap) { +} +static inline void tlb_flush_by_mmuidx_all_cpus_synced(CPUState *cpu, MMUIdxMap idxmap) { +} +static inline void tlb_flush_page_bits_by_mmuidx(CPUState *cpu, vaddr addr, MMUIdxMap idxmap, unsigned bits) { +} +static inline void tlb_flush_page_bits_by_mmuidx_all_cpus_synced(CPUState *cpu, vaddr addr, MMUIdxMap idxmap, + unsigned bits) { +} +static inline void tlb_flush_range_by_mmuidx(CPUState *cpu, vaddr addr, vaddr len, MMUIdxMap idxmap, unsigned bits) { +} +static inline void tlb_flush_range_by_mmuidx_all_cpus_synced(CPUState *cpu, vaddr addr, vaddr len, MMUIdxMap idxmap, + unsigned bits) { +} +#endif /* CONFIG_TCG && !CONFIG_USER_ONLY */ +#endif /* CPUTLB_H */ diff --git a/libcpu/include/cpu/exec/memattrs.h b/libcpu/include/cpu/exec/memattrs.h new file mode 100644 index 000000000..7f4548371 --- /dev/null +++ b/libcpu/include/cpu/exec/memattrs.h @@ -0,0 +1,93 @@ +/* + * Memory transaction attributes + * + * Copyright (c) 2015 Linaro Limited. + * + * Authors: + * Peter Maydell + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + */ + +#ifndef MEMATTRS_H +#define MEMATTRS_H + +/* Every memory transaction has associated with it a set of + * attributes. Some of these are generic (such as the ID of + * the bus master); some are specific to a particular kind of + * bus (such as the ARM Secure/NonSecure bit). We define them + * all as non-overlapping bitfields in a single struct to avoid + * confusion if different parts of QEMU used the same bit for + * different semantics. + */ +typedef struct MemTxAttrs { + /* + * ARM/AMBA: TrustZone Secure access + * x86: System Management Mode access + */ + unsigned int secure : 1; + /* + * ARM: ArmSecuritySpace. This partially overlaps secure, but it is + * easier to have both fields to assist code that does not understand + * ARMv9 RME, or no specific knowledge of ARM at all (e.g. pflash). + */ + unsigned int space : 2; + /* Memory access is usermode (unprivileged) */ + unsigned int user : 1; + /* + * Bus interconnect and peripherals can access anything (memories, + * devices) by default. By setting the 'memory' bit, bus transaction + * are restricted to "normal" memories (per the AMBA documentation) + * versus devices. Access to devices will be logged and rejected + * (see MEMTX_ACCESS_ERROR). + */ + unsigned int memory : 1; + /* Debug access that can even write to ROM. */ + unsigned int debug : 1; + /* Requester ID (for MSI for example) */ + unsigned int requester_id : 16; + + /* + * PID (PCI PASID) support: Limited to 8 bits process identifier. + */ + unsigned int pid : 8; + + /* PCI - IOMMU operations, see PCIAddressType */ + unsigned int address_type : 1; + + /* + * Bus masters which don't specify any attributes will get this + * (via the MEMTXATTRS_UNSPECIFIED constant), so that we can + * distinguish "all attributes deliberately clear" from + * "didn't specify" if necessary. "debug" can be set alongside + * "unspecified". + */ + bool unspecified; + + uint8_t _reserved1; + uint16_t _reserved2; +} MemTxAttrs; + +QEMU_BUILD_BUG_ON(sizeof(MemTxAttrs) > 8); + +/* Bus masters which don't specify any attributes will get this, + * which has all attribute bits clear except the topmost one + * (so that we can distinguish "all attributes deliberately clear" + * from "didn't specify" if necessary). + */ +#define MEMTXATTRS_UNSPECIFIED ((MemTxAttrs) {.unspecified = true}) + +/* New-style MMIO accessors can indicate that the transaction failed. + * A zero (MEMTX_OK) response means success; anything else is a failure + * of some kind. The memory subsystem will bitwise-OR together results + * if it is synthesizing an operation from multiple smaller accesses. + */ +#define MEMTX_OK 0 +#define MEMTX_ERROR (1U << 0) /* device returned an error */ +#define MEMTX_DECODE_ERROR (1U << 1) /* nothing at that address */ +#define MEMTX_ACCESS_ERROR (1U << 2) /* access denied */ +typedef uint32_t MemTxResult; + +#endif diff --git a/libcpu/include/cpu/exec/mmu-access-type.h b/libcpu/include/cpu/exec/mmu-access-type.h new file mode 100644 index 000000000..c08144835 --- /dev/null +++ b/libcpu/include/cpu/exec/mmu-access-type.h @@ -0,0 +1,18 @@ +/* + * QEMU MMU Access type definitions + * + * Copyright (c) 2012 SUSE LINUX Products GmbH + * + * SPDX-License-Identifier: GPL-2.0-or-later + */ +#ifndef EXEC_MMU_ACCESS_TYPE_H +#define EXEC_MMU_ACCESS_TYPE_H + +typedef enum MMUAccessType { + MMU_DATA_LOAD = 0, + MMU_DATA_STORE = 1, + MMU_INST_FETCH = 2 +#define MMU_ACCESS_COUNT 3 +} MMUAccessType; + +#endif diff --git a/libcpu/include/cpu/exec/page-protection.h b/libcpu/include/cpu/exec/page-protection.h new file mode 100644 index 000000000..4649760d1 --- /dev/null +++ b/libcpu/include/cpu/exec/page-protection.h @@ -0,0 +1,42 @@ +/* + * QEMU page protection definitions. + * + * Copyright (c) 2003 Fabrice Bellard + * + * SPDX-License-Identifier: LGPL-2.1+ + */ +#ifndef EXEC_PAGE_PROT_COMMON_H +#define EXEC_PAGE_PROT_COMMON_H + +/* same as PROT_xxx */ +#define PAGE_READ 0x0001 +#define PAGE_WRITE 0x0002 +#define PAGE_EXEC 0x0004 +#define PAGE_RWX (PAGE_READ | PAGE_WRITE | PAGE_EXEC) +#define PAGE_VALID 0x0008 +/* + * Original state of the write flag (used when tracking self-modifying code) + */ +#define PAGE_WRITE_ORG 0x0010 +/* + * Invalidate the TLB entry immediately, helpful for s390x + * Low-Address-Protection. Used with PAGE_WRITE in tlb_set_page_with_attrs() + */ +#define PAGE_WRITE_INV 0x0020 +/* + * For linux-user, indicates that the page is mapped with the same semantics + * in both guest and host. + */ +#define PAGE_PASSTHROUGH 0x40 +/* For linux-user, indicates that the page is MAP_ANON. */ +#define PAGE_ANON 0x0080 +/* + * For linux-user, indicates that the page should not be + * included in a core dump. + */ +#define PAGE_DONTDUMP 0x0100 +/* Target-specific bits that will be used via page_get_flags(). */ +#define PAGE_TARGET_1 0x0200 +#define PAGE_TARGET_2 0x0400 + +#endif diff --git a/libcpu/include/cpu/exec/tlb-flags.h b/libcpu/include/cpu/exec/tlb-flags.h new file mode 100644 index 000000000..016c5963c --- /dev/null +++ b/libcpu/include/cpu/exec/tlb-flags.h @@ -0,0 +1,84 @@ +/* + * TLB flags definition + * + * Copyright (c) 2003 Fabrice Bellard + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ +#ifndef TLB_FLAGS_H +#define TLB_FLAGS_H + +/* + * Flags returned for lookup of a TLB virtual address. + */ + +#ifdef CONFIG_USER_ONLY + +/* + * Allow some level of source compatibility with softmmu. + * INVALID is set when the page does not have requested permissions. + * FORCE_SLOW is set when we want the target helper to use the functional + * interface for load/store so that plugins see the access. + */ +#define TLB_INVALID_MASK (1 << 0) +#define TLB_FORCE_SLOW (1 << 1) +#define TLB_MMIO 0 +#define TLB_WATCHPOINT 0 + +#else + +/* + * Flags stored in CPUTLBEntryFull.slow_flags[x]. + * TLB_FORCE_SLOW must be set in CPUTLBEntry.addr_idx[x]. + */ + +/* Set if TLB entry requires byte swap. */ +#define TLB_BSWAP (1 << 0) +/* Set if TLB entry contains a watchpoint. */ +#define TLB_WATCHPOINT (1 << 1) +/* Set if TLB entry requires aligned accesses. */ +#define TLB_CHECK_ALIGNED (1 << 2) +/* Set if TLB entry writes ignored. */ +#define TLB_DISCARD_WRITE (1 << 3) +/* Set if TLB entry is an IO callback. */ +#define TLB_MMIO (1 << 4) + +#define TLB_SLOW_FLAGS_MASK (TLB_BSWAP | TLB_WATCHPOINT | TLB_CHECK_ALIGNED | TLB_DISCARD_WRITE | TLB_MMIO) + +/* + * Flags stored in CPUTLBEntry.addr_idx[x]. + * These must be above the largest alignment (64 bytes), + * and below the smallest page size (1024 bytes). + * This leaves bits [9:6] available for use. + */ + +/* Zero if TLB entry is valid. */ +#define TLB_INVALID_MASK (1 << 6) +/* Set if TLB entry references a clean RAM page. */ +#define TLB_NOTDIRTY (1 << 7) +/* Set if the slow path must be used; more flags in CPUTLBEntryFull. */ +#define TLB_FORCE_SLOW (1 << 8) + +/* + * Use this mask to check interception with an alignment mask + * in a TCG backend. + */ +#define TLB_FLAGS_MASK (TLB_INVALID_MASK | TLB_NOTDIRTY | TLB_FORCE_SLOW) + +/* The two sets of flags must not overlap. */ +QEMU_BUILD_BUG_ON(TLB_FLAGS_MASK &TLB_SLOW_FLAGS_MASK); + +#endif /* !CONFIG_USER_ONLY */ + +#endif /* TLB_FLAGS_H */ diff --git a/libcpu/include/cpu/exec/vaddr.h b/libcpu/include/cpu/exec/vaddr.h new file mode 100644 index 000000000..7c5579717 --- /dev/null +++ b/libcpu/include/cpu/exec/vaddr.h @@ -0,0 +1,20 @@ +/* Define vaddr. */ + +#ifndef VADDR_H +#define VADDR_H + +/** + * vaddr: + * Type wide enough to contain any #target_ulong virtual address. + * We do not support 64-bit guest on 32-host and detect at configure time. + * Therefore, a host pointer width will always fit a guest pointer. + */ +typedef uintptr_t vaddr; +#define VADDR_PRId PRIdPTR +#define VADDR_PRIu PRIuPTR +#define VADDR_PRIo PRIoPTR +#define VADDR_PRIx PRIxPTR +#define VADDR_PRIX PRIXPTR +#define VADDR_MAX UINTPTR_MAX + +#endif diff --git a/libcpu/scripts/upgrade/BASELINE b/libcpu/scripts/upgrade/BASELINE new file mode 100644 index 000000000..a933a5dd7 --- /dev/null +++ b/libcpu/scripts/upgrade/BASELINE @@ -0,0 +1 @@ +v11.1.0 diff --git a/libcpu/scripts/upgrade/mapping.tsv b/libcpu/scripts/upgrade/mapping.tsv new file mode 100644 index 000000000..9c11145f5 --- /dev/null +++ b/libcpu/scripts/upgrade/mapping.tsv @@ -0,0 +1,26 @@ +# libcpu path upstream QEMU path, as of the tag recorded in BASELINE. +# +# Only files that track upstream appear here. Hand-written files (cpu/state.h, +# everything under src/s2e/, the QEMU 1.0 code that has not been replaced yet) +# are deliberately absent: they have no upstream counterpart to merge from. +# +# The merge driver is scripts/upgrade/merge.sh at the S2E source root. +# +# upstream-dirs: accel/tcg/ include/accel/tcg/ include/exec/ +# --- softmmu ------------------------------------------------------------- +src/accel/cputlb.c accel/tcg/cputlb.c +src/accel/ldst_common.c.inc accel/tcg/ldst_common.c.inc +src/accel/ldst_atomicity.c.inc accel/tcg/ldst_atomicity.c.inc +src/accel/tlb-bounds.h accel/tcg/tlb-bounds.h +include/cpu/accel/cpu-ldst.h include/accel/tcg/cpu-ldst.h +include/cpu/accel/cpu-ldst-common.h include/accel/tcg/cpu-ldst-common.h +include/cpu/accel/probe.h include/accel/tcg/probe.h +include/cpu/exec/cputlb.h include/exec/cputlb.h +include/cpu/exec/tlb-flags.h include/exec/tlb-flags.h +include/cpu/exec/vaddr.h include/exec/vaddr.h +include/cpu/exec/memattrs.h include/exec/memattrs.h +include/cpu/exec/mmu-access-type.h include/exec/mmu-access-type.h +include/cpu/exec/page-protection.h include/exec/page-protection.h +include/cpu/accel/cpu-ops.h include/accel/tcg/cpu-ops.h +src/accel/atomic_common.c.inc accel/tcg/atomic_common.c.inc +src/accel/atomic_template.h accel/tcg/atomic_template.h diff --git a/libcpu/src/accel/atomic_common.c.inc b/libcpu/src/accel/atomic_common.c.inc new file mode 100644 index 000000000..dcf3badc5 --- /dev/null +++ b/libcpu/src/accel/atomic_common.c.inc @@ -0,0 +1,94 @@ +/* + * Common Atomic Helper Functions + * + * This file should be included before the various instantiations of + * the atomic_template.h helpers. + * + * Copyright (c) 2019 Linaro + * Written by Alex Bennée + * + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +static void atomic_trace_rmw_post(CPUArchState *env, uint64_t addr, uint64_t read_value_low, uint64_t read_value_high, + uint64_t write_value_low, uint64_t write_value_high, MemOpIdx oi) { + if (cpu_plugin_mem_cbs_enabled(env_cpu(env))) { + qemu_plugin_vcpu_mem_cb(env_cpu(env), addr, read_value_low, read_value_high, oi, QEMU_PLUGIN_MEM_R); + qemu_plugin_vcpu_mem_cb(env_cpu(env), addr, write_value_low, write_value_high, oi, QEMU_PLUGIN_MEM_W); + } +} + +/* + * Atomic helpers callable from TCG. + * These have a common interface and all defer to cpu_atomic_* + * using the host return address from GETPC(). + */ + +#define CMPXCHG_HELPER(OP, TYPE) \ + TYPE HELPER(atomic_##OP)(CPUArchState * env, uint64_t addr, TYPE oldv, TYPE newv, uint32_t oi) { \ + return cpu_atomic_##OP##_mmu(env, addr, oldv, newv, oi, GETPC()); \ + } + +CMPXCHG_HELPER(cmpxchgb, uint32_t) +CMPXCHG_HELPER(cmpxchgw_be, uint32_t) +CMPXCHG_HELPER(cmpxchgw_le, uint32_t) +CMPXCHG_HELPER(cmpxchgl_be, uint32_t) +CMPXCHG_HELPER(cmpxchgl_le, uint32_t) +CMPXCHG_HELPER(cmpxchgq_be, uint64_t) +CMPXCHG_HELPER(cmpxchgq_le, uint64_t) + +#if HAVE_CMPXCHG128 +CMPXCHG_HELPER(cmpxchgo_be, Int128) +CMPXCHG_HELPER(cmpxchgo_le, Int128) +#endif + +#undef CMPXCHG_HELPER + +#define ATOMIC_HELPER(OP, TYPE) \ + TYPE HELPER(glue(atomic_, OP))(CPUArchState * env, uint64_t addr, TYPE val, uint32_t oi) { \ + return glue(glue(cpu_atomic_, OP), _mmu)(env, addr, val, oi, GETPC()); \ + } + +#define GEN_ATOMIC_HELPERS(OP) \ + ATOMIC_HELPER(glue(OP, b), uint32_t) \ + ATOMIC_HELPER(glue(OP, w_be), uint32_t) \ + ATOMIC_HELPER(glue(OP, w_le), uint32_t) \ + ATOMIC_HELPER(glue(OP, l_be), uint32_t) \ + ATOMIC_HELPER(glue(OP, l_le), uint32_t) \ + ATOMIC_HELPER(glue(OP, q_be), uint64_t) \ + ATOMIC_HELPER(glue(OP, q_le), uint64_t) + +GEN_ATOMIC_HELPERS(fetch_add) +GEN_ATOMIC_HELPERS(fetch_and) +GEN_ATOMIC_HELPERS(fetch_or) +GEN_ATOMIC_HELPERS(fetch_xor) +GEN_ATOMIC_HELPERS(fetch_smin) +GEN_ATOMIC_HELPERS(fetch_umin) +GEN_ATOMIC_HELPERS(fetch_smax) +GEN_ATOMIC_HELPERS(fetch_umax) + +GEN_ATOMIC_HELPERS(add_fetch) +GEN_ATOMIC_HELPERS(and_fetch) +GEN_ATOMIC_HELPERS(or_fetch) +GEN_ATOMIC_HELPERS(xor_fetch) +GEN_ATOMIC_HELPERS(smin_fetch) +GEN_ATOMIC_HELPERS(umin_fetch) +GEN_ATOMIC_HELPERS(smax_fetch) +GEN_ATOMIC_HELPERS(umax_fetch) + +GEN_ATOMIC_HELPERS(xchg) + +#if HAVE_CMPXCHG128 +ATOMIC_HELPER(xchgo_be, Int128) +ATOMIC_HELPER(xchgo_le, Int128) +ATOMIC_HELPER(fetch_ando_be, Int128) +ATOMIC_HELPER(fetch_ando_le, Int128) +ATOMIC_HELPER(fetch_oro_be, Int128) +ATOMIC_HELPER(fetch_oro_le, Int128) +#endif + +#undef ATOMIC_HELPER +#undef GEN_ATOMIC_HELPERS diff --git a/libcpu/src/accel/atomic_template.h b/libcpu/src/accel/atomic_template.h new file mode 100644 index 000000000..8516e6236 --- /dev/null +++ b/libcpu/src/accel/atomic_template.h @@ -0,0 +1,316 @@ +/* + * Atomic helper templates + * Included from tcg-runtime.c and cputlb.c. + * + * Copyright (c) 2016 Red Hat, Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ + +#include "qemu/plugin.h" + +#if DATA_SIZE == 16 +#define SUFFIX o +#define DATA_TYPE Int128 +#define BSWAP bswap128 +#define SHIFT 4 +#elif DATA_SIZE == 8 +#define SUFFIX q +#define DATA_TYPE uint64_t +#define SDATA_TYPE int64_t +#define BSWAP bswap64 +#define SHIFT 3 +#elif DATA_SIZE == 4 +#define SUFFIX l +#define DATA_TYPE uint32_t +#define SDATA_TYPE int32_t +#define BSWAP bswap32 +#define SHIFT 2 +#elif DATA_SIZE == 2 +#define SUFFIX w +#define DATA_TYPE uint16_t +#define SDATA_TYPE int16_t +#define BSWAP bswap16 +#define SHIFT 1 +#elif DATA_SIZE == 1 +#define SUFFIX b +#define DATA_TYPE uint8_t +#define SDATA_TYPE int8_t +#define BSWAP +#define SHIFT 0 +#else +#error unsupported data size +#endif + +#if DATA_SIZE == 16 +#define VALUE_LOW(val) int128_getlo(val) +#define VALUE_HIGH(val) int128_gethi(val) +#else +#define VALUE_LOW(val) val +#define VALUE_HIGH(val) 0 +#endif + +#if DATA_SIZE >= 4 +#define ABI_TYPE DATA_TYPE +#else +#define ABI_TYPE uint32_t +#endif + +/* Define host-endian atomic operations. Note that END is used within + the ATOMIC_NAME macro, and redefined below. */ +#if DATA_SIZE == 1 +#define END +#elif HOST_BIG_ENDIAN +#define END _be +#else +#define END _le +#endif + +ABI_TYPE ATOMIC_NAME(cmpxchg)(CPUArchState *env, vaddr addr, ABI_TYPE cmpv, ABI_TYPE newv, MemOpIdx oi, + uintptr_t retaddr) { + DATA_TYPE *haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); + DATA_TYPE ret; + +#if DATA_SIZE == 16 + ret = atomic16_cmpxchg(haddr, cmpv, newv); +#else + ret = qatomic_cmpxchg__nocheck(haddr, cmpv, newv); +#endif + ATOMIC_MMU_CLEANUP; + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(newv), VALUE_HIGH(newv), oi); + return ret; +} + +ABI_TYPE ATOMIC_NAME(xchg)(CPUArchState *env, vaddr addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { + DATA_TYPE *haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); + DATA_TYPE ret; + +#if DATA_SIZE == 16 + ret = atomic16_xchg(haddr, val); +#else + ret = qatomic_xchg__nocheck(haddr, val); +#endif + ATOMIC_MMU_CLEANUP; + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(val), VALUE_HIGH(val), oi); + return ret; +} + +#if DATA_SIZE == 16 +ABI_TYPE ATOMIC_NAME(fetch_and)(CPUArchState *env, vaddr addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { + DATA_TYPE *haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); + DATA_TYPE ret = atomic16_fetch_and(haddr, val); + ATOMIC_MMU_CLEANUP; + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(val), VALUE_HIGH(val), oi); + return ret; +} + +ABI_TYPE ATOMIC_NAME(fetch_or)(CPUArchState *env, vaddr addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { + DATA_TYPE *haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); + DATA_TYPE ret = atomic16_fetch_or(haddr, val); + ATOMIC_MMU_CLEANUP; + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(val), VALUE_HIGH(val), oi); + return ret; +} +#else +#define GEN_ATOMIC_HELPER(X) \ + ABI_TYPE ATOMIC_NAME(X)(CPUArchState * env, vaddr addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { \ + DATA_TYPE *haddr, ret; \ + haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); \ + ret = qatomic_##X(haddr, val); \ + ATOMIC_MMU_CLEANUP; \ + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(val), VALUE_HIGH(val), oi); \ + return ret; \ + } + +GEN_ATOMIC_HELPER(fetch_add) +GEN_ATOMIC_HELPER(fetch_and) +GEN_ATOMIC_HELPER(fetch_or) +GEN_ATOMIC_HELPER(fetch_xor) +GEN_ATOMIC_HELPER(add_fetch) +GEN_ATOMIC_HELPER(and_fetch) +GEN_ATOMIC_HELPER(or_fetch) +GEN_ATOMIC_HELPER(xor_fetch) + +#undef GEN_ATOMIC_HELPER + +/* + * These helpers are, as a whole, full barriers. Within the helper, + * the leading barrier is explicit and the trailing barrier is within + * cmpxchg primitive. + * + * Trace this load + RMW loop as a single RMW op. This way, regardless + * of CF_PARALLEL's value, we'll trace just a read and a write. + */ +#define GEN_ATOMIC_HELPER_FN(X, FN, XDATA_TYPE, RET) \ + ABI_TYPE ATOMIC_NAME(X)(CPUArchState * env, vaddr addr, ABI_TYPE xval, MemOpIdx oi, uintptr_t retaddr) { \ + XDATA_TYPE *haddr, cmp, old, new, val = xval; \ + haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); \ + smp_mb(); \ + cmp = qatomic_read__nocheck(haddr); \ + do { \ + old = cmp; \ + new = FN(old, val); \ + cmp = qatomic_cmpxchg__nocheck(haddr, old, new); \ + } while (cmp != old); \ + ATOMIC_MMU_CLEANUP; \ + atomic_trace_rmw_post(env, addr, VALUE_LOW(old), VALUE_HIGH(old), VALUE_LOW(xval), VALUE_HIGH(xval), oi); \ + return RET; \ + } + +GEN_ATOMIC_HELPER_FN(fetch_smin, MIN, SDATA_TYPE, old) +GEN_ATOMIC_HELPER_FN(fetch_umin, MIN, DATA_TYPE, old) +GEN_ATOMIC_HELPER_FN(fetch_smax, MAX, SDATA_TYPE, old) +GEN_ATOMIC_HELPER_FN(fetch_umax, MAX, DATA_TYPE, old) + +GEN_ATOMIC_HELPER_FN(smin_fetch, MIN, SDATA_TYPE, new) +GEN_ATOMIC_HELPER_FN(umin_fetch, MIN, DATA_TYPE, new) +GEN_ATOMIC_HELPER_FN(smax_fetch, MAX, SDATA_TYPE, new) +GEN_ATOMIC_HELPER_FN(umax_fetch, MAX, DATA_TYPE, new) + +#undef GEN_ATOMIC_HELPER_FN +#endif /* DATA SIZE == 16 */ + +#undef END + +#if DATA_SIZE > 1 + +/* Define reverse-host-endian atomic operations. Note that END is used + within the ATOMIC_NAME macro. */ +#if HOST_BIG_ENDIAN +#define END _le +#else +#define END _be +#endif + +ABI_TYPE ATOMIC_NAME(cmpxchg)(CPUArchState *env, vaddr addr, ABI_TYPE cmpv, ABI_TYPE newv, MemOpIdx oi, + uintptr_t retaddr) { + DATA_TYPE *haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); + DATA_TYPE ret; + +#if DATA_SIZE == 16 + ret = atomic16_cmpxchg(haddr, BSWAP(cmpv), BSWAP(newv)); +#else + ret = qatomic_cmpxchg__nocheck(haddr, BSWAP(cmpv), BSWAP(newv)); +#endif + ATOMIC_MMU_CLEANUP; + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(newv), VALUE_HIGH(newv), oi); + return BSWAP(ret); +} + +ABI_TYPE ATOMIC_NAME(xchg)(CPUArchState *env, vaddr addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { + DATA_TYPE *haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); + ABI_TYPE ret; + +#if DATA_SIZE == 16 + ret = atomic16_xchg(haddr, BSWAP(val)); +#else + ret = qatomic_xchg__nocheck(haddr, BSWAP(val)); +#endif + ATOMIC_MMU_CLEANUP; + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(val), VALUE_HIGH(val), oi); + return BSWAP(ret); +} + +#if DATA_SIZE == 16 +ABI_TYPE ATOMIC_NAME(fetch_and)(CPUArchState *env, vaddr addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { + DATA_TYPE *haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); + DATA_TYPE ret = atomic16_fetch_and(haddr, BSWAP(val)); + ATOMIC_MMU_CLEANUP; + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(val), VALUE_HIGH(val), oi); + return BSWAP(ret); +} + +ABI_TYPE ATOMIC_NAME(fetch_or)(CPUArchState *env, vaddr addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { + DATA_TYPE *haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); + DATA_TYPE ret = atomic16_fetch_or(haddr, BSWAP(val)); + ATOMIC_MMU_CLEANUP; + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(val), VALUE_HIGH(val), oi); + return BSWAP(ret); +} +#else +#define GEN_ATOMIC_HELPER(X) \ + ABI_TYPE ATOMIC_NAME(X)(CPUArchState * env, vaddr addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { \ + DATA_TYPE *haddr, ret; \ + haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); \ + ret = qatomic_##X(haddr, BSWAP(val)); \ + ATOMIC_MMU_CLEANUP; \ + atomic_trace_rmw_post(env, addr, VALUE_LOW(ret), VALUE_HIGH(ret), VALUE_LOW(val), VALUE_HIGH(val), oi); \ + return BSWAP(ret); \ + } + +GEN_ATOMIC_HELPER(fetch_and) +GEN_ATOMIC_HELPER(fetch_or) +GEN_ATOMIC_HELPER(fetch_xor) +GEN_ATOMIC_HELPER(and_fetch) +GEN_ATOMIC_HELPER(or_fetch) +GEN_ATOMIC_HELPER(xor_fetch) + +#undef GEN_ATOMIC_HELPER + +/* These helpers are, as a whole, full barriers. Within the helper, + * the leading barrier is explicit and the trailing barrier is within + * cmpxchg primitive. + * + * Trace this load + RMW loop as a single RMW op. This way, regardless + * of CF_PARALLEL's value, we'll trace just a read and a write. + */ +#define GEN_ATOMIC_HELPER_FN(X, FN, XDATA_TYPE, RET) \ + ABI_TYPE ATOMIC_NAME(X)(CPUArchState * env, vaddr addr, ABI_TYPE xval, MemOpIdx oi, uintptr_t retaddr) { \ + XDATA_TYPE *haddr, ldo, ldn, old, new, val = xval; \ + haddr = atomic_mmu_lookup(env_cpu(env), addr, oi, DATA_SIZE, retaddr); \ + smp_mb(); \ + ldn = qatomic_read__nocheck(haddr); \ + do { \ + ldo = ldn; \ + old = BSWAP(ldo); \ + new = FN(old, val); \ + ldn = qatomic_cmpxchg__nocheck(haddr, ldo, BSWAP(new)); \ + } while (ldo != ldn); \ + ATOMIC_MMU_CLEANUP; \ + atomic_trace_rmw_post(env, addr, VALUE_LOW(old), VALUE_HIGH(old), VALUE_LOW(xval), VALUE_HIGH(xval), oi); \ + return RET; \ + } + +GEN_ATOMIC_HELPER_FN(fetch_smin, MIN, SDATA_TYPE, old) +GEN_ATOMIC_HELPER_FN(fetch_umin, MIN, DATA_TYPE, old) +GEN_ATOMIC_HELPER_FN(fetch_smax, MAX, SDATA_TYPE, old) +GEN_ATOMIC_HELPER_FN(fetch_umax, MAX, DATA_TYPE, old) + +GEN_ATOMIC_HELPER_FN(smin_fetch, MIN, SDATA_TYPE, new) +GEN_ATOMIC_HELPER_FN(umin_fetch, MIN, DATA_TYPE, new) +GEN_ATOMIC_HELPER_FN(smax_fetch, MAX, SDATA_TYPE, new) +GEN_ATOMIC_HELPER_FN(umax_fetch, MAX, DATA_TYPE, new) + +/* Note that for addition, we need to use a separate cmpxchg loop instead + of bswaps for the reverse-host-endian helpers. */ +#define ADD(X, Y) (X + Y) +GEN_ATOMIC_HELPER_FN(fetch_add, ADD, DATA_TYPE, old) +GEN_ATOMIC_HELPER_FN(add_fetch, ADD, DATA_TYPE, new) +#undef ADD + +#undef GEN_ATOMIC_HELPER_FN +#endif /* DATA_SIZE == 16 */ + +#undef END +#endif /* DATA_SIZE > 1 */ + +#undef BSWAP +#undef ABI_TYPE +#undef DATA_TYPE +#undef SDATA_TYPE +#undef SUFFIX +#undef DATA_SIZE +#undef SHIFT +#undef VALUE_LOW +#undef VALUE_HIGH diff --git a/libcpu/src/accel/cputlb.c b/libcpu/src/accel/cputlb.c new file mode 100644 index 000000000..dafa9368d --- /dev/null +++ b/libcpu/src/accel/cputlb.c @@ -0,0 +1,2618 @@ +/* + * Common CPU TLB handling (system emulation) + * + * Copyright (c) 2003 Fabrice Bellard + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ + +#include "exec/cputlb.h" +#include "accel/tcg/cpu-ldst-common.h" +#include "accel/tcg/cpu-loop.h" +#include "accel/tcg/cpu-mmu-index.h" +#include "accel/tcg/cpu-ops.h" +#include "accel/tcg/iommu.h" +#include "accel/tcg/probe.h" +#include "exec/helper-proto-common.h" +#include "exec/log.h" +#include "exec/mmu-access-type.h" +#include "exec/page-protection.h" +#include "exec/tb-flush.h" +#include "exec/tlb-common.h" +#include "exec/tlb-flags.h" +#include "exec/vaddr.h" +#include "internal-common.h" +#include "qemu/atomic.h" +#include "qemu/atomic128.h" +#include "qemu/error-report.h" +#include "qemu/main-loop.h" +#include "qemu/osdep.h" +#include "qemu/target-info.h" +#include "system-page-protection.h" +#include "system/memory.h" +#include "system/physmem.h" +#include "system/ramblock.h" +#include "tb-hash.h" +#include "tb-internal.h" +#include "tcg/tcg.h" +#include "tlb-bounds.h" +#include "trace.h" +#ifdef CONFIG_PLUGIN +#include "qemu/plugin-memory.h" +#endif +#include "backend-ldst.h" +#include "tcg/tcg-ldst.h" + +/* DEBUG defines, enable DEBUG_TLB_LOG to log to the CPU_LOG_MMU target */ +/* #define DEBUG_TLB */ +/* #define DEBUG_TLB_LOG */ + +#ifdef DEBUG_TLB +#define DEBUG_TLB_GATE 1 +#ifdef DEBUG_TLB_LOG +#define DEBUG_TLB_LOG_GATE 1 +#else +#define DEBUG_TLB_LOG_GATE 0 +#endif +#else +#define DEBUG_TLB_GATE 0 +#define DEBUG_TLB_LOG_GATE 0 +#endif + +#define tlb_debug(fmt, ...) \ + do { \ + if (DEBUG_TLB_LOG_GATE) { \ + qemu_log_mask(CPU_LOG_MMU, "%s: " fmt, __func__, ##__VA_ARGS__); \ + } else if (DEBUG_TLB_GATE) { \ + fprintf(stderr, "%s: " fmt, __func__, ##__VA_ARGS__); \ + } \ + } while (0) + +#define assert_cpu_is_self(cpu) \ + do { \ + if (DEBUG_TLB_GATE) { \ + g_assert(!(cpu)->created || qemu_cpu_is_self(cpu)); \ + } \ + } while (0) + +/* run_on_cpu_data.target_ptr should always be big enough for a + * vaddr even on 32 bit builds + */ +QEMU_BUILD_BUG_ON(sizeof(vaddr) > sizeof(run_on_cpu_data)); + +#define ALL_MMUIDX_BITS ((1 << NB_MMU_MODES) - 1) + +static inline size_t tlb_n_entries(CPUTLBDescFast *fast) { + return (fast->mask >> CPU_TLB_ENTRY_BITS) + 1; +} + +static inline size_t sizeof_tlb(CPUTLBDescFast *fast) { + return fast->mask + (1 << CPU_TLB_ENTRY_BITS); +} + +static inline uint64_t tlb_read_idx(const CPUTLBEntry *entry, MMUAccessType access_type) { + /* Do not rearrange the CPUTLBEntry structure members. */ + QEMU_BUILD_BUG_ON(offsetof(CPUTLBEntry, addr_read) != MMU_DATA_LOAD * sizeof(uintptr_t)); + QEMU_BUILD_BUG_ON(offsetof(CPUTLBEntry, addr_write) != MMU_DATA_STORE * sizeof(uintptr_t)); + QEMU_BUILD_BUG_ON(offsetof(CPUTLBEntry, addr_code) != MMU_INST_FETCH * sizeof(uintptr_t)); + + const uintptr_t *ptr = &entry->addr_idx[access_type]; + /* ofs might correspond to .addr_write, so use qatomic_read */ + return qatomic_read(ptr); +} + +static inline uint64_t tlb_addr_write(const CPUTLBEntry *entry) { + return tlb_read_idx(entry, MMU_DATA_STORE); +} + +/* Find the TLB index corresponding to the mmu_idx + address pair. */ +static inline uintptr_t tlb_index(CPUState *cpu, uintptr_t mmu_idx, vaddr addr) { + uintptr_t size_mask = cpu_tlb_fast(cpu, mmu_idx)->mask >> CPU_TLB_ENTRY_BITS; + + return (addr >> TARGET_PAGE_BITS) & size_mask; +} + +/* Find the TLB entry corresponding to the mmu_idx + address pair. */ +static inline CPUTLBEntry *tlb_entry(CPUState *cpu, uintptr_t mmu_idx, vaddr addr) { + return &cpu_tlb_fast(cpu, mmu_idx)->table[tlb_index(cpu, mmu_idx, addr)]; +} + +static void tlb_window_reset(CPUTLBDesc *desc, int64_t ns, size_t max_entries) { + desc->window_begin_ns = ns; + desc->window_max_entries = max_entries; +} + +static void tb_jmp_cache_clear_page(CPUState *cpu, vaddr page_addr) { + CPUJumpCache *jc = cpu->tb_jmp_cache; + int i, i0; + + if (unlikely(!jc)) { + return; + } + + i0 = tb_jmp_cache_hash_page(page_addr); + for (i = 0; i < TB_JMP_PAGE_SIZE; i++) { + qatomic_set(&jc->array[i0 + i].tb, NULL); + } +} + +/** + * tlb_mmu_resize_locked() - perform TLB resize bookkeeping; resize if necessary + * @desc: The CPUTLBDesc portion of the TLB + * @fast: The CPUTLBDescFast portion of the same TLB + * + * Called with tlb_lock_held. + * + * We have two main constraints when resizing a TLB: (1) we only resize it + * on a TLB flush (otherwise we'd have to take a perf hit by either rehashing + * the array or unnecessarily flushing it), which means we do not control how + * frequently the resizing can occur; (2) we don't have access to the guest's + * future scheduling decisions, and therefore have to decide the magnitude of + * the resize based on past observations. + * + * In general, a memory-hungry process can benefit greatly from an appropriately + * sized TLB, since a guest TLB miss is very expensive. This doesn't mean that + * we just have to make the TLB as large as possible; while an oversized TLB + * results in minimal TLB miss rates, it also takes longer to be flushed + * (flushes can be _very_ frequent), and the reduced locality can also hurt + * performance. + * + * To achieve near-optimal performance for all kinds of workloads, we: + * + * 1. Aggressively increase the size of the TLB when the use rate of the + * TLB being flushed is high, since it is likely that in the near future this + * memory-hungry process will execute again, and its memory hungriness will + * probably be similar. + * + * 2. Slowly reduce the size of the TLB as the use rate declines over a + * reasonably large time window. The rationale is that if in such a time window + * we have not observed a high TLB use rate, it is likely that we won't observe + * it in the near future. In that case, once a time window expires we downsize + * the TLB to match the maximum use rate observed in the window. + * + * 3. Try to keep the maximum use rate in a time window in the 30-70% range, + * since in that range performance is likely near-optimal. Recall that the TLB + * is direct mapped, so we want the use rate to be low (or at least not too + * high), since otherwise we are likely to have a significant amount of + * conflict misses. + */ +static void tlb_mmu_resize_locked(CPUTLBDesc *desc, CPUTLBDescFast *fast, int64_t now) { + size_t old_size = tlb_n_entries(fast); + size_t rate; + size_t new_size = old_size; + int64_t window_len_ms = 100; + int64_t window_len_ns = window_len_ms * 1000 * 1000; + bool window_expired = now > desc->window_begin_ns + window_len_ns; + + if (desc->n_used_entries > desc->window_max_entries) { + desc->window_max_entries = desc->n_used_entries; + } + rate = desc->window_max_entries * 100 / old_size; + + if (rate > 70) { + new_size = MIN(old_size << 1, 1 << CPU_TLB_DYN_MAX_BITS); + } else if (rate < 30 && window_expired) { + size_t ceil = pow2ceil(desc->window_max_entries); + size_t expected_rate = desc->window_max_entries * 100 / ceil; + + /* + * Avoid undersizing when the max number of entries seen is just below + * a pow2. For instance, if max_entries == 1025, the expected use rate + * would be 1025/2048==50%. However, if max_entries == 1023, we'd get + * 1023/1024==99.9% use rate, so we'd likely end up doubling the size + * later. Thus, make sure that the expected use rate remains below 70%. + * (and since we double the size, that means the lowest rate we'd + * expect to get is 35%, which is still in the 30-70% range where + * we consider that the size is appropriate.) + */ + if (expected_rate > 70) { + ceil *= 2; + } + new_size = MAX(ceil, 1 << CPU_TLB_DYN_MIN_BITS); + } + + if (new_size == old_size) { + if (window_expired) { + tlb_window_reset(desc, now, desc->n_used_entries); + } + return; + } + + g_free(fast->table); + g_free(desc->fulltlb); + + tlb_window_reset(desc, now, 0); + /* desc->n_used_entries is cleared by the caller */ + fast->mask = (new_size - 1) << CPU_TLB_ENTRY_BITS; + fast->table = g_try_new(CPUTLBEntry, new_size); + desc->fulltlb = g_try_new(CPUTLBEntryFull, new_size); + + /* + * If the allocations fail, try smaller sizes. We just freed some + * memory, so going back to half of new_size has a good chance of working. + * Increased memory pressure elsewhere in the system might cause the + * allocations to fail though, so we progressively reduce the allocation + * size, aborting if we cannot even allocate the smallest TLB we support. + */ + while (fast->table == NULL || desc->fulltlb == NULL) { + if (new_size == (1 << CPU_TLB_DYN_MIN_BITS)) { + error_report("%s: %s", __func__, strerror(errno)); + abort(); + } + new_size = MAX(new_size >> 1, 1 << CPU_TLB_DYN_MIN_BITS); + fast->mask = (new_size - 1) << CPU_TLB_ENTRY_BITS; + + g_free(fast->table); + g_free(desc->fulltlb); + fast->table = g_try_new(CPUTLBEntry, new_size); + desc->fulltlb = g_try_new(CPUTLBEntryFull, new_size); + } +} + +static void tlb_mmu_flush_locked(CPUTLBDesc *desc, CPUTLBDescFast *fast) { + desc->n_used_entries = 0; + desc->large_page_addr = -1; + desc->large_page_mask = -1; + desc->vindex = 0; + memset(fast->table, -1, sizeof_tlb(fast)); + memset(desc->vtable, -1, sizeof(desc->vtable)); +} + +static void tlb_flush_one_mmuidx_locked(CPUState *cpu, int mmu_idx, int64_t now) { + CPUTLBDesc *desc = &cpu->neg.tlb.d[mmu_idx]; + CPUTLBDescFast *fast = cpu_tlb_fast(cpu, mmu_idx); + + tlb_mmu_resize_locked(desc, fast, now); + tlb_mmu_flush_locked(desc, fast); +} + +static void tlb_mmu_init(CPUTLBDesc *desc, CPUTLBDescFast *fast, int64_t now) { + size_t n_entries = 1 << CPU_TLB_DYN_DEFAULT_BITS; + + tlb_window_reset(desc, now, 0); + desc->n_used_entries = 0; + fast->mask = (n_entries - 1) << CPU_TLB_ENTRY_BITS; + fast->table = g_new(CPUTLBEntry, n_entries); + desc->fulltlb = g_new(CPUTLBEntryFull, n_entries); + tlb_mmu_flush_locked(desc, fast); +} + +static inline void tlb_n_used_entries_inc(CPUState *cpu, uintptr_t mmu_idx) { + cpu->neg.tlb.d[mmu_idx].n_used_entries++; +} + +static inline void tlb_n_used_entries_dec(CPUState *cpu, uintptr_t mmu_idx) { + cpu->neg.tlb.d[mmu_idx].n_used_entries--; +} + +void tlb_init(CPUState *cpu) { + int64_t now = get_clock_realtime(); + int i; + + qemu_spin_init(&cpu->neg.tlb.c.lock); + + /* All tlbs are initialized flushed. */ + cpu->neg.tlb.c.dirty = 0; + + for (i = 0; i < NB_MMU_MODES; i++) { + tlb_mmu_init(&cpu->neg.tlb.d[i], cpu_tlb_fast(cpu, i), now); + } +} + +void tlb_destroy(CPUState *cpu) { + int i; + + qemu_spin_destroy(&cpu->neg.tlb.c.lock); + for (i = 0; i < NB_MMU_MODES; i++) { + CPUTLBDesc *desc = &cpu->neg.tlb.d[i]; + CPUTLBDescFast *fast = cpu_tlb_fast(cpu, i); + + g_free(fast->table); + g_free(desc->fulltlb); + } +} + +/* flush_all_helper: run fn across all cpus + * + * If the wait flag is set then the src cpu's helper will be queued as + * "safe" work and the loop exited creating a synchronisation point + * where all queued work will be finished before execution starts + * again. + */ +static void flush_all_helper(CPUState *src, run_on_cpu_func fn, run_on_cpu_data d) { + CPUState *cpu; + + CPU_FOREACH(cpu) { + if (cpu != src) { + async_run_on_cpu(cpu, fn, d); + } + } +} + +static void tlb_flush_by_mmuidx_async_work(CPUState *cpu, run_on_cpu_data data) { + MMUIdxMap asked = data.host_int; + MMUIdxMap all_dirty, work, to_clean; + int64_t now = get_clock_realtime(); + + assert_cpu_is_self(cpu); + + tlb_debug("mmu_idx:0x%04" PRIx16 "\n", asked); + + qemu_spin_lock(&cpu->neg.tlb.c.lock); + + all_dirty = cpu->neg.tlb.c.dirty; + to_clean = asked & all_dirty; + all_dirty &= ~to_clean; + cpu->neg.tlb.c.dirty = all_dirty; + + for (work = to_clean; work != 0; work &= work - 1) { + int mmu_idx = ctz32(work); + tlb_flush_one_mmuidx_locked(cpu, mmu_idx, now); + } + + qemu_spin_unlock(&cpu->neg.tlb.c.lock); + + tcg_flush_jmp_cache(cpu); + + if (to_clean == ALL_MMUIDX_BITS) { + qatomic_set(&cpu->neg.tlb.c.full_flush_count, cpu->neg.tlb.c.full_flush_count + 1); + } else { + qatomic_set(&cpu->neg.tlb.c.part_flush_count, cpu->neg.tlb.c.part_flush_count + ctpop16(to_clean)); + if (to_clean != asked) { + qatomic_set(&cpu->neg.tlb.c.elide_flush_count, + cpu->neg.tlb.c.elide_flush_count + ctpop16(asked & ~to_clean)); + } + } +} + +void tlb_flush_by_mmuidx(CPUState *cpu, MMUIdxMap idxmap) { + tlb_debug("mmu_idx: 0x%" PRIx16 "\n", idxmap); + + assert_cpu_is_self(cpu); + + tlb_flush_by_mmuidx_async_work(cpu, RUN_ON_CPU_HOST_INT(idxmap)); +} + +void tlb_flush(CPUState *cpu) { + tlb_flush_by_mmuidx(cpu, ALL_MMUIDX_BITS); +} + +void tlb_flush_by_mmuidx_all_cpus_synced(CPUState *src_cpu, MMUIdxMap idxmap) { + const run_on_cpu_func fn = tlb_flush_by_mmuidx_async_work; + + tlb_debug("mmu_idx: 0x%" PRIx16 "\n", idxmap); + + flush_all_helper(src_cpu, fn, RUN_ON_CPU_HOST_INT(idxmap)); + async_safe_run_on_cpu(src_cpu, fn, RUN_ON_CPU_HOST_INT(idxmap)); +} + +void tlb_flush_all_cpus_synced(CPUState *src_cpu) { + tlb_flush_by_mmuidx_all_cpus_synced(src_cpu, ALL_MMUIDX_BITS); +} + +static bool tlb_hit_page_mask_anyprot(CPUTLBEntry *tlb_entry, vaddr page, vaddr mask) { + page &= mask; + mask &= TARGET_PAGE_MASK | TLB_INVALID_MASK; + + return (page == (tlb_entry->addr_read & mask) || page == (tlb_addr_write(tlb_entry) & mask) || + page == (tlb_entry->addr_code & mask)); +} + +static inline bool tlb_hit_page_anyprot(CPUTLBEntry *tlb_entry, vaddr page) { + return tlb_hit_page_mask_anyprot(tlb_entry, page, -1); +} + +/** + * tlb_entry_is_empty - return true if the entry is not in use + * @te: pointer to CPUTLBEntry + */ +static inline bool tlb_entry_is_empty(const CPUTLBEntry *te) { + return te->addr_read == -1 && te->addr_write == -1 && te->addr_code == -1; +} + +/* Called with tlb_c.lock held */ +static bool tlb_flush_entry_mask_locked(CPUTLBEntry *tlb_entry, vaddr page, vaddr mask) { + if (tlb_hit_page_mask_anyprot(tlb_entry, page, mask)) { + memset(tlb_entry, -1, sizeof(*tlb_entry)); + return true; + } + return false; +} + +static inline bool tlb_flush_entry_locked(CPUTLBEntry *tlb_entry, vaddr page) { + return tlb_flush_entry_mask_locked(tlb_entry, page, -1); +} + +/* Called with tlb_c.lock held */ +static void tlb_flush_vtlb_page_mask_locked(CPUState *cpu, int mmu_idx, vaddr page, vaddr mask) { + CPUTLBDesc *d = &cpu->neg.tlb.d[mmu_idx]; + int k; + + assert_cpu_is_self(cpu); + for (k = 0; k < CPU_VTLB_SIZE; k++) { + if (tlb_flush_entry_mask_locked(&d->vtable[k], page, mask)) { + tlb_n_used_entries_dec(cpu, mmu_idx); + } + } +} + +static inline void tlb_flush_vtlb_page_locked(CPUState *cpu, int mmu_idx, vaddr page) { + tlb_flush_vtlb_page_mask_locked(cpu, mmu_idx, page, -1); +} + +static void tlb_flush_page_locked(CPUState *cpu, int midx, vaddr page) { + vaddr lp_addr = cpu->neg.tlb.d[midx].large_page_addr; + vaddr lp_mask = cpu->neg.tlb.d[midx].large_page_mask; + + /* Check if we need to flush due to large pages. */ + if ((page & lp_mask) == lp_addr) { + tlb_debug("forcing full flush midx %d (%016" VADDR_PRIx "/%016" VADDR_PRIx ")\n", midx, lp_addr, lp_mask); + tlb_flush_one_mmuidx_locked(cpu, midx, get_clock_realtime()); + } else { + if (tlb_flush_entry_locked(tlb_entry(cpu, midx, page), page)) { + tlb_n_used_entries_dec(cpu, midx); + } + tlb_flush_vtlb_page_locked(cpu, midx, page); + } +} + +/** + * tlb_flush_page_by_mmuidx_async_0: + * @cpu: cpu on which to flush + * @addr: page of virtual address to flush + * @idxmap: set of mmu_idx to flush + * + * Helper for tlb_flush_page_by_mmuidx and friends, flush one page + * at @addr from the tlbs indicated by @idxmap from @cpu. + */ +static void tlb_flush_page_by_mmuidx_async_0(CPUState *cpu, vaddr addr, MMUIdxMap idxmap) { + int mmu_idx; + + assert_cpu_is_self(cpu); + + tlb_debug("page addr: %016" VADDR_PRIx " mmu_map:0x%x\n", addr, idxmap); + + qemu_spin_lock(&cpu->neg.tlb.c.lock); + for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { + if ((idxmap >> mmu_idx) & 1) { + tlb_flush_page_locked(cpu, mmu_idx, addr); + } + } + qemu_spin_unlock(&cpu->neg.tlb.c.lock); + + /* + * Discard jump cache entries for any tb which might potentially + * overlap the flushed page, which includes the previous. + */ + tb_jmp_cache_clear_page(cpu, addr - TARGET_PAGE_SIZE); + tb_jmp_cache_clear_page(cpu, addr); +} + +/** + * tlb_flush_page_by_mmuidx_async_1: + * @cpu: cpu on which to flush + * @data: encoded addr + idxmap + * + * Helper for tlb_flush_page_by_mmuidx and friends, called through + * async_run_on_cpu. The idxmap parameter is encoded in the page + * offset of the target_ptr field. This limits the set of mmu_idx + * that can be passed via this method. + */ +static void tlb_flush_page_by_mmuidx_async_1(CPUState *cpu, run_on_cpu_data data) { + vaddr addr_and_idxmap = data.target_ptr; + vaddr addr = addr_and_idxmap & TARGET_PAGE_MASK; + MMUIdxMap idxmap = addr_and_idxmap & ~TARGET_PAGE_MASK; + + tlb_flush_page_by_mmuidx_async_0(cpu, addr, idxmap); +} + +typedef struct { + vaddr addr; + MMUIdxMap idxmap; +} TLBFlushPageByMMUIdxData; + +/** + * tlb_flush_page_by_mmuidx_async_2: + * @cpu: cpu on which to flush + * @data: allocated addr + idxmap + * + * Helper for tlb_flush_page_by_mmuidx and friends, called through + * async_run_on_cpu. The addr+idxmap parameters are stored in a + * TLBFlushPageByMMUIdxData structure that has been allocated + * specifically for this helper. Free the structure when done. + */ +static void tlb_flush_page_by_mmuidx_async_2(CPUState *cpu, run_on_cpu_data data) { + TLBFlushPageByMMUIdxData *d = data.host_ptr; + + tlb_flush_page_by_mmuidx_async_0(cpu, d->addr, d->idxmap); + g_free(d); +} + +void tlb_flush_page_by_mmuidx(CPUState *cpu, vaddr addr, MMUIdxMap idxmap) { + tlb_debug("addr: %016" VADDR_PRIx " mmu_idx:%" PRIx16 "\n", addr, idxmap); + + assert_cpu_is_self(cpu); + + /* This should already be page aligned */ + addr &= TARGET_PAGE_MASK; + + tlb_flush_page_by_mmuidx_async_0(cpu, addr, idxmap); +} + +void tlb_flush_page(CPUState *cpu, vaddr addr) { + tlb_flush_page_by_mmuidx(cpu, addr, ALL_MMUIDX_BITS); +} + +void tlb_flush_page_by_mmuidx_all_cpus_synced(CPUState *src_cpu, vaddr addr, MMUIdxMap idxmap) { + tlb_debug("addr: %016" VADDR_PRIx " mmu_idx:%" PRIx16 "\n", addr, idxmap); + + /* This should already be page aligned */ + addr &= TARGET_PAGE_MASK; + + /* + * Allocate memory to hold addr+idxmap only when needed. + * See tlb_flush_page_by_mmuidx for details. + */ + if (idxmap < TARGET_PAGE_SIZE) { + flush_all_helper(src_cpu, tlb_flush_page_by_mmuidx_async_1, RUN_ON_CPU_TARGET_PTR(addr | idxmap)); + async_safe_run_on_cpu(src_cpu, tlb_flush_page_by_mmuidx_async_1, RUN_ON_CPU_TARGET_PTR(addr | idxmap)); + } else { + CPUState *dst_cpu; + TLBFlushPageByMMUIdxData *d; + + /* Allocate a separate data block for each destination cpu. */ + CPU_FOREACH(dst_cpu) { + if (dst_cpu != src_cpu) { + d = g_new(TLBFlushPageByMMUIdxData, 1); + d->addr = addr; + d->idxmap = idxmap; + async_run_on_cpu(dst_cpu, tlb_flush_page_by_mmuidx_async_2, RUN_ON_CPU_HOST_PTR(d)); + } + } + + d = g_new(TLBFlushPageByMMUIdxData, 1); + d->addr = addr; + d->idxmap = idxmap; + async_safe_run_on_cpu(src_cpu, tlb_flush_page_by_mmuidx_async_2, RUN_ON_CPU_HOST_PTR(d)); + } +} + +void tlb_flush_page_all_cpus_synced(CPUState *src, vaddr addr) { + tlb_flush_page_by_mmuidx_all_cpus_synced(src, addr, ALL_MMUIDX_BITS); +} + +static void tlb_flush_range_locked(CPUState *cpu, int midx, vaddr addr, vaddr len, unsigned bits) { + CPUTLBDesc *d = &cpu->neg.tlb.d[midx]; + CPUTLBDescFast *f = cpu_tlb_fast(cpu, midx); + vaddr mask = MAKE_64BIT_MASK(0, bits); + + /* + * If @bits is smaller than the tlb size, there may be multiple entries + * within the TLB; otherwise all addresses that match under @mask hit + * the same TLB entry. + * TODO: Perhaps allow bits to be a few bits less than the size. + * For now, just flush the entire TLB. + * + * If @len is larger than the tlb size, then it will take longer to + * test all of the entries in the TLB than it will to flush it all. + */ + if (mask < f->mask || len > f->mask) { + tlb_debug("forcing full flush midx %d (" + "%016" VADDR_PRIx "/%016" VADDR_PRIx "+%016" VADDR_PRIx ")\n", + midx, addr, mask, len); + tlb_flush_one_mmuidx_locked(cpu, midx, get_clock_realtime()); + return; + } + + /* + * Check if we need to flush due to large pages. + * Because large_page_mask contains all 1's from the msb, + * we only need to test the end of the range. + */ + if (((addr + len - 1) & d->large_page_mask) == d->large_page_addr) { + tlb_debug("forcing full flush midx %d (" + "%016" VADDR_PRIx "/%016" VADDR_PRIx ")\n", + midx, d->large_page_addr, d->large_page_mask); + tlb_flush_one_mmuidx_locked(cpu, midx, get_clock_realtime()); + return; + } + + for (vaddr i = 0; i < len; i += TARGET_PAGE_SIZE) { + vaddr page = addr + i; + CPUTLBEntry *entry = tlb_entry(cpu, midx, page); + + if (tlb_flush_entry_mask_locked(entry, page, mask)) { + tlb_n_used_entries_dec(cpu, midx); + } + tlb_flush_vtlb_page_mask_locked(cpu, midx, page, mask); + } +} + +typedef struct { + vaddr addr; + vaddr len; + MMUIdxMap idxmap; + unsigned bits; +} TLBFlushRangeData; + +static void tlb_flush_range_by_mmuidx_async_0(CPUState *cpu, TLBFlushRangeData d) { + int mmu_idx; + + assert_cpu_is_self(cpu); + + tlb_debug("range: %016" VADDR_PRIx "/%u+%016" VADDR_PRIx " mmu_map:0x%x\n", d.addr, d.bits, d.len, d.idxmap); + + qemu_spin_lock(&cpu->neg.tlb.c.lock); + for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { + if ((d.idxmap >> mmu_idx) & 1) { + tlb_flush_range_locked(cpu, mmu_idx, d.addr, d.len, d.bits); + } + } + qemu_spin_unlock(&cpu->neg.tlb.c.lock); + + /* + * If the length is larger than the jump cache size, then it will take + * longer to clear each entry individually than it will to clear it all. + */ + if (d.len >= (TARGET_PAGE_SIZE * TB_JMP_CACHE_SIZE)) { + tcg_flush_jmp_cache(cpu); + return; + } + + /* + * Discard jump cache entries for any tb which might potentially + * overlap the flushed pages, which includes the previous. + */ + d.addr -= TARGET_PAGE_SIZE; + for (vaddr i = 0, n = d.len / TARGET_PAGE_SIZE + 1; i < n; i++) { + tb_jmp_cache_clear_page(cpu, d.addr); + d.addr += TARGET_PAGE_SIZE; + } +} + +static void tlb_flush_range_by_mmuidx_async_1(CPUState *cpu, run_on_cpu_data data) { + TLBFlushRangeData *d = data.host_ptr; + tlb_flush_range_by_mmuidx_async_0(cpu, *d); + g_free(d); +} + +void tlb_flush_range_by_mmuidx(CPUState *cpu, vaddr addr, vaddr len, MMUIdxMap idxmap, unsigned bits) { + TLBFlushRangeData d; + + assert_cpu_is_self(cpu); + + /* If no page bits are significant, this devolves to tlb_flush. */ + if (bits < TARGET_PAGE_BITS) { + tlb_flush_by_mmuidx(cpu, idxmap); + return; + } + /* + * If all bits are significant, and len is small, + * this devolves to tlb_flush_page. + */ + if (len <= TARGET_PAGE_SIZE && bits >= target_long_bits()) { + tlb_flush_page_by_mmuidx(cpu, addr, idxmap); + return; + } + + /* This should already be page aligned */ + d.addr = addr & TARGET_PAGE_MASK; + d.len = len; + d.idxmap = idxmap; + d.bits = bits; + + tlb_flush_range_by_mmuidx_async_0(cpu, d); +} + +void tlb_flush_page_bits_by_mmuidx(CPUState *cpu, vaddr addr, MMUIdxMap idxmap, unsigned bits) { + tlb_flush_range_by_mmuidx(cpu, addr, TARGET_PAGE_SIZE, idxmap, bits); +} + +void tlb_flush_range_by_mmuidx_all_cpus_synced(CPUState *src_cpu, vaddr addr, vaddr len, MMUIdxMap idxmap, + unsigned bits) { + TLBFlushRangeData d, *p; + CPUState *dst_cpu; + + /* If no page bits are significant, this devolves to tlb_flush. */ + if (bits < TARGET_PAGE_BITS) { + tlb_flush_by_mmuidx_all_cpus_synced(src_cpu, idxmap); + return; + } + /* + * If all bits are significant, and len is small, + * this devolves to tlb_flush_page. + */ + if (len <= TARGET_PAGE_SIZE && bits >= target_long_bits()) { + tlb_flush_page_by_mmuidx_all_cpus_synced(src_cpu, addr, idxmap); + return; + } + + /* This should already be page aligned */ + d.addr = addr & TARGET_PAGE_MASK; + d.len = len; + d.idxmap = idxmap; + d.bits = bits; + + /* Allocate a separate data block for each destination cpu. */ + CPU_FOREACH(dst_cpu) { + if (dst_cpu != src_cpu) { + p = g_memdup(&d, sizeof(d)); + async_run_on_cpu(dst_cpu, tlb_flush_range_by_mmuidx_async_1, RUN_ON_CPU_HOST_PTR(p)); + } + } + + p = g_memdup(&d, sizeof(d)); + async_safe_run_on_cpu(src_cpu, tlb_flush_range_by_mmuidx_async_1, RUN_ON_CPU_HOST_PTR(p)); +} + +void tlb_flush_page_bits_by_mmuidx_all_cpus_synced(CPUState *src_cpu, vaddr addr, MMUIdxMap idxmap, unsigned bits) { + tlb_flush_range_by_mmuidx_all_cpus_synced(src_cpu, addr, TARGET_PAGE_SIZE, idxmap, bits); +} + +/* update the TLBs so that writes to code in the virtual page 'addr' + can be detected */ +void tlb_protect_code(ram_addr_t ram_addr) { + physical_memory_test_and_clear_dirty(ram_addr & TARGET_PAGE_MASK, TARGET_PAGE_SIZE, DIRTY_MEMORY_CODE, NULL); +} + +/* update the TLB so that writes in physical page 'phys_addr' are no longer + tested for self modifying code */ +void tlb_unprotect_code(ram_addr_t ram_addr) { + physical_memory_set_dirty_flag(ram_addr, DIRTY_MEMORY_CODE); +} + +/* + * Dirty write flag handling + * + * When the TCG code writes to a location it looks up the address in + * the TLB and uses that data to compute the final address. If any of + * the lower bits of the address are set then the slow path is forced. + * There are a number of reasons to do this but for normal RAM the + * most usual is detecting writes to code regions which may invalidate + * generated code. + * + * Other vCPUs might be reading their TLBs during guest execution, so we update + * te->addr_write with qatomic_set. We don't need to worry about this for + * oversized guests as MTTCG is disabled for them. + * + * Called with tlb_c.lock held. + */ +static void tlb_reset_dirty_range_locked(CPUTLBEntryFull *full, CPUTLBEntry *ent, uintptr_t start, uintptr_t length) { + const uintptr_t addr = ent->addr_write; + int flags = addr | full->slow_flags[MMU_DATA_STORE]; + + flags &= TLB_INVALID_MASK | TLB_MMIO | TLB_DISCARD_WRITE | TLB_NOTDIRTY; + if (flags == 0) { + uintptr_t host = (addr & TARGET_PAGE_MASK) + ent->addend; + if ((host - start) < length) { + qatomic_set(&ent->addr_write, addr | TLB_NOTDIRTY); + } + } +} + +/* + * Called with tlb_c.lock held. + * Called only from the vCPU context, i.e. the TLB's owner thread. + */ +static inline void copy_tlb_helper_locked(CPUTLBEntry *d, const CPUTLBEntry *s) { + *d = *s; +} + +/* This is a cross vCPU call (i.e. another vCPU resetting the flags of + * the target vCPU). + * We must take tlb_c.lock to avoid racing with another vCPU update. The only + * thing actually updated is the target TLB entry ->addr_write flags. + */ +void tlb_reset_dirty(CPUState *cpu, uintptr_t start, uintptr_t length) { + int mmu_idx; + + qemu_spin_lock(&cpu->neg.tlb.c.lock); + for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { + CPUTLBDesc *desc = &cpu->neg.tlb.d[mmu_idx]; + CPUTLBDescFast *fast = cpu_tlb_fast(cpu, mmu_idx); + unsigned int n = tlb_n_entries(fast); + unsigned int i; + + for (i = 0; i < n; i++) { + tlb_reset_dirty_range_locked(&desc->fulltlb[i], &fast->table[i], start, length); + } + + for (i = 0; i < CPU_VTLB_SIZE; i++) { + tlb_reset_dirty_range_locked(&desc->vfulltlb[i], &desc->vtable[i], start, length); + } + } + qemu_spin_unlock(&cpu->neg.tlb.c.lock); +} + +/* Called with tlb_c.lock held */ +static inline void tlb_set_dirty1_locked(CPUTLBEntry *tlb_entry, vaddr addr) { + if (tlb_entry->addr_write == (addr | TLB_NOTDIRTY)) { + tlb_entry->addr_write = addr; + } +} + +/* update the TLB corresponding to virtual page vaddr + so that it is no longer dirty */ +static void tlb_set_dirty(CPUState *cpu, vaddr addr) { + int mmu_idx; + + assert_cpu_is_self(cpu); + + addr &= TARGET_PAGE_MASK; + qemu_spin_lock(&cpu->neg.tlb.c.lock); + for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { + tlb_set_dirty1_locked(tlb_entry(cpu, mmu_idx, addr), addr); + } + + for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { + int k; + for (k = 0; k < CPU_VTLB_SIZE; k++) { + tlb_set_dirty1_locked(&cpu->neg.tlb.d[mmu_idx].vtable[k], addr); + } + } + qemu_spin_unlock(&cpu->neg.tlb.c.lock); +} + +/* Our TLB does not support large pages, so remember the area covered by + large pages and trigger a full TLB flush if these are invalidated. */ +static void tlb_add_large_page(CPUState *cpu, int mmu_idx, vaddr addr, uint64_t size) { + vaddr lp_addr = cpu->neg.tlb.d[mmu_idx].large_page_addr; + vaddr lp_mask = ~(size - 1); + + if (lp_addr == (vaddr) -1) { + /* No previous large page. */ + lp_addr = addr; + } else { + /* Extend the existing region to include the new page. + This is a compromise between unnecessary flushes and + the cost of maintaining a full variable size TLB. */ + lp_mask &= cpu->neg.tlb.d[mmu_idx].large_page_mask; + while (((lp_addr ^ addr) & lp_mask) != 0) { + lp_mask <<= 1; + } + } + cpu->neg.tlb.d[mmu_idx].large_page_addr = lp_addr & lp_mask; + cpu->neg.tlb.d[mmu_idx].large_page_mask = lp_mask; +} + +static inline void tlb_set_compare(CPUTLBEntryFull *full, CPUTLBEntry *ent, vaddr address, int flags, + MMUAccessType access_type, bool enable) { + if (enable) { + address |= flags & TLB_FLAGS_MASK; + flags &= TLB_SLOW_FLAGS_MASK; + if (flags) { + address |= TLB_FORCE_SLOW; + } + } else { + address = -1; + flags = 0; + } + ent->addr_idx[access_type] = address; + full->slow_flags[access_type] = flags; +} + +/* + * Add a new TLB entry. At most one entry for a given virtual address + * is permitted. Only a single TARGET_PAGE_SIZE region is mapped, the + * supplied size is only used by tlb_flush_page. + * + * Called from TCG-generated code, which is under an RCU read-side + * critical section. + */ +void tlb_set_page_full(CPUState *cpu, int mmu_idx, vaddr addr, CPUTLBEntryFull *full) { + CPUTLB *tlb = &cpu->neg.tlb; + CPUTLBDesc *desc = &tlb->d[mmu_idx]; + MemoryRegionSection *section; + unsigned int index, read_flags, write_flags; + uintptr_t addend; + CPUTLBEntry *te, tn; + hwaddr iotlb, xlat, sz, paddr_page; + vaddr addr_page; + int asidx, wp_flags, prot; + bool is_ram, is_romd; + + assert_cpu_is_self(cpu); + + if (full->lg_page_size <= TARGET_PAGE_BITS) { + sz = TARGET_PAGE_SIZE; + } else { + sz = (hwaddr) 1 << full->lg_page_size; + tlb_add_large_page(cpu, mmu_idx, addr, sz); + } + addr_page = addr & TARGET_PAGE_MASK; + paddr_page = full->phys_addr & TARGET_PAGE_MASK; + + prot = full->prot; + asidx = cpu_asidx_from_attrs(cpu, full->attrs); + section = address_space_translate_for_iotlb(cpu, asidx, paddr_page, &xlat, &sz, full->attrs, &prot); + assert(sz >= TARGET_PAGE_SIZE); + + tlb_debug("vaddr=%016" VADDR_PRIx " paddr=0x" HWADDR_FMT_plx " prot=%x idx=%d\n", addr, full->phys_addr, prot, + mmu_idx); + + read_flags = full->tlb_fill_flags; + if (full->lg_page_size < TARGET_PAGE_BITS) { + /* Repeat the MMU check and TLB fill on every access. */ + read_flags |= TLB_INVALID_MASK; + } + + is_ram = memory_region_is_ram(section->mr); + is_romd = memory_region_is_romd(section->mr); + + if (is_ram || is_romd) { + /* RAM and ROMD both have associated host memory. */ + addend = (uintptr_t) memory_region_get_ram_ptr(section->mr) + xlat; + } else { + /* I/O does not; force the host address to NULL. */ + addend = 0; + } + + write_flags = read_flags; + if (is_ram) { + iotlb = memory_region_get_ram_addr(section->mr) + xlat; + assert(!(iotlb & ~TARGET_PAGE_MASK)); + /* + * Computing is_clean is expensive; avoid all that unless + * the page is actually writable. + */ + if (prot & PAGE_WRITE) { + if (section->readonly) { + write_flags |= TLB_DISCARD_WRITE; + } else if (physical_memory_is_clean(iotlb)) { + write_flags |= TLB_NOTDIRTY; + } + } + } else { + /* I/O or ROMD */ + iotlb = xlat; + /* + * Writes to romd devices must go through MMIO to enable write. + * Reads to romd devices go through the ram_ptr found above, + * but of course reads to I/O must go through MMIO. + */ + write_flags |= TLB_MMIO; + if (!is_romd) { + read_flags = write_flags; + } + } + + wp_flags = cpu_watchpoint_address_matches(cpu, addr_page, TARGET_PAGE_SIZE); + + index = tlb_index(cpu, mmu_idx, addr_page); + te = tlb_entry(cpu, mmu_idx, addr_page); + + /* + * Hold the TLB lock for the rest of the function. We could acquire/release + * the lock several times in the function, but it is faster to amortize the + * acquisition cost by acquiring it just once. Note that this leads to + * a longer critical section, but this is not a concern since the TLB lock + * is unlikely to be contended. + */ + qemu_spin_lock(&tlb->c.lock); + + /* Note that the tlb is no longer clean. */ + tlb->c.dirty |= 1 << mmu_idx; + + /* Make sure there's no cached translation for the new page. */ + tlb_flush_vtlb_page_locked(cpu, mmu_idx, addr_page); + + /* + * Only evict the old entry to the victim tlb if it's for a + * different page; otherwise just overwrite the stale data. + */ + if (!tlb_hit_page_anyprot(te, addr_page) && !tlb_entry_is_empty(te)) { + unsigned vidx = desc->vindex++ % CPU_VTLB_SIZE; + CPUTLBEntry *tv = &desc->vtable[vidx]; + + /* Evict the old entry into the victim tlb. */ + copy_tlb_helper_locked(tv, te); + desc->vfulltlb[vidx] = desc->fulltlb[index]; + tlb_n_used_entries_dec(cpu, mmu_idx); + } + + /* refill the tlb */ + /* + * When memory region is ram, iotlb contains a TARGET_PAGE_BITS + * aligned ram_addr_t of the page base of the target RAM. + * Otherwise, iotlb contains a TARGET_PAGE_BITS aligned + * offset within section->mr of the page base (I/O, ROMD) + * + * We subtract addr_page (which is page aligned and thus won't + * disturb the low bits) to give an offset which can be added to the + * (non-page-aligned) vaddr of the eventual memory access to get + * the MemoryRegion offset for the access. Note that the vaddr we + * subtract here is that of the page base, and not the same as the + * vaddr we add back in io_prepare()/get_page_addr_code(). + */ + desc->fulltlb[index] = *full; + full = &desc->fulltlb[index]; + full->xlat_offset = iotlb - addr_page; + full->section = section; + full->phys_addr = paddr_page; + + /* Now calculate the new entry */ + tn.addend = addend - addr_page; + + tlb_set_compare(full, &tn, addr_page, read_flags, MMU_INST_FETCH, prot & PAGE_EXEC); + + if (wp_flags & BP_MEM_READ) { + read_flags |= TLB_WATCHPOINT; + } + tlb_set_compare(full, &tn, addr_page, read_flags, MMU_DATA_LOAD, prot & PAGE_READ); + + if (prot & PAGE_WRITE_INV) { + write_flags |= TLB_INVALID_MASK; + } + if (wp_flags & BP_MEM_WRITE) { + write_flags |= TLB_WATCHPOINT; + } + tlb_set_compare(full, &tn, addr_page, write_flags, MMU_DATA_STORE, prot & PAGE_WRITE); + + copy_tlb_helper_locked(te, &tn); + tlb_n_used_entries_inc(cpu, mmu_idx); + qemu_spin_unlock(&tlb->c.lock); +} + +void tlb_set_page_with_attrs(CPUState *cpu, vaddr addr, hwaddr paddr, MemTxAttrs attrs, int prot, int mmu_idx, + vaddr size) { + CPUTLBEntryFull full = {.phys_addr = paddr, .attrs = attrs, .prot = prot, .lg_page_size = ctz64(size)}; + + assert(is_power_of_2(size)); + tlb_set_page_full(cpu, mmu_idx, addr, &full); +} + +void tlb_set_page(CPUState *cpu, vaddr addr, hwaddr paddr, int prot, int mmu_idx, vaddr size) { + tlb_set_page_with_attrs(cpu, addr, paddr, MEMTXATTRS_UNSPECIFIED, prot, mmu_idx, size); +} + +/** + * tlb_hit_page: return true if page aligned @addr is a hit against the + * TLB entry @tlb_addr + * + * @addr: virtual address to test (must be page aligned) + * @tlb_addr: TLB entry address (a CPUTLBEntry addr_read/write/code value) + */ +static inline bool tlb_hit_page(uint64_t tlb_addr, vaddr addr) { + return addr == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK)); +} + +/** + * tlb_hit: return true if @addr is a hit against the TLB entry @tlb_addr + * + * @addr: virtual address to test (need not be page aligned) + * @tlb_addr: TLB entry address (a CPUTLBEntry addr_read/write/code value) + */ +static inline bool tlb_hit(uint64_t tlb_addr, vaddr addr) { + return tlb_hit_page(tlb_addr, addr & TARGET_PAGE_MASK); +} + +/* + * Note: tlb_fill_align() can trigger a resize of the TLB. + * This means that all of the caller's prior references to the TLB table + * (e.g. CPUTLBEntry pointers) must be discarded and looked up again + * (e.g. via tlb_entry()). + */ +static bool tlb_fill_align(CPUState *cpu, vaddr addr, MMUAccessType type, int mmu_idx, MemOp memop, int size, + bool probe, uintptr_t ra) { + const TCGCPUOps *ops = cpu->cc->tcg_ops; + CPUTLBEntryFull full; + + if (ops->tlb_fill_align) { + if (ops->tlb_fill_align(cpu, &full, addr, type, mmu_idx, memop, size, probe, ra)) { + tlb_set_page_full(cpu, mmu_idx, addr, &full); + return true; + } + } else { + /* Legacy behaviour is alignment before paging. */ + if (addr & ((1u << memop_alignment_bits(memop)) - 1)) { + ops->do_unaligned_access(cpu, addr, type, mmu_idx, ra); + } + if (ops->tlb_fill(cpu, addr, size, type, mmu_idx, probe, ra)) { + return true; + } + } + assert(probe); + return false; +} + +static inline void cpu_unaligned_access(CPUState *cpu, vaddr addr, MMUAccessType access_type, int mmu_idx, + uintptr_t retaddr) { + cpu->cc->tcg_ops->do_unaligned_access(cpu, addr, access_type, mmu_idx, retaddr); +} + +static MemoryRegionSection *io_prepare(hwaddr *out_offset, CPUState *cpu, CPUTLBEntryFull *full, vaddr addr, + uintptr_t retaddr) { + MemoryRegionSection *section; + hwaddr mr_offset; + + section = full->section; + mr_offset = full->xlat_offset + addr; + cpu->mem_io_pc = retaddr; + if (!cpu->neg.can_do_io) { + cpu_io_recompile(cpu, retaddr); + } + + *out_offset = mr_offset; + return section; +} + +static void io_failed(CPUState *cpu, CPUTLBEntryFull *full, vaddr addr, unsigned size, MMUAccessType access_type, + int mmu_idx, MemTxResult response, uintptr_t retaddr) { + if (!cpu->ignore_memory_transaction_failures && cpu->cc->tcg_ops->do_transaction_failed) { + hwaddr physaddr = full->phys_addr | (addr & ~TARGET_PAGE_MASK); + + cpu->cc->tcg_ops->do_transaction_failed(cpu, physaddr, addr, size, access_type, mmu_idx, full->attrs, response, + retaddr); + } +} + +/* Return true if ADDR is present in the victim tlb, and has been copied + back to the main tlb. */ +static bool victim_tlb_hit(CPUState *cpu, size_t mmu_idx, size_t index, MMUAccessType access_type, vaddr page) { + size_t vidx; + + assert_cpu_is_self(cpu); + for (vidx = 0; vidx < CPU_VTLB_SIZE; ++vidx) { + CPUTLBEntry *vtlb = &cpu->neg.tlb.d[mmu_idx].vtable[vidx]; + uint64_t cmp = tlb_read_idx(vtlb, access_type); + + if (cmp == page) { + /* Found entry in victim tlb, swap tlb and iotlb. */ + CPUTLBEntry tmptlb, *tlb = &cpu_tlb_fast(cpu, mmu_idx)->table[index]; + + qemu_spin_lock(&cpu->neg.tlb.c.lock); + copy_tlb_helper_locked(&tmptlb, tlb); + copy_tlb_helper_locked(tlb, vtlb); + copy_tlb_helper_locked(vtlb, &tmptlb); + qemu_spin_unlock(&cpu->neg.tlb.c.lock); + + CPUTLBEntryFull *f1 = &cpu->neg.tlb.d[mmu_idx].fulltlb[index]; + CPUTLBEntryFull *f2 = &cpu->neg.tlb.d[mmu_idx].vfulltlb[vidx]; + CPUTLBEntryFull tmpf; + tmpf = *f1; + *f1 = *f2; + *f2 = tmpf; + return true; + } + } + return false; +} + +static void notdirty_write(CPUState *cpu, vaddr mem_vaddr, unsigned size, CPUTLBEntryFull *full, uintptr_t retaddr) { + ram_addr_t ram_addr = mem_vaddr + full->xlat_offset; + + trace_memory_notdirty_write_access(mem_vaddr, ram_addr, size); + + if (!physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) { + tb_invalidate_phys_range_fast(cpu, ram_addr, size, retaddr); + } + + /* + * Set both VGA and migration bits for simplicity and to remove + * the notdirty callback faster. + */ + physical_memory_set_dirty_range(ram_addr, size, DIRTY_CLIENTS_NOCODE); + + /* We remove the notdirty callback only if the code has been flushed. */ + if (!physical_memory_is_clean(ram_addr)) { + trace_memory_notdirty_set_dirty(mem_vaddr); + tlb_set_dirty(cpu, mem_vaddr); + } +} + +static int probe_access_internal(CPUState *cpu, vaddr addr, int fault_size, MMUAccessType access_type, int mmu_idx, + bool nonfault, void **phost, CPUTLBEntryFull **pfull, uintptr_t retaddr, + bool check_mem_cbs) { + uintptr_t index = tlb_index(cpu, mmu_idx, addr); + CPUTLBEntry *entry = tlb_entry(cpu, mmu_idx, addr); + uint64_t tlb_addr = tlb_read_idx(entry, access_type); + vaddr page_addr = addr & TARGET_PAGE_MASK; + int flags = TLB_FLAGS_MASK & ~TLB_FORCE_SLOW; + bool force_mmio = check_mem_cbs && cpu_plugin_mem_cbs_enabled(cpu); + CPUTLBEntryFull *full; + + if (!tlb_hit_page(tlb_addr, page_addr)) { + if (!victim_tlb_hit(cpu, mmu_idx, index, access_type, page_addr)) { + if (!tlb_fill_align(cpu, addr, access_type, mmu_idx, 0, fault_size, nonfault, retaddr)) { + /* Non-faulting page table read failed. */ + *phost = NULL; + *pfull = NULL; + return TLB_INVALID_MASK; + } + + /* TLB resize via tlb_fill_align may have moved the entry. */ + index = tlb_index(cpu, mmu_idx, addr); + entry = tlb_entry(cpu, mmu_idx, addr); + + /* + * With PAGE_WRITE_INV, we set TLB_INVALID_MASK immediately, + * to force the next access through tlb_fill_align. We've just + * called tlb_fill_align, so we know that this entry *is* valid. + */ + flags &= ~TLB_INVALID_MASK; + } + tlb_addr = tlb_read_idx(entry, access_type); + } + flags &= tlb_addr; + + *pfull = full = &cpu->neg.tlb.d[mmu_idx].fulltlb[index]; + flags |= full->slow_flags[access_type]; + + /* Fold all "mmio-like" bits into TLB_MMIO. This is not RAM. */ + if (unlikely(flags & ~(TLB_WATCHPOINT | TLB_NOTDIRTY | TLB_CHECK_ALIGNED)) || + (access_type != MMU_INST_FETCH && force_mmio)) { + *phost = NULL; + return TLB_MMIO; + } + + /* Everything else is RAM. */ + *phost = (void *) ((uintptr_t) addr + entry->addend); + return flags; +} + +int probe_access_full(CPUArchState *env, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, bool nonfault, + void **phost, CPUTLBEntryFull **pfull, uintptr_t retaddr) { + int flags = + probe_access_internal(env_cpu(env), addr, size, access_type, mmu_idx, nonfault, phost, pfull, retaddr, true); + + /* Handle clean RAM pages. */ + if (unlikely(flags & TLB_NOTDIRTY)) { + int dirtysize = size == 0 ? 1 : size; + notdirty_write(env_cpu(env), addr, dirtysize, *pfull, retaddr); + flags &= ~TLB_NOTDIRTY; + } + + return flags; +} + +int probe_access_full_mmu(CPUArchState *env, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, void **phost, + CPUTLBEntryFull **pfull) { + void *discard_phost; + CPUTLBEntryFull *discard_tlb; + + /* privately handle users that don't need full results */ + phost = phost ? phost : &discard_phost; + pfull = pfull ? pfull : &discard_tlb; + + int flags = probe_access_internal(env_cpu(env), addr, size, access_type, mmu_idx, true, phost, pfull, 0, false); + + /* Handle clean RAM pages. */ + if (unlikely(flags & TLB_NOTDIRTY)) { + int dirtysize = size == 0 ? 1 : size; + notdirty_write(env_cpu(env), addr, dirtysize, *pfull, 0); + flags &= ~TLB_NOTDIRTY; + } + + return flags; +} + +int probe_access_flags(CPUArchState *env, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, bool nonfault, + void **phost, uintptr_t retaddr) { + CPUTLBEntryFull *full; + int flags; + + g_assert(-(addr | TARGET_PAGE_MASK) >= size); + + flags = + probe_access_internal(env_cpu(env), addr, size, access_type, mmu_idx, nonfault, phost, &full, retaddr, true); + + /* Handle clean RAM pages. */ + if (unlikely(flags & TLB_NOTDIRTY)) { + int dirtysize = size == 0 ? 1 : size; + notdirty_write(env_cpu(env), addr, dirtysize, full, retaddr); + flags &= ~TLB_NOTDIRTY; + } + + return flags; +} + +void *probe_access(CPUArchState *env, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, uintptr_t retaddr) { + CPUTLBEntryFull *full; + void *host; + int flags; + + g_assert(-(addr | TARGET_PAGE_MASK) >= size); + + flags = probe_access_internal(env_cpu(env), addr, size, access_type, mmu_idx, false, &host, &full, retaddr, true); + + /* Per the interface, size == 0 merely faults the access. */ + if (size == 0) { + return NULL; + } + + if (unlikely(flags & (TLB_NOTDIRTY | TLB_WATCHPOINT))) { + /* Handle watchpoints. */ + if (flags & TLB_WATCHPOINT) { + int wp_access = (access_type == MMU_DATA_STORE ? BP_MEM_WRITE : BP_MEM_READ); + cpu_check_watchpoint(env_cpu(env), addr, size, full->attrs, wp_access, retaddr); + } + + /* Handle clean RAM pages. */ + if (flags & TLB_NOTDIRTY) { + notdirty_write(env_cpu(env), addr, size, full, retaddr); + } + } + + return host; +} + +void *tlb_vaddr_to_host(CPUArchState *env, vaddr addr, MMUAccessType access_type, int mmu_idx) { + CPUTLBEntryFull *full; + void *host; + int flags; + + flags = probe_access_internal(env_cpu(env), addr, 0, access_type, mmu_idx, true, &host, &full, 0, false); + + /* No combination of flags are expected by the caller. */ + return flags ? NULL : host; +} + +/* + * Return a ram_addr_t for the virtual address for execution. + * + * Return -1 if we can't translate and execute from an entire page + * of RAM. This will force us to execute by loading and translating + * one insn at a time, without caching. + * + * NOTE: This function will trigger an exception if the page is + * not executable. + */ +tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr, void **hostp) { + CPUTLBEntryFull *full; + void *p; + + (void) probe_access_internal(env_cpu(env), addr, 1, MMU_INST_FETCH, cpu_mmu_index(env_cpu(env), true), false, hostp, + &full, 0, false); + + p = *hostp; + if (p == NULL) { + return -1; + } + + if (full->lg_page_size < TARGET_PAGE_BITS) { + *hostp = NULL; + return -1; + } + + return qemu_ram_addr_from_host_nofail(p); +} + +/* Load/store with atomicity primitives. */ +#include "ldst_atomicity.c.inc" + +#ifdef CONFIG_PLUGIN +/* + * Perform a TLB lookup and populate the qemu_plugin_hwaddr structure. + * This should be a hot path as we will have just looked this path up + * in the softmmu lookup code (or helper). We don't handle re-fills or + * checking the victim table. This is purely informational. + * + * The one corner case is i/o write, which can cause changes to the + * address space. Those changes, and the corresponding tlb flush, + * should be delayed until the next TB, so even then this ought not fail. + * But check, Just in Case. + */ +bool tlb_plugin_lookup(CPUState *cpu, vaddr addr, int mmu_idx, bool is_store, struct qemu_plugin_hwaddr *data) { + CPUTLBEntry *tlbe = tlb_entry(cpu, mmu_idx, addr); + uintptr_t index = tlb_index(cpu, mmu_idx, addr); + MMUAccessType access_type = is_store ? MMU_DATA_STORE : MMU_DATA_LOAD; + uint64_t tlb_addr = tlb_read_idx(tlbe, access_type); + CPUTLBEntryFull *full; + + if (unlikely(!tlb_hit(tlb_addr, addr))) { + return false; + } + + full = &cpu->neg.tlb.d[mmu_idx].fulltlb[index]; + data->phys_addr = full->phys_addr | (addr & ~TARGET_PAGE_MASK); + + /* We must have an iotlb entry for MMIO */ + if (tlb_addr & TLB_MMIO) { + MemoryRegionSection *section = full->section; + data->is_io = true; + data->mr = section->mr; + } else { + data->is_io = false; + data->mr = NULL; + } + return true; +} +#endif + +/* + * Probe for a load/store operation. + * Return the host address and into @flags. + */ + +typedef struct MMULookupPageData { + CPUTLBEntryFull *full; + void *haddr; + vaddr addr; + int flags; + int size; +} MMULookupPageData; + +typedef struct MMULookupLocals { + MMULookupPageData page[2]; + MemOp memop; + int mmu_idx; +} MMULookupLocals; + +/** + * mmu_lookup1: translate one page + * @cpu: generic cpu state + * @data: lookup parameters + * @memop: memory operation for the access, or 0 + * @mmu_idx: virtual address context + * @access_type: load/store/code + * @ra: return address into tcg generated code, or 0 + * + * Resolve the translation for the one page at @data.addr, filling in + * the rest of @data with the results. If the translation fails, + * tlb_fill_align will longjmp out. Return true if the softmmu tlb for + * @mmu_idx may have resized. + */ +static bool mmu_lookup1(CPUState *cpu, MMULookupPageData *data, MemOp memop, int mmu_idx, MMUAccessType access_type, + uintptr_t ra) { + vaddr addr = data->addr; + uintptr_t index = tlb_index(cpu, mmu_idx, addr); + CPUTLBEntry *entry = tlb_entry(cpu, mmu_idx, addr); + uint64_t tlb_addr = tlb_read_idx(entry, access_type); + bool maybe_resized = false; + CPUTLBEntryFull *full; + int flags; + + /* If the TLB entry is for a different page, reload and try again. */ + if (!tlb_hit(tlb_addr, addr)) { + if (!victim_tlb_hit(cpu, mmu_idx, index, access_type, addr & TARGET_PAGE_MASK)) { + tlb_fill_align(cpu, addr, access_type, mmu_idx, memop, data->size, false, ra); + maybe_resized = true; + index = tlb_index(cpu, mmu_idx, addr); + entry = tlb_entry(cpu, mmu_idx, addr); + } + tlb_addr = tlb_read_idx(entry, access_type) & ~TLB_INVALID_MASK; + } + + full = &cpu->neg.tlb.d[mmu_idx].fulltlb[index]; + flags = tlb_addr & (TLB_FLAGS_MASK & ~TLB_FORCE_SLOW); + flags |= full->slow_flags[access_type]; + + if (likely(!maybe_resized)) { + /* Alignment has not been checked by tlb_fill_align. */ + int a_bits = memop_tlb_alignment_bits(memop, flags & TLB_CHECK_ALIGNED); + if (unlikely(addr & ((1 << a_bits) - 1))) { + cpu_unaligned_access(cpu, addr, access_type, mmu_idx, ra); + } + } + + data->full = full; + data->flags = flags; + /* Compute haddr speculatively; depending on flags it might be invalid. */ + data->haddr = (void *) ((uintptr_t) addr + entry->addend); + + return maybe_resized; +} + +/** + * mmu_watch_or_dirty + * @cpu: generic cpu state + * @data: lookup parameters + * @access_type: load/store/code + * @ra: return address into tcg generated code, or 0 + * + * Trigger watchpoints for @data.addr:@data.size; + * record writes to protected clean pages. + */ +static void mmu_watch_or_dirty(CPUState *cpu, MMULookupPageData *data, MMUAccessType access_type, uintptr_t ra) { + CPUTLBEntryFull *full = data->full; + vaddr addr = data->addr; + int flags = data->flags; + int size = data->size; + + /* On watchpoint hit, this will longjmp out. */ + if (flags & TLB_WATCHPOINT) { + int wp = access_type == MMU_DATA_STORE ? BP_MEM_WRITE : BP_MEM_READ; + cpu_check_watchpoint(cpu, addr, size, full->attrs, wp, ra); + flags &= ~TLB_WATCHPOINT; + } + + /* Note that notdirty is only set for writes. */ + if (flags & TLB_NOTDIRTY) { + notdirty_write(cpu, addr, size, full, ra); + flags &= ~TLB_NOTDIRTY; + } + data->flags = flags; +} + +/** + * mmu_lookup: translate page(s) + * @cpu: generic cpu state + * @addr: virtual address + * @oi: combined mmu_idx and MemOp + * @ra: return address into tcg generated code, or 0 + * @access_type: load/store/code + * @l: output result + * + * Resolve the translation for the page(s) beginning at @addr, for MemOp.size + * bytes. Return true if the lookup crosses a page boundary. + */ +static bool mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMUAccessType type, MMULookupLocals *l) { + bool crosspage; + vaddr last; + int flags; + + l->memop = get_memop(oi); + l->mmu_idx = get_mmuidx(oi); + + tcg_debug_assert(l->mmu_idx < NB_MMU_MODES); + + l->page[0].addr = addr; + l->page[0].size = memop_size(l->memop); + l->page[1].addr = 0; + l->page[1].size = 0; + + /* Lookup and recognize exceptions from the first page. */ + mmu_lookup1(cpu, &l->page[0], l->memop, l->mmu_idx, type, ra); + + last = addr + l->page[0].size - 1; + crosspage = (addr ^ last) & TARGET_PAGE_MASK; + if (likely(!crosspage)) { + flags = l->page[0].flags; + if (unlikely(flags & (TLB_WATCHPOINT | TLB_NOTDIRTY))) { + mmu_watch_or_dirty(cpu, &l->page[0], type, ra); + } + if (unlikely(flags & TLB_BSWAP)) { + l->memop ^= MO_BSWAP; + } + } else { + /* Finish compute of page crossing. */ + vaddr addr1 = last & TARGET_PAGE_MASK; + int size0 = addr1 - addr; + l->page[1].size = l->page[0].size - size0; + l->page[0].size = size0; + l->page[1].addr = cpu->cc->tcg_ops->pointer_wrap(cpu, l->mmu_idx, addr1, addr); + + /* + * Lookup and recognize exceptions from the second page. + * If the lookup potentially resized the table, refresh the + * first CPUTLBEntryFull pointer. + */ + if (mmu_lookup1(cpu, &l->page[1], 0, l->mmu_idx, type, ra)) { + uintptr_t index = tlb_index(cpu, l->mmu_idx, addr); + l->page[0].full = &cpu->neg.tlb.d[l->mmu_idx].fulltlb[index]; + } + + flags = l->page[0].flags | l->page[1].flags; + if (unlikely(flags & (TLB_WATCHPOINT | TLB_NOTDIRTY))) { + mmu_watch_or_dirty(cpu, &l->page[0], type, ra); + mmu_watch_or_dirty(cpu, &l->page[1], type, ra); + } + + /* + * Since target/sparc is the only user of TLB_BSWAP, and all + * Sparc accesses are aligned, any treatment across two pages + * would be arbitrary. Refuse it until there's a use. + */ + tcg_debug_assert((flags & TLB_BSWAP) == 0); + } + + return crosspage; +} + +/* + * Probe for an atomic operation. Do not allow unaligned operations, + * or io operations to proceed. Return the host address. + */ +static void *atomic_mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi, int size, uintptr_t retaddr) { + uintptr_t mmu_idx = get_mmuidx(oi); + MemOp mop = get_memop(oi); + uintptr_t index; + CPUTLBEntry *tlbe; + vaddr tlb_addr; + void *hostaddr; + CPUTLBEntryFull *full; + bool did_tlb_fill = false; + + tcg_debug_assert(mmu_idx < NB_MMU_MODES); + + /* Adjust the given return address. */ + retaddr -= GETPC_ADJ; + + index = tlb_index(cpu, mmu_idx, addr); + tlbe = tlb_entry(cpu, mmu_idx, addr); + + /* Check TLB entry and enforce page permissions. */ + tlb_addr = tlb_addr_write(tlbe); + if (!tlb_hit(tlb_addr, addr)) { + if (!victim_tlb_hit(cpu, mmu_idx, index, MMU_DATA_STORE, addr & TARGET_PAGE_MASK)) { + tlb_fill_align(cpu, addr, MMU_DATA_STORE, mmu_idx, mop, size, false, retaddr); + did_tlb_fill = true; + index = tlb_index(cpu, mmu_idx, addr); + tlbe = tlb_entry(cpu, mmu_idx, addr); + } + tlb_addr = tlb_addr_write(tlbe) & ~TLB_INVALID_MASK; + } + + /* + * Let the guest notice RMW on a write-only page. + * We have just verified that the page is writable. + * Subpage lookups may have left TLB_INVALID_MASK set, + * but addr_read will only be -1 if PAGE_READ was unset. + */ + if (unlikely(tlbe->addr_read == -1)) { + tlb_fill_align(cpu, addr, MMU_DATA_LOAD, mmu_idx, 0, size, false, retaddr); + /* + * Since we don't support reads and writes to different + * addresses, and we do have the proper page loaded for + * write, this shouldn't ever return. + */ + g_assert_not_reached(); + } + + /* Enforce guest required alignment, if not handled by tlb_fill_align. */ + if (!did_tlb_fill && (addr & ((1 << memop_alignment_bits(mop)) - 1))) { + cpu_unaligned_access(cpu, addr, MMU_DATA_STORE, mmu_idx, retaddr); + } + + /* Enforce qemu required alignment. */ + if (unlikely(addr & (size - 1))) { + /* + * We get here if guest alignment was not requested, or was not + * enforced by cpu_unaligned_access or tlb_fill_align above. + * We might widen the access and emulate, but for now + * mark an exception and exit the cpu loop. + */ + goto stop_the_world; + } + + /* Finish collecting tlb flags for both read and write. */ + full = &cpu->neg.tlb.d[mmu_idx].fulltlb[index]; + tlb_addr |= tlbe->addr_read; + tlb_addr &= TLB_FLAGS_MASK & ~TLB_FORCE_SLOW; + tlb_addr |= full->slow_flags[MMU_DATA_STORE]; + tlb_addr |= full->slow_flags[MMU_DATA_LOAD]; + + /* Notice an IO access or a needs-MMU-lookup access */ + if (unlikely(tlb_addr & (TLB_MMIO | TLB_DISCARD_WRITE))) { + /* There's really nothing that can be done to + support this apart from stop-the-world. */ + goto stop_the_world; + } + + hostaddr = (void *) ((uintptr_t) addr + tlbe->addend); + + if (unlikely(tlb_addr & TLB_NOTDIRTY)) { + notdirty_write(cpu, addr, size, full, retaddr); + } + + if (unlikely(tlb_addr & TLB_WATCHPOINT)) { + int wp_flags = 0; + + if (full->slow_flags[MMU_DATA_STORE] & TLB_WATCHPOINT) { + wp_flags |= BP_MEM_WRITE; + } + if (full->slow_flags[MMU_DATA_LOAD] & TLB_WATCHPOINT) { + wp_flags |= BP_MEM_READ; + } + cpu_check_watchpoint(cpu, addr, size, full->attrs, wp_flags, retaddr); + } + + return hostaddr; + +stop_the_world: + cpu_loop_exit_atomic(cpu, retaddr); +} + +/* + * Load Helpers + * + * We support two different access types. SOFTMMU_CODE_ACCESS is + * specifically for reading instructions from system memory. It is + * called by the translation loop and in some helpers where the code + * is disassembled. It shouldn't be called directly by guest code. + * + * For the benefit of TCG generated code, we want to avoid the + * complication of ABI-specific return type promotion and always + * return a value extended to the register size of the host. This is + * tcg_target_long, except in the case of a 32-bit host and 64-bit + * data, and for that we always have uint64_t. + * + * We don't bother with this widened value for SOFTMMU_CODE_ACCESS. + */ + +/** + * do_ld_mmio_beN: + * @cpu: generic cpu state + * @full: page parameters + * @ret_be: accumulated data + * @addr: virtual address + * @size: number of bytes + * @mmu_idx: virtual address context + * @ra: return address into tcg generated code, or 0 + * Context: BQL held + * + * Load @size bytes from @addr, which is memory-mapped i/o. + * The bytes are concatenated in big-endian order with @ret_be. + */ +static uint64_t int_ld_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, + int mmu_idx, MMUAccessType type, uintptr_t ra, MemoryRegion *mr, hwaddr mr_offset) { + do { + MemOp this_mop; + unsigned this_size; + uint64_t val; + MemTxResult r; + + /* Read aligned pieces up to 8 bytes. */ + this_mop = ctz32(size | (int) addr | 8); + this_size = 1 << this_mop; + this_mop |= MO_BE; + + r = memory_region_dispatch_read(mr, mr_offset, &val, this_mop, full->attrs); + if (unlikely(r != MEMTX_OK)) { + io_failed(cpu, full, addr, this_size, type, mmu_idx, r, ra); + } + if (this_size == 8) { + return val; + } + + ret_be = (ret_be << (this_size * 8)) | val; + addr += this_size; + mr_offset += this_size; + size -= this_size; + } while (size); + + return ret_be; +} + +static uint64_t do_ld_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, int mmu_idx, + MMUAccessType type, uintptr_t ra) { + MemoryRegionSection *section; + MemoryRegion *mr; + hwaddr mr_offset; + + tcg_debug_assert(size > 0 && size <= 8); + + section = io_prepare(&mr_offset, cpu, full, addr, ra); + mr = section->mr; + + BQL_LOCK_GUARD(); + return int_ld_mmio_beN(cpu, full, ret_be, addr, size, mmu_idx, type, ra, mr, mr_offset); +} + +static Int128 do_ld16_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, int mmu_idx, + uintptr_t ra) { + MemoryRegionSection *section; + MemoryRegion *mr; + hwaddr mr_offset; + uint64_t a, b; + + tcg_debug_assert(size > 8 && size <= 16); + + section = io_prepare(&mr_offset, cpu, full, addr, ra); + mr = section->mr; + + BQL_LOCK_GUARD(); + a = int_ld_mmio_beN(cpu, full, ret_be, addr, size - 8, mmu_idx, MMU_DATA_LOAD, ra, mr, mr_offset); + b = int_ld_mmio_beN(cpu, full, ret_be, addr + size - 8, 8, mmu_idx, MMU_DATA_LOAD, ra, mr, mr_offset + size - 8); + return int128_make128(b, a); +} + +/** + * do_ld_bytes_beN + * @p: translation parameters + * @ret_be: accumulated data + * + * Load @p->size bytes from @p->haddr, which is RAM. + * The bytes to concatenated in big-endian order with @ret_be. + */ +static uint64_t do_ld_bytes_beN(MMULookupPageData *p, uint64_t ret_be) { + uint8_t *haddr = p->haddr; + int i, size = p->size; + + for (i = 0; i < size; i++) { + ret_be = (ret_be << 8) | haddr[i]; + } + return ret_be; +} + +/** + * do_ld_parts_beN + * @p: translation parameters + * @ret_be: accumulated data + * + * As do_ld_bytes_beN, but atomically on each aligned part. + */ +static uint64_t do_ld_parts_beN(MMULookupPageData *p, uint64_t ret_be) { + void *haddr = p->haddr; + int size = p->size; + + do { + uint64_t x; + int n; + + /* + * Find minimum of alignment and size. + * This is slightly stronger than required by MO_ATOM_SUBALIGN, which + * would have only checked the low bits of addr|size once at the start, + * but is just as easy. + */ + switch (((uintptr_t) haddr | size) & 7) { + case 4: + x = cpu_to_be32(load_atomic4(haddr)); + ret_be = (ret_be << 32) | x; + n = 4; + break; + case 2: + case 6: + x = cpu_to_be16(load_atomic2(haddr)); + ret_be = (ret_be << 16) | x; + n = 2; + break; + default: + x = *(uint8_t *) haddr; + ret_be = (ret_be << 8) | x; + n = 1; + break; + case 0: + g_assert_not_reached(); + } + haddr += n; + size -= n; + } while (size != 0); + return ret_be; +} + +/** + * do_ld_parts_be8 + * @p: translation parameters + * @ret_be: accumulated data + * + * As do_ld_bytes_beN, but with one atomic load. + * Eight aligned bytes are guaranteed to cover the load. + */ +static uint64_t do_ld_whole_be8(CPUState *cpu, uintptr_t ra, MMULookupPageData *p, uint64_t ret_be) { + int o = p->addr & 7; + uint64_t x = load_atomic8(p->haddr - o); + + x = cpu_to_be64(x); + x <<= o * 8; + x >>= (8 - p->size) * 8; + return (ret_be << (p->size * 8)) | x; +} + +/** + * do_ld_parts_be16 + * @p: translation parameters + * @ret_be: accumulated data + * + * As do_ld_bytes_beN, but with one atomic load. + * 16 aligned bytes are guaranteed to cover the load. + */ +static Int128 do_ld_whole_be16(CPUState *cpu, uintptr_t ra, MMULookupPageData *p, uint64_t ret_be) { + int o = p->addr & 15; + Int128 x, y = load_atomic16_or_exit(cpu, ra, p->haddr - o); + int size = p->size; + + if (!HOST_BIG_ENDIAN) { + y = bswap128(y); + } + y = int128_lshift(y, o * 8); + y = int128_urshift(y, (16 - size) * 8); + x = int128_make64(ret_be); + x = int128_lshift(x, size * 8); + return int128_or(x, y); +} + +/* + * Wrapper for the above. + */ +static uint64_t do_ld_beN(CPUState *cpu, MMULookupPageData *p, uint64_t ret_be, int mmu_idx, MMUAccessType type, + MemOp mop, uintptr_t ra) { + MemOp atom; + unsigned tmp, half_size; + + if (unlikely(p->flags & TLB_MMIO)) { + return do_ld_mmio_beN(cpu, p->full, ret_be, p->addr, p->size, mmu_idx, type, ra); + } + + /* + * It is a given that we cross a page and therefore there is no + * atomicity for the load as a whole, but subobjects may need attention. + */ + atom = mop & MO_ATOM_MASK; + switch (atom) { + case MO_ATOM_SUBALIGN: + return do_ld_parts_beN(p, ret_be); + + case MO_ATOM_IFALIGN_PAIR: + case MO_ATOM_WITHIN16_PAIR: + tmp = mop & MO_SIZE; + tmp = tmp ? tmp - 1 : 0; + half_size = 1 << tmp; + if (atom == MO_ATOM_IFALIGN_PAIR ? p->size == half_size : p->size >= half_size) { + return do_ld_whole_be8(cpu, ra, p, ret_be); + } + /* fall through */ + + case MO_ATOM_IFALIGN: + case MO_ATOM_WITHIN16: + case MO_ATOM_NONE: + return do_ld_bytes_beN(p, ret_be); + + default: + g_assert_not_reached(); + } +} + +/* + * Wrapper for the above, for 8 < size < 16. + */ +static Int128 do_ld16_beN(CPUState *cpu, MMULookupPageData *p, uint64_t a, int mmu_idx, MemOp mop, uintptr_t ra) { + int size = p->size; + uint64_t b; + MemOp atom; + + if (unlikely(p->flags & TLB_MMIO)) { + return do_ld16_mmio_beN(cpu, p->full, a, p->addr, size, mmu_idx, ra); + } + + /* + * It is a given that we cross a page and therefore there is no + * atomicity for the load as a whole, but subobjects may need attention. + */ + atom = mop & MO_ATOM_MASK; + switch (atom) { + case MO_ATOM_SUBALIGN: + p->size = size - 8; + a = do_ld_parts_beN(p, a); + p->haddr += size - 8; + p->size = 8; + b = do_ld_parts_beN(p, 0); + break; + + case MO_ATOM_WITHIN16_PAIR: + /* Since size > 8, this is the half that must be atomic. */ + return do_ld_whole_be16(cpu, ra, p, a); + + case MO_ATOM_IFALIGN_PAIR: + /* + * Since size > 8, both halves are misaligned, + * and so neither is atomic. + */ + case MO_ATOM_IFALIGN: + case MO_ATOM_WITHIN16: + case MO_ATOM_NONE: + p->size = size - 8; + a = do_ld_bytes_beN(p, a); + b = ldq_be_p(p->haddr + size - 8); + break; + + default: + g_assert_not_reached(); + } + + return int128_make128(b, a); +} + +static uint8_t do_ld_1(CPUState *cpu, MMULookupPageData *p, int mmu_idx, MMUAccessType type, uintptr_t ra) { + if (unlikely(p->flags & TLB_MMIO)) { + return do_ld_mmio_beN(cpu, p->full, 0, p->addr, 1, mmu_idx, type, ra); + } else { + return *(uint8_t *) p->haddr; + } +} + +static uint16_t do_ld_2(CPUState *cpu, MMULookupPageData *p, int mmu_idx, MMUAccessType type, MemOp memop, + uintptr_t ra) { + uint16_t ret; + + if (unlikely(p->flags & TLB_MMIO)) { + ret = do_ld_mmio_beN(cpu, p->full, 0, p->addr, 2, mmu_idx, type, ra); + if ((memop & MO_BSWAP) == MO_LE) { + ret = bswap16(ret); + } + } else { + /* Perform the load host endian, then swap if necessary. */ + ret = load_atom_2(cpu, ra, p->haddr, memop); + if (memop & MO_BSWAP) { + ret = bswap16(ret); + } + } + return ret; +} + +static uint32_t do_ld_4(CPUState *cpu, MMULookupPageData *p, int mmu_idx, MMUAccessType type, MemOp memop, + uintptr_t ra) { + uint32_t ret; + + if (unlikely(p->flags & TLB_MMIO)) { + ret = do_ld_mmio_beN(cpu, p->full, 0, p->addr, 4, mmu_idx, type, ra); + if ((memop & MO_BSWAP) == MO_LE) { + ret = bswap32(ret); + } + } else { + /* Perform the load host endian. */ + ret = load_atom_4(cpu, ra, p->haddr, memop); + if (memop & MO_BSWAP) { + ret = bswap32(ret); + } + } + return ret; +} + +static uint64_t do_ld_8(CPUState *cpu, MMULookupPageData *p, int mmu_idx, MMUAccessType type, MemOp memop, + uintptr_t ra) { + uint64_t ret; + + if (unlikely(p->flags & TLB_MMIO)) { + ret = do_ld_mmio_beN(cpu, p->full, 0, p->addr, 8, mmu_idx, type, ra); + if ((memop & MO_BSWAP) == MO_LE) { + ret = bswap64(ret); + } + } else { + /* Perform the load host endian. */ + ret = load_atom_8(cpu, ra, p->haddr, memop); + if (memop & MO_BSWAP) { + ret = bswap64(ret); + } + } + return ret; +} + +static uint8_t do_ld1_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMUAccessType access_type) { + MMULookupLocals l; + bool crosspage; + + cpu_req_mo(cpu, TCG_MO_LD_LD | TCG_MO_ST_LD); + crosspage = mmu_lookup(cpu, addr, oi, ra, access_type, &l); + tcg_debug_assert(!crosspage); + + return do_ld_1(cpu, &l.page[0], l.mmu_idx, access_type, ra); +} + +static uint16_t do_ld2_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMUAccessType access_type) { + MMULookupLocals l; + bool crosspage; + uint16_t ret; + uint8_t a, b; + + cpu_req_mo(cpu, TCG_MO_LD_LD | TCG_MO_ST_LD); + crosspage = mmu_lookup(cpu, addr, oi, ra, access_type, &l); + if (likely(!crosspage)) { + return do_ld_2(cpu, &l.page[0], l.mmu_idx, access_type, l.memop, ra); + } + + a = do_ld_1(cpu, &l.page[0], l.mmu_idx, access_type, ra); + b = do_ld_1(cpu, &l.page[1], l.mmu_idx, access_type, ra); + + if ((l.memop & MO_BSWAP) == MO_LE) { + ret = a | (b << 8); + } else { + ret = b | (a << 8); + } + return ret; +} + +static uint32_t do_ld4_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMUAccessType access_type) { + MMULookupLocals l; + bool crosspage; + uint32_t ret; + + cpu_req_mo(cpu, TCG_MO_LD_LD | TCG_MO_ST_LD); + crosspage = mmu_lookup(cpu, addr, oi, ra, access_type, &l); + if (likely(!crosspage)) { + return do_ld_4(cpu, &l.page[0], l.mmu_idx, access_type, l.memop, ra); + } + + ret = do_ld_beN(cpu, &l.page[0], 0, l.mmu_idx, access_type, l.memop, ra); + ret = do_ld_beN(cpu, &l.page[1], ret, l.mmu_idx, access_type, l.memop, ra); + if ((l.memop & MO_BSWAP) == MO_LE) { + ret = bswap32(ret); + } + return ret; +} + +static uint64_t do_ld8_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMUAccessType access_type) { + MMULookupLocals l; + bool crosspage; + uint64_t ret; + + cpu_req_mo(cpu, TCG_MO_LD_LD | TCG_MO_ST_LD); + crosspage = mmu_lookup(cpu, addr, oi, ra, access_type, &l); + if (likely(!crosspage)) { + return do_ld_8(cpu, &l.page[0], l.mmu_idx, access_type, l.memop, ra); + } + + ret = do_ld_beN(cpu, &l.page[0], 0, l.mmu_idx, access_type, l.memop, ra); + ret = do_ld_beN(cpu, &l.page[1], ret, l.mmu_idx, access_type, l.memop, ra); + if ((l.memop & MO_BSWAP) == MO_LE) { + ret = bswap64(ret); + } + return ret; +} + +static Int128 do_ld16_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra) { + MMULookupLocals l; + bool crosspage; + uint64_t a, b; + Int128 ret; + int first; + + cpu_req_mo(cpu, TCG_MO_LD_LD | TCG_MO_ST_LD); + crosspage = mmu_lookup(cpu, addr, oi, ra, MMU_DATA_LOAD, &l); + if (likely(!crosspage)) { + if (unlikely(l.page[0].flags & TLB_MMIO)) { + ret = do_ld16_mmio_beN(cpu, l.page[0].full, 0, addr, 16, l.mmu_idx, ra); + if ((l.memop & MO_BSWAP) == MO_LE) { + ret = bswap128(ret); + } + } else { + /* Perform the load host endian. */ + ret = load_atom_16(cpu, ra, l.page[0].haddr, l.memop); + if (l.memop & MO_BSWAP) { + ret = bswap128(ret); + } + } + return ret; + } + + first = l.page[0].size; + if (first == 8) { + MemOp mop8 = (l.memop & ~MO_SIZE) | MO_64; + + a = do_ld_8(cpu, &l.page[0], l.mmu_idx, MMU_DATA_LOAD, mop8, ra); + b = do_ld_8(cpu, &l.page[1], l.mmu_idx, MMU_DATA_LOAD, mop8, ra); + if ((mop8 & MO_BSWAP) == MO_LE) { + ret = int128_make128(a, b); + } else { + ret = int128_make128(b, a); + } + return ret; + } + + if (first < 8) { + a = do_ld_beN(cpu, &l.page[0], 0, l.mmu_idx, MMU_DATA_LOAD, l.memop, ra); + ret = do_ld16_beN(cpu, &l.page[1], a, l.mmu_idx, l.memop, ra); + } else { + ret = do_ld16_beN(cpu, &l.page[0], 0, l.mmu_idx, l.memop, ra); + b = int128_getlo(ret); + ret = int128_lshift(ret, l.page[1].size * 8); + a = int128_gethi(ret); + b = do_ld_beN(cpu, &l.page[1], b, l.mmu_idx, MMU_DATA_LOAD, l.memop, ra); + ret = int128_make128(b, a); + } + if ((l.memop & MO_BSWAP) == MO_LE) { + ret = bswap128(ret); + } + return ret; +} + +/* + * Store Helpers + */ + +/** + * do_st_mmio_leN: + * @cpu: generic cpu state + * @full: page parameters + * @val_le: data to store + * @addr: virtual address + * @size: number of bytes + * @mmu_idx: virtual address context + * @ra: return address into tcg generated code, or 0 + * Context: BQL held + * + * Store @size bytes at @addr, which is memory-mapped i/o. + * The bytes to store are extracted in little-endian order from @val_le; + * return the bytes of @val_le beyond @p->size that have not been stored. + */ +static uint64_t int_st_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t val_le, vaddr addr, int size, + int mmu_idx, uintptr_t ra, MemoryRegion *mr, hwaddr mr_offset) { + do { + MemOp this_mop; + unsigned this_size; + MemTxResult r; + + /* Store aligned pieces up to 8 bytes. */ + this_mop = ctz32(size | (int) addr | 8); + this_size = 1 << this_mop; + this_mop |= MO_LE; + + r = memory_region_dispatch_write(mr, mr_offset, val_le, this_mop, full->attrs); + if (unlikely(r != MEMTX_OK)) { + io_failed(cpu, full, addr, this_size, MMU_DATA_STORE, mmu_idx, r, ra); + } + if (this_size == 8) { + return 0; + } + + val_le >>= this_size * 8; + addr += this_size; + mr_offset += this_size; + size -= this_size; + } while (size); + + return val_le; +} + +static uint64_t do_st_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t val_le, vaddr addr, int size, int mmu_idx, + uintptr_t ra) { + MemoryRegionSection *section; + hwaddr mr_offset; + MemoryRegion *mr; + + tcg_debug_assert(size > 0 && size <= 8); + + section = io_prepare(&mr_offset, cpu, full, addr, ra); + mr = section->mr; + + BQL_LOCK_GUARD(); + return int_st_mmio_leN(cpu, full, val_le, addr, size, mmu_idx, ra, mr, mr_offset); +} + +static uint64_t do_st16_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, Int128 val_le, vaddr addr, int size, int mmu_idx, + uintptr_t ra) { + MemoryRegionSection *section; + MemoryRegion *mr; + hwaddr mr_offset; + + tcg_debug_assert(size > 8 && size <= 16); + + section = io_prepare(&mr_offset, cpu, full, addr, ra); + mr = section->mr; + + BQL_LOCK_GUARD(); + int_st_mmio_leN(cpu, full, int128_getlo(val_le), addr, 8, mmu_idx, ra, mr, mr_offset); + return int_st_mmio_leN(cpu, full, int128_gethi(val_le), addr + 8, size - 8, mmu_idx, ra, mr, mr_offset + 8); +} + +/* + * Wrapper for the above. + */ +static uint64_t do_st_leN(CPUState *cpu, MMULookupPageData *p, uint64_t val_le, int mmu_idx, MemOp mop, uintptr_t ra) { + MemOp atom; + unsigned tmp, half_size; + + if (unlikely(p->flags & TLB_MMIO)) { + return do_st_mmio_leN(cpu, p->full, val_le, p->addr, p->size, mmu_idx, ra); + } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) { + return val_le >> (p->size * 8); + } + + /* + * It is a given that we cross a page and therefore there is no atomicity + * for the store as a whole, but subobjects may need attention. + */ + atom = mop & MO_ATOM_MASK; + switch (atom) { + case MO_ATOM_SUBALIGN: + return store_parts_leN(p->haddr, p->size, val_le); + + case MO_ATOM_IFALIGN_PAIR: + case MO_ATOM_WITHIN16_PAIR: + tmp = mop & MO_SIZE; + tmp = tmp ? tmp - 1 : 0; + half_size = 1 << tmp; + if (atom == MO_ATOM_IFALIGN_PAIR ? p->size == half_size : p->size >= half_size) { + return store_whole_le8(p->haddr, p->size, val_le); + } + /* fall through */ + + case MO_ATOM_IFALIGN: + case MO_ATOM_WITHIN16: + case MO_ATOM_NONE: + return store_bytes_leN(p->haddr, p->size, val_le); + + default: + g_assert_not_reached(); + } +} + +/* + * Wrapper for the above, for 8 < size < 16. + */ +static uint64_t do_st16_leN(CPUState *cpu, MMULookupPageData *p, Int128 val_le, int mmu_idx, MemOp mop, uintptr_t ra) { + int size = p->size; + MemOp atom; + + if (unlikely(p->flags & TLB_MMIO)) { + return do_st16_mmio_leN(cpu, p->full, val_le, p->addr, size, mmu_idx, ra); + } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) { + return int128_gethi(val_le) >> ((size - 8) * 8); + } + + /* + * It is a given that we cross a page and therefore there is no atomicity + * for the store as a whole, but subobjects may need attention. + */ + atom = mop & MO_ATOM_MASK; + switch (atom) { + case MO_ATOM_SUBALIGN: + store_parts_leN(p->haddr, 8, int128_getlo(val_le)); + return store_parts_leN(p->haddr + 8, p->size - 8, int128_gethi(val_le)); + + case MO_ATOM_WITHIN16_PAIR: + /* Since size > 8, this is the half that must be atomic. */ + if (!HAVE_CMPXCHG128) { + cpu_loop_exit_atomic(cpu, ra); + } + return store_whole_le16(p->haddr, p->size, val_le); + + case MO_ATOM_IFALIGN_PAIR: + /* + * Since size > 8, both halves are misaligned, + * and so neither is atomic. + */ + case MO_ATOM_IFALIGN: + case MO_ATOM_WITHIN16: + case MO_ATOM_NONE: + stq_le_p(p->haddr, int128_getlo(val_le)); + return store_bytes_leN(p->haddr + 8, p->size - 8, int128_gethi(val_le)); + + default: + g_assert_not_reached(); + } +} + +static void do_st_1(CPUState *cpu, MMULookupPageData *p, uint8_t val, int mmu_idx, uintptr_t ra) { + if (unlikely(p->flags & TLB_MMIO)) { + do_st_mmio_leN(cpu, p->full, val, p->addr, 1, mmu_idx, ra); + } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) { + /* nothing */ + } else { + *(uint8_t *) p->haddr = val; + } +} + +static void do_st_2(CPUState *cpu, MMULookupPageData *p, uint16_t val, int mmu_idx, MemOp memop, uintptr_t ra) { + if (unlikely(p->flags & TLB_MMIO)) { + if ((memop & MO_BSWAP) != MO_LE) { + val = bswap16(val); + } + do_st_mmio_leN(cpu, p->full, val, p->addr, 2, mmu_idx, ra); + } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) { + /* nothing */ + } else { + /* Swap to host endian if necessary, then store. */ + if (memop & MO_BSWAP) { + val = bswap16(val); + } + store_atom_2(cpu, ra, p->haddr, memop, val); + } +} + +static void do_st_4(CPUState *cpu, MMULookupPageData *p, uint32_t val, int mmu_idx, MemOp memop, uintptr_t ra) { + if (unlikely(p->flags & TLB_MMIO)) { + if ((memop & MO_BSWAP) != MO_LE) { + val = bswap32(val); + } + do_st_mmio_leN(cpu, p->full, val, p->addr, 4, mmu_idx, ra); + } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) { + /* nothing */ + } else { + /* Swap to host endian if necessary, then store. */ + if (memop & MO_BSWAP) { + val = bswap32(val); + } + store_atom_4(cpu, ra, p->haddr, memop, val); + } +} + +static void do_st_8(CPUState *cpu, MMULookupPageData *p, uint64_t val, int mmu_idx, MemOp memop, uintptr_t ra) { + if (unlikely(p->flags & TLB_MMIO)) { + if ((memop & MO_BSWAP) != MO_LE) { + val = bswap64(val); + } + do_st_mmio_leN(cpu, p->full, val, p->addr, 8, mmu_idx, ra); + } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) { + /* nothing */ + } else { + /* Swap to host endian if necessary, then store. */ + if (memop & MO_BSWAP) { + val = bswap64(val); + } + store_atom_8(cpu, ra, p->haddr, memop, val); + } +} + +static void do_st1_mmu(CPUState *cpu, vaddr addr, uint8_t val, MemOpIdx oi, uintptr_t ra) { + MMULookupLocals l; + bool crosspage; + + cpu_req_mo(cpu, TCG_MO_LD_ST | TCG_MO_ST_ST); + crosspage = mmu_lookup(cpu, addr, oi, ra, MMU_DATA_STORE, &l); + tcg_debug_assert(!crosspage); + + do_st_1(cpu, &l.page[0], val, l.mmu_idx, ra); +} + +static void do_st2_mmu(CPUState *cpu, vaddr addr, uint16_t val, MemOpIdx oi, uintptr_t ra) { + MMULookupLocals l; + bool crosspage; + uint8_t a, b; + + cpu_req_mo(cpu, TCG_MO_LD_ST | TCG_MO_ST_ST); + crosspage = mmu_lookup(cpu, addr, oi, ra, MMU_DATA_STORE, &l); + if (likely(!crosspage)) { + do_st_2(cpu, &l.page[0], val, l.mmu_idx, l.memop, ra); + return; + } + + if ((l.memop & MO_BSWAP) == MO_LE) { + a = val, b = val >> 8; + } else { + b = val, a = val >> 8; + } + do_st_1(cpu, &l.page[0], a, l.mmu_idx, ra); + do_st_1(cpu, &l.page[1], b, l.mmu_idx, ra); +} + +static void do_st4_mmu(CPUState *cpu, vaddr addr, uint32_t val, MemOpIdx oi, uintptr_t ra) { + MMULookupLocals l; + bool crosspage; + + cpu_req_mo(cpu, TCG_MO_LD_ST | TCG_MO_ST_ST); + crosspage = mmu_lookup(cpu, addr, oi, ra, MMU_DATA_STORE, &l); + if (likely(!crosspage)) { + do_st_4(cpu, &l.page[0], val, l.mmu_idx, l.memop, ra); + return; + } + + /* Swap to little endian for simplicity, then store by bytes. */ + if ((l.memop & MO_BSWAP) != MO_LE) { + val = bswap32(val); + } + val = do_st_leN(cpu, &l.page[0], val, l.mmu_idx, l.memop, ra); + (void) do_st_leN(cpu, &l.page[1], val, l.mmu_idx, l.memop, ra); +} + +static void do_st8_mmu(CPUState *cpu, vaddr addr, uint64_t val, MemOpIdx oi, uintptr_t ra) { + MMULookupLocals l; + bool crosspage; + + cpu_req_mo(cpu, TCG_MO_LD_ST | TCG_MO_ST_ST); + crosspage = mmu_lookup(cpu, addr, oi, ra, MMU_DATA_STORE, &l); + if (likely(!crosspage)) { + do_st_8(cpu, &l.page[0], val, l.mmu_idx, l.memop, ra); + return; + } + + /* Swap to little endian for simplicity, then store by bytes. */ + if ((l.memop & MO_BSWAP) != MO_LE) { + val = bswap64(val); + } + val = do_st_leN(cpu, &l.page[0], val, l.mmu_idx, l.memop, ra); + (void) do_st_leN(cpu, &l.page[1], val, l.mmu_idx, l.memop, ra); +} + +static void do_st16_mmu(CPUState *cpu, vaddr addr, Int128 val, MemOpIdx oi, uintptr_t ra) { + MMULookupLocals l; + bool crosspage; + uint64_t a, b; + int first; + + cpu_req_mo(cpu, TCG_MO_LD_ST | TCG_MO_ST_ST); + crosspage = mmu_lookup(cpu, addr, oi, ra, MMU_DATA_STORE, &l); + if (likely(!crosspage)) { + if (unlikely(l.page[0].flags & TLB_MMIO)) { + if ((l.memop & MO_BSWAP) != MO_LE) { + val = bswap128(val); + } + do_st16_mmio_leN(cpu, l.page[0].full, val, addr, 16, l.mmu_idx, ra); + } else if (unlikely(l.page[0].flags & TLB_DISCARD_WRITE)) { + /* nothing */ + } else { + /* Swap to host endian if necessary, then store. */ + if (l.memop & MO_BSWAP) { + val = bswap128(val); + } + store_atom_16(cpu, ra, l.page[0].haddr, l.memop, val); + } + return; + } + + first = l.page[0].size; + if (first == 8) { + MemOp mop8 = (l.memop & ~(MO_SIZE | MO_BSWAP)) | MO_64; + + if (l.memop & MO_BSWAP) { + val = bswap128(val); + } + if (HOST_BIG_ENDIAN) { + b = int128_getlo(val), a = int128_gethi(val); + } else { + a = int128_getlo(val), b = int128_gethi(val); + } + do_st_8(cpu, &l.page[0], a, l.mmu_idx, mop8, ra); + do_st_8(cpu, &l.page[1], b, l.mmu_idx, mop8, ra); + return; + } + + if ((l.memop & MO_BSWAP) != MO_LE) { + val = bswap128(val); + } + if (first < 8) { + do_st_leN(cpu, &l.page[0], int128_getlo(val), l.mmu_idx, l.memop, ra); + val = int128_urshift(val, first * 8); + do_st16_leN(cpu, &l.page[1], val, l.mmu_idx, l.memop, ra); + } else { + b = do_st16_leN(cpu, &l.page[0], val, l.mmu_idx, l.memop, ra); + do_st_leN(cpu, &l.page[1], b, l.mmu_idx, l.memop, ra); + } +} + +#include "ldst_common.c.inc" + +/* + * First set of functions passes in OI and RETADDR. + * This makes them callable from other helpers. + */ + +#define ATOMIC_NAME(X) glue(glue(glue(cpu_atomic_##X, SUFFIX), END), _mmu) + +#define ATOMIC_MMU_CLEANUP + +#include "atomic_common.c.inc" + +#define DATA_SIZE 1 +#include "atomic_template.h" + +#define DATA_SIZE 2 +#include "atomic_template.h" + +#define DATA_SIZE 4 +#include "atomic_template.h" + +#define DATA_SIZE 8 +#include "atomic_template.h" + +#if defined(CONFIG_ATOMIC128) || HAVE_CMPXCHG128 +#define DATA_SIZE 16 +#include "atomic_template.h" +#endif + +/* Code access functions. */ + +uint8_t cpu_ldb_code_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t retaddr) { + return do_ld1_mmu(env_cpu(env), addr, oi, retaddr, MMU_INST_FETCH); +} + +uint16_t cpu_ldw_code_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t retaddr) { + return do_ld2_mmu(env_cpu(env), addr, oi, retaddr, MMU_INST_FETCH); +} + +uint32_t cpu_ldl_code_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t retaddr) { + return do_ld4_mmu(env_cpu(env), addr, oi, retaddr, MMU_INST_FETCH); +} + +uint64_t cpu_ldq_code_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t retaddr) { + return do_ld8_mmu(env_cpu(env), addr, oi, retaddr, MMU_INST_FETCH); +} + +/* + * Common pointer_wrap implementations. + */ + +/* + * To be used for strict alignment targets. + * Because no accesses are unaligned, no accesses wrap either. + */ +vaddr cpu_pointer_wrap_notreached(CPUState *cs, int idx, vaddr res, vaddr base) { + g_assert_not_reached(); +} + +/* To be used for strict 32-bit targets. */ +vaddr cpu_pointer_wrap_uint32(CPUState *cs, int idx, vaddr res, vaddr base) { + return (uint32_t) res; +} diff --git a/libcpu/src/accel/ldst_atomicity.c.inc b/libcpu/src/accel/ldst_atomicity.c.inc new file mode 100644 index 000000000..5f8652f2b --- /dev/null +++ b/libcpu/src/accel/ldst_atomicity.c.inc @@ -0,0 +1,967 @@ +/* + * Routines common to user and system emulation of load/store. + * + * Copyright (c) 2022 Linaro, Ltd. + * + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#include "host/load-extract-al16-al8.h.inc" +#include "host/store-insert-al16.h.inc" + +/** + * required_atomicity: + * + * Return the lg2 bytes of atomicity required by @memop for @p. + * If the operation must be split into two operations to be + * examined separately for atomicity, return -lg2. + */ +static int required_atomicity(CPUState *cpu, uintptr_t p, MemOp memop) { + MemOp atom = memop & MO_ATOM_MASK; + MemOp size = memop & MO_SIZE; + MemOp half = size ? size - 1 : 0; + unsigned tmp; + int atmax; + + switch (atom) { + case MO_ATOM_NONE: + atmax = MO_8; + break; + + case MO_ATOM_IFALIGN_PAIR: + size = half; + /* fall through */ + + case MO_ATOM_IFALIGN: + tmp = (1 << size) - 1; + atmax = p & tmp ? MO_8 : size; + break; + + case MO_ATOM_WITHIN16: + tmp = p & 15; + atmax = (tmp + (1 << size) <= 16 ? size : MO_8); + break; + + case MO_ATOM_WITHIN16_PAIR: + tmp = p & 15; + if (tmp + (1 << size) <= 16) { + atmax = size; + } else if (tmp + (1 << half) == 16) { + /* + * The pair exactly straddles the boundary. + * Both halves are naturally aligned and atomic. + */ + atmax = half; + } else { + /* + * One of the pair crosses the boundary, and is non-atomic. + * The other of the pair does not cross, and is atomic. + */ + atmax = -half; + } + break; + + case MO_ATOM_SUBALIGN: + /* + * Examine the alignment of p to determine if there are subobjects + * that must be aligned. Note that we only really need ctz4() -- + * any more significant bits are discarded by the immediately + * following comparison. + */ + tmp = ctz32(p); + atmax = MIN(size, tmp); + break; + + default: + g_assert_not_reached(); + } + + /* + * Here we have the architectural atomicity of the operation. + * However, when executing in a serial context, we need no extra + * host atomicity in order to avoid racing. This reduction + * avoids looping with cpu_loop_exit_atomic. + */ + if (cpu_in_serial_context(cpu)) { + return MO_8; + } + return atmax; +} + +/** + * load_atomic2: + * @pv: host address + * + * Atomically load 2 aligned bytes from @pv. + */ +static inline uint16_t load_atomic2(void *pv) { + uint16_t *p = __builtin_assume_aligned(pv, 2); + return qatomic_read(p); +} + +/** + * load_atomic4: + * @pv: host address + * + * Atomically load 4 aligned bytes from @pv. + */ +static inline uint32_t load_atomic4(void *pv) { + uint32_t *p = __builtin_assume_aligned(pv, 4); + return qatomic_read(p); +} + +/** + * load_atomic8: + * @pv: host address + * + * Atomically load 8 aligned bytes from @pv. + */ +static inline uint64_t load_atomic8(void *pv) { + uint64_t *p = __builtin_assume_aligned(pv, 8); + return qatomic_read(p); +} + +/** + * load_atomic16_or_exit: + * @cpu: generic cpu state + * @ra: host unwind address + * @pv: host address + * + * Atomically load 16 aligned bytes from @pv. + * If this is not possible, longjmp out to restart serially. + */ +static Int128 load_atomic16_or_exit(CPUState *cpu, uintptr_t ra, void *pv) { + Int128 *p = __builtin_assume_aligned(pv, 16); + + if (HAVE_ATOMIC128_RO) { + return atomic16_read_ro(p); + } + + /* + * We can only use cmpxchg to emulate a load if the page is writable. + * If the page is not writable, then assume the value is immutable + * and requires no locking. This ignores the case of MAP_SHARED with + * another process, because the fallback start_exclusive solution + * provides no protection across processes. + * + * In system mode all guest pages are writable. For user mode, + * we must take mmap_lock so that the query remains valid until + * the write is complete -- tests/tcg/multiarch/munmap-pthread.c + * is an example that can race. + */ + WITH_MMAP_LOCK_GUARD() { +#ifdef CONFIG_USER_ONLY + if (!page_check_range(h2g(p), 16, PAGE_WRITE_ORG)) { + return *p; + } +#endif + if (HAVE_ATOMIC128_RW) { + return atomic16_read_rw(p); + } + } + + /* Ultimate fallback: re-execute in serial context. */ + trace_load_atom16_or_exit_fallback(ra); + cpu_loop_exit_atomic(cpu, ra); +} + +/** + * load_atom_extract_al4x2: + * @pv: host address + * + * Load 4 bytes from @p, from two sequential atomic 4-byte loads. + */ +static uint32_t load_atom_extract_al4x2(void *pv) { + uintptr_t pi = (uintptr_t) pv; + int sh = (pi & 3) * 8; + uint32_t a, b; + + pv = (void *) (pi & ~3); + a = load_atomic4(pv); + b = load_atomic4(pv + 4); + + if (HOST_BIG_ENDIAN) { + return (a << sh) | (b >> (-sh & 31)); + } else { + return (a >> sh) | (b << (-sh & 31)); + } +} + +/** + * load_atom_extract_al8x2: + * @pv: host address + * + * Load 8 bytes from @p, from two sequential atomic 8-byte loads. + */ +static uint64_t load_atom_extract_al8x2(void *pv) { + uintptr_t pi = (uintptr_t) pv; + int sh = (pi & 7) * 8; + uint64_t a, b; + + pv = (void *) (pi & ~7); + a = load_atomic8(pv); + b = load_atomic8(pv + 8); + + if (HOST_BIG_ENDIAN) { + return (a << sh) | (b >> (-sh & 63)); + } else { + return (a >> sh) | (b << (-sh & 63)); + } +} + +/** + * load_atom_extract_al8 + * @pv: host address + * @s: object size in bytes, @s <= 4. + * + * Atomically load @s bytes from @p, when p % s != 0, and [p, p+s-1] does + * not cross an 8-byte boundary. This means that we can perform an atomic + * 8-byte load and extract. + * The value is returned in the low bits of a uint32_t. + */ +static uint32_t load_atom_extract_al8(void *pv, int s) { + uintptr_t pi = (uintptr_t) pv; + int o = pi & 7; + int shr = (HOST_BIG_ENDIAN ? 8 - s - o : o) * 8; + + pv = (void *) (pi & ~7); + return load_atomic8(pv) >> shr; +} + +/** + * load_atom_extract_al16_or_exit: + * @cpu: generic cpu state + * @ra: host unwind address + * @p: host address + * @s: object size in bytes, @s <= 8. + * + * Atomically load @s bytes from @p, when p % 16 < 8 + * and p % 16 + s > 8. I.e. does not cross a 16-byte + * boundary, but *does* cross an 8-byte boundary. + * This is the slow version, so we must have eliminated + * any faster load_atom_extract_al8 case. + * + * If this is not possible, longjmp out to restart serially. + */ +static uint64_t load_atom_extract_al16_or_exit(CPUState *cpu, uintptr_t ra, void *pv, int s) { + uintptr_t pi = (uintptr_t) pv; + int o = pi & 7; + int shr = (HOST_BIG_ENDIAN ? 16 - s - o : o) * 8; + Int128 r; + + /* + * Note constraints above: p & 8 must be clear. + * Provoke SIGBUS if possible otherwise. + */ + pv = (void *) (pi & ~7); + r = load_atomic16_or_exit(cpu, ra, pv); + + r = int128_urshift(r, shr); + return int128_getlo(r); +} + +/** + * load_atom_4_by_2: + * @pv: host address + * + * Load 4 bytes from @pv, with two 2-byte atomic loads. + */ +static inline uint32_t load_atom_4_by_2(void *pv) { + uint32_t a = load_atomic2(pv); + uint32_t b = load_atomic2(pv + 2); + + if (HOST_BIG_ENDIAN) { + return (a << 16) | b; + } else { + return (b << 16) | a; + } +} + +/** + * load_atom_8_by_2: + * @pv: host address + * + * Load 8 bytes from @pv, with four 2-byte atomic loads. + */ +static inline uint64_t load_atom_8_by_2(void *pv) { + uint32_t a = load_atom_4_by_2(pv); + uint32_t b = load_atom_4_by_2(pv + 4); + + if (HOST_BIG_ENDIAN) { + return ((uint64_t) a << 32) | b; + } else { + return ((uint64_t) b << 32) | a; + } +} + +/** + * load_atom_8_by_4: + * @pv: host address + * + * Load 8 bytes from @pv, with two 4-byte atomic loads. + */ +static inline uint64_t load_atom_8_by_4(void *pv) { + uint32_t a = load_atomic4(pv); + uint32_t b = load_atomic4(pv + 4); + + if (HOST_BIG_ENDIAN) { + return ((uint64_t) a << 32) | b; + } else { + return ((uint64_t) b << 32) | a; + } +} + +/** + * load_atom_2: + * @p: host address + * @memop: the full memory op + * + * Load 2 bytes from @p, honoring the atomicity of @memop. + */ +static uint16_t load_atom_2(CPUState *cpu, uintptr_t ra, void *pv, MemOp memop) { + uintptr_t pi = (uintptr_t) pv; + int atmax; + + if (likely((pi & 1) == 0)) { + return load_atomic2(pv); + } + if (HAVE_ATOMIC128_RO) { + intptr_t left_in_page = -(pi | TARGET_PAGE_MASK); + if (likely(left_in_page > 8)) { + return load_atom_extract_al16_or_al8(pv, 2); + } + } + + atmax = required_atomicity(cpu, pi, memop); + switch (atmax) { + case MO_8: + return lduw_he_p(pv); + case MO_16: + /* The only case remaining is MO_ATOM_WITHIN16. */ + if ((pi & 15) != 7) { + return load_atom_extract_al8(pv, 2); + } + return load_atom_extract_al16_or_exit(cpu, ra, pv, 2); + default: + g_assert_not_reached(); + } +} + +/** + * load_atom_4: + * @p: host address + * @memop: the full memory op + * + * Load 4 bytes from @p, honoring the atomicity of @memop. + */ +static uint32_t load_atom_4(CPUState *cpu, uintptr_t ra, void *pv, MemOp memop) { + uintptr_t pi = (uintptr_t) pv; + int atmax; + + if (likely((pi & 3) == 0)) { + return load_atomic4(pv); + } + if (HAVE_ATOMIC128_RO) { + intptr_t left_in_page = -(pi | TARGET_PAGE_MASK); + if (likely(left_in_page > 8)) { + return load_atom_extract_al16_or_al8(pv, 4); + } + } + + atmax = required_atomicity(cpu, pi, memop); + switch (atmax) { + case MO_8: + case MO_16: + case -MO_16: + /* + * For MO_ATOM_IFALIGN, this is more atomicity than required, + * but it's trivially supported on all hosts, better than 4 + * individual byte loads (when the host requires alignment), + * and overlaps with the MO_ATOM_SUBALIGN case of p % 2 == 0. + */ + return load_atom_extract_al4x2(pv); + case MO_32: + if (!(pi & 4)) { + return load_atom_extract_al8(pv, 4); + } + return load_atom_extract_al16_or_exit(cpu, ra, pv, 4); + default: + g_assert_not_reached(); + } +} + +/** + * load_atom_8: + * @p: host address + * @memop: the full memory op + * + * Load 8 bytes from @p, honoring the atomicity of @memop. + */ +static uint64_t load_atom_8(CPUState *cpu, uintptr_t ra, void *pv, MemOp memop) { + uintptr_t pi = (uintptr_t) pv; + int atmax; + + /* + * If the host does not support 8-byte atomics, wait until we have + * examined the atomicity parameters below. + */ + if (likely((pi & 7) == 0)) { + return load_atomic8(pv); + } + if (HAVE_ATOMIC128_RO) { + return load_atom_extract_al16_or_al8(pv, 8); + } + + atmax = required_atomicity(cpu, pi, memop); + if (atmax == MO_64) { + return load_atom_extract_al16_or_exit(cpu, ra, pv, 8); + } + return load_atom_extract_al8x2(pv); +} + +/** + * load_atom_16: + * @p: host address + * @memop: the full memory op + * + * Load 16 bytes from @p, honoring the atomicity of @memop. + */ +static Int128 load_atom_16(CPUState *cpu, uintptr_t ra, void *pv, MemOp memop) { + uintptr_t pi = (uintptr_t) pv; + int atmax; + Int128 r; + uint64_t a, b; + + /* + * If the host does not support 16-byte atomics, wait until we have + * examined the atomicity parameters below. + */ + if (HAVE_ATOMIC128_RO && likely((pi & 15) == 0)) { + return atomic16_read_ro(pv); + } + + atmax = required_atomicity(cpu, pi, memop); + switch (atmax) { + case MO_8: + memcpy(&r, pv, 16); + return r; + case MO_16: + a = load_atom_8_by_2(pv); + b = load_atom_8_by_2(pv + 8); + break; + case MO_32: + a = load_atom_8_by_4(pv); + b = load_atom_8_by_4(pv + 8); + break; + case MO_64: + a = load_atomic8(pv); + b = load_atomic8(pv + 8); + break; + case -MO_64: + a = load_atom_extract_al8x2(pv); + b = load_atom_extract_al8x2(pv + 8); + break; + case MO_128: + return load_atomic16_or_exit(cpu, ra, pv); + default: + g_assert_not_reached(); + } + return int128_make128(HOST_BIG_ENDIAN ? b : a, HOST_BIG_ENDIAN ? a : b); +} + +/** + * store_atomic2: + * @pv: host address + * @val: value to store + * + * Atomically store 2 aligned bytes to @pv. + */ +static inline void store_atomic2(void *pv, uint16_t val) { + uint16_t *p = __builtin_assume_aligned(pv, 2); + qatomic_set(p, val); +} + +/** + * store_atomic4: + * @pv: host address + * @val: value to store + * + * Atomically store 4 aligned bytes to @pv. + */ +static inline void store_atomic4(void *pv, uint32_t val) { + uint32_t *p = __builtin_assume_aligned(pv, 4); + qatomic_set(p, val); +} + +/** + * store_atomic8: + * @pv: host address + * @val: value to store + * + * Atomically store 8 aligned bytes to @pv. + */ +static inline void store_atomic8(void *pv, uint64_t val) { + uint64_t *p = __builtin_assume_aligned(pv, 8); + qatomic_set(p, val); +} + +/** + * store_atom_4x2 + */ +static inline void store_atom_4_by_2(void *pv, uint32_t val) { + store_atomic2(pv, val >> (HOST_BIG_ENDIAN ? 16 : 0)); + store_atomic2(pv + 2, val >> (HOST_BIG_ENDIAN ? 0 : 16)); +} + +/** + * store_atom_8_by_2 + */ +static inline void store_atom_8_by_2(void *pv, uint64_t val) { + store_atom_4_by_2(pv, val >> (HOST_BIG_ENDIAN ? 32 : 0)); + store_atom_4_by_2(pv + 4, val >> (HOST_BIG_ENDIAN ? 0 : 32)); +} + +/** + * store_atom_8_by_4 + */ +static inline void store_atom_8_by_4(void *pv, uint64_t val) { + store_atomic4(pv, val >> (HOST_BIG_ENDIAN ? 32 : 0)); + store_atomic4(pv + 4, val >> (HOST_BIG_ENDIAN ? 0 : 32)); +} + +/** + * store_atom_insert_al4: + * @p: host address + * @val: shifted value to store + * @msk: mask for value to store + * + * Atomically store @val to @p, masked by @msk. + */ +static void store_atom_insert_al4(uint32_t *p, uint32_t val, uint32_t msk) { + uint32_t old, new; + + p = __builtin_assume_aligned(p, 4); + old = qatomic_read(p); + do { + new = (old & ~msk) | val; + } while (!__atomic_compare_exchange_n(p, &old, new, true, __ATOMIC_RELAXED, __ATOMIC_RELAXED)); +} + +/** + * store_atom_insert_al8: + * @p: host address + * @val: shifted value to store + * @msk: mask for value to store + * + * Atomically store @val to @p masked by @msk. + */ +static void store_atom_insert_al8(uint64_t *p, uint64_t val, uint64_t msk) { + uint64_t old, new; + + p = __builtin_assume_aligned(p, 8); + old = qatomic_read(p); + do { + new = (old & ~msk) | val; + } while (!__atomic_compare_exchange_n(p, &old, new, true, __ATOMIC_RELAXED, __ATOMIC_RELAXED)); +} + +/** + * store_bytes_leN: + * @pv: host address + * @size: number of bytes to store + * @val_le: data to store + * + * Store @size bytes at @p. The bytes to store are extracted in little-endian order + * from @val_le; return the bytes of @val_le beyond @size that have not been stored. + */ +static uint64_t store_bytes_leN(void *pv, int size, uint64_t val_le) { + uint8_t *p = pv; + for (int i = 0; i < size; i++, val_le >>= 8) { + p[i] = val_le; + } + return val_le; +} + +/** + * store_parts_leN + * @pv: host address + * @size: number of bytes to store + * @val_le: data to store + * + * As store_bytes_leN, but atomically on each aligned part. + */ +G_GNUC_UNUSED +static uint64_t store_parts_leN(void *pv, int size, uint64_t val_le) { + do { + int n; + + /* Find minimum of alignment and size */ + switch (((uintptr_t) pv | size) & 7) { + case 4: + store_atomic4(pv, le32_to_cpu(val_le)); + val_le >>= 32; + n = 4; + break; + case 2: + case 6: + store_atomic2(pv, le16_to_cpu(val_le)); + val_le >>= 16; + n = 2; + break; + default: + *(uint8_t *) pv = val_le; + val_le >>= 8; + n = 1; + break; + case 0: + g_assert_not_reached(); + } + pv += n; + size -= n; + } while (size != 0); + + return val_le; +} + +/** + * store_whole_le4 + * @pv: host address + * @size: number of bytes to store + * @val_le: data to store + * + * As store_bytes_leN, but atomically as a whole. + * Four aligned bytes are guaranteed to cover the store. + */ +static uint64_t store_whole_le4(void *pv, int size, uint64_t val_le) { + int sz = size * 8; + int o = (uintptr_t) pv & 3; + int sh = o * 8; + uint32_t m = MAKE_64BIT_MASK(0, sz); + uint32_t v; + + if (HOST_BIG_ENDIAN) { + v = bswap32(val_le) >> sh; + m = bswap32(m) >> sh; + } else { + v = val_le << sh; + m <<= sh; + } + store_atom_insert_al4(pv - o, v, m); + return val_le >> sz; +} + +/** + * store_whole_le8 + * @pv: host address + * @size: number of bytes to store + * @val_le: data to store + * + * As store_bytes_leN, but atomically as a whole. + * Eight aligned bytes are guaranteed to cover the store. + */ +static uint64_t store_whole_le8(void *pv, int size, uint64_t val_le) { + int sz = size * 8; + int o = (uintptr_t) pv & 7; + int sh = o * 8; + uint64_t m = MAKE_64BIT_MASK(0, sz); + uint64_t v; + + if (HOST_BIG_ENDIAN) { + v = bswap64(val_le) >> sh; + m = bswap64(m) >> sh; + } else { + v = val_le << sh; + m <<= sh; + } + store_atom_insert_al8(pv - o, v, m); + return val_le >> sz; +} + +/** + * store_whole_le16 + * @pv: host address + * @size: number of bytes to store + * @val_le: data to store + * + * As store_bytes_leN, but atomically as a whole. + * 16 aligned bytes are guaranteed to cover the store. + */ +static uint64_t store_whole_le16(void *pv, int size, Int128 val_le) { + int sz = size * 8; + int o = (uintptr_t) pv & 15; + int sh = o * 8; + Int128 m, v; + + qemu_build_assert(HAVE_CMPXCHG128); + + /* Like MAKE_64BIT_MASK(0, sz), but larger. */ + if (sz <= 64) { + m = int128_make64(MAKE_64BIT_MASK(0, sz)); + } else { + m = int128_make128(-1, MAKE_64BIT_MASK(0, sz - 64)); + } + + if (HOST_BIG_ENDIAN) { + v = int128_urshift(bswap128(val_le), sh); + m = int128_urshift(bswap128(m), sh); + } else { + v = int128_lshift(val_le, sh); + m = int128_lshift(m, sh); + } + store_atom_insert_al16(pv - o, v, m); + + if (sz <= 64) { + return 0; + } + return int128_gethi(val_le) >> (sz - 64); +} + +/** + * store_atom_2: + * @p: host address + * @val: the value to store + * @memop: the full memory op + * + * Store 2 bytes to @p, honoring the atomicity of @memop. + */ +static void store_atom_2(CPUState *cpu, uintptr_t ra, void *pv, MemOp memop, uint16_t val) { + uintptr_t pi = (uintptr_t) pv; + int atmax; + + if (likely((pi & 1) == 0)) { + store_atomic2(pv, val); + return; + } + + atmax = required_atomicity(cpu, pi, memop); + if (atmax == MO_8) { + stw_he_p(pv, val); + return; + } + + /* + * The only case remaining is MO_ATOM_WITHIN16. + * Big or little endian, we want the middle two bytes in each test. + */ + if ((pi & 3) == 1) { + store_atom_insert_al4(pv - 1, (uint32_t) val << 8, MAKE_64BIT_MASK(8, 16)); + return; + } else if ((pi & 7) == 3) { + store_atom_insert_al8(pv - 3, (uint64_t) val << 24, MAKE_64BIT_MASK(24, 16)); + return; + } else if ((pi & 15) == 7) { + if (HAVE_CMPXCHG128) { + Int128 v = int128_lshift(int128_make64(val), 56); + Int128 m = int128_lshift(int128_make64(0xffff), 56); + store_atom_insert_al16(pv - 7, v, m); + return; + } + } else { + g_assert_not_reached(); + } + + trace_store_atom2_fallback(memop, ra); + cpu_loop_exit_atomic(cpu, ra); +} + +/** + * store_atom_4: + * @p: host address + * @val: the value to store + * @memop: the full memory op + * + * Store 4 bytes to @p, honoring the atomicity of @memop. + */ +static void store_atom_4(CPUState *cpu, uintptr_t ra, void *pv, MemOp memop, uint32_t val) { + uintptr_t pi = (uintptr_t) pv; + int atmax; + + if (likely((pi & 3) == 0)) { + store_atomic4(pv, val); + return; + } + + atmax = required_atomicity(cpu, pi, memop); + switch (atmax) { + case MO_8: + stl_he_p(pv, val); + return; + case MO_16: + store_atom_4_by_2(pv, val); + return; + case -MO_16: { + uint32_t val_le = cpu_to_le32(val); + int s2 = pi & 3; + int s1 = 4 - s2; + + switch (s2) { + case 1: + val_le = store_whole_le4(pv, s1, val_le); + *(uint8_t *) (pv + 3) = val_le; + break; + case 3: + *(uint8_t *) pv = val_le; + store_whole_le4(pv + 1, s2, val_le >> 8); + break; + case 0: /* aligned */ + case 2: /* atmax MO_16 */ + default: + g_assert_not_reached(); + } + } + return; + case MO_32: + if ((pi & 7) < 4) { + store_whole_le8(pv, 4, cpu_to_le32(val)); + return; + } else { + if (HAVE_CMPXCHG128) { + store_whole_le16(pv, 4, int128_make64(cpu_to_le32(val))); + return; + } + } + trace_store_atom4_fallback(memop, ra); + cpu_loop_exit_atomic(cpu, ra); + default: + g_assert_not_reached(); + } +} + +/** + * store_atom_8: + * @p: host address + * @val: the value to store + * @memop: the full memory op + * + * Store 8 bytes to @p, honoring the atomicity of @memop. + */ +static void store_atom_8(CPUState *cpu, uintptr_t ra, void *pv, MemOp memop, uint64_t val) { + uintptr_t pi = (uintptr_t) pv; + int atmax; + + if (likely((pi & 7) == 0)) { + store_atomic8(pv, val); + return; + } + + atmax = required_atomicity(cpu, pi, memop); + switch (atmax) { + case MO_8: + stq_he_p(pv, val); + return; + case MO_16: + store_atom_8_by_2(pv, val); + return; + case MO_32: + store_atom_8_by_4(pv, val); + return; + case -MO_32: { + uint64_t val_le = cpu_to_le64(val); + int s2 = pi & 7; + int s1 = 8 - s2; + + switch (s2) { + case 1 ... 3: + val_le = store_whole_le8(pv, s1, val_le); + store_bytes_leN(pv + s1, s2, val_le); + break; + case 5 ... 7: + val_le = store_bytes_leN(pv, s1, val_le); + store_whole_le8(pv + s1, s2, val_le); + break; + case 0: /* aligned */ + case 4: /* atmax MO_32 */ + default: + g_assert_not_reached(); + } + } + return; + case MO_64: + if (HAVE_CMPXCHG128) { + store_whole_le16(pv, 8, int128_make64(cpu_to_le64(val))); + return; + } + break; + default: + g_assert_not_reached(); + } + trace_store_atom8_fallback(memop, ra); + cpu_loop_exit_atomic(cpu, ra); +} + +/** + * store_atom_16: + * @p: host address + * @val: the value to store + * @memop: the full memory op + * + * Store 16 bytes to @p, honoring the atomicity of @memop. + */ +static void store_atom_16(CPUState *cpu, uintptr_t ra, void *pv, MemOp memop, Int128 val) { + uintptr_t pi = (uintptr_t) pv; + uint64_t a, b; + int atmax; + + if (HAVE_ATOMIC128_RW && likely((pi & 15) == 0)) { + atomic16_set(pv, val); + return; + } + + atmax = required_atomicity(cpu, pi, memop); + + a = HOST_BIG_ENDIAN ? int128_gethi(val) : int128_getlo(val); + b = HOST_BIG_ENDIAN ? int128_getlo(val) : int128_gethi(val); + switch (atmax) { + case MO_8: + memcpy(pv, &val, 16); + return; + case MO_16: + store_atom_8_by_2(pv, a); + store_atom_8_by_2(pv + 8, b); + return; + case MO_32: + store_atom_8_by_4(pv, a); + store_atom_8_by_4(pv + 8, b); + return; + case MO_64: + store_atomic8(pv, a); + store_atomic8(pv + 8, b); + return; + case -MO_64: + if (HAVE_CMPXCHG128) { + uint64_t val_le; + int s2 = pi & 15; + int s1 = 16 - s2; + + if (HOST_BIG_ENDIAN) { + val = bswap128(val); + } + switch (s2) { + case 1 ... 7: + val_le = store_whole_le16(pv, s1, val); + store_bytes_leN(pv + s1, s2, val_le); + break; + case 9 ... 15: + store_bytes_leN(pv, s1, int128_getlo(val)); + val = int128_urshift(val, s1 * 8); + store_whole_le16(pv + s1, s2, val); + break; + case 0: /* aligned */ + case 8: /* atmax MO_64 */ + default: + g_assert_not_reached(); + } + return; + } + break; + case MO_128: + break; + default: + g_assert_not_reached(); + } + trace_store_atom16_fallback(memop, ra); + cpu_loop_exit_atomic(cpu, ra); +} diff --git a/libcpu/src/accel/ldst_common.c.inc b/libcpu/src/accel/ldst_common.c.inc new file mode 100644 index 000000000..4ce282a4d --- /dev/null +++ b/libcpu/src/accel/ldst_common.c.inc @@ -0,0 +1,186 @@ +/* + * Routines common to user and system emulation of load/store. + * + * Copyright (c) 2003 Fabrice Bellard + * + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ +/* + * Load helpers for tcg-ldst.h + */ + +tcg_target_ulong helper_ldub_mmu(CPUArchState *env, uint64_t addr, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_8); + return do_ld1_mmu(env_cpu(env), addr, oi, retaddr, MMU_DATA_LOAD); +} + +tcg_target_ulong helper_lduw_mmu(CPUArchState *env, uint64_t addr, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_16); + return do_ld2_mmu(env_cpu(env), addr, oi, retaddr, MMU_DATA_LOAD); +} + +tcg_target_ulong helper_ldul_mmu(CPUArchState *env, uint64_t addr, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_32); + return do_ld4_mmu(env_cpu(env), addr, oi, retaddr, MMU_DATA_LOAD); +} + +uint64_t helper_ldq_mmu(CPUArchState *env, uint64_t addr, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_64); + return do_ld8_mmu(env_cpu(env), addr, oi, retaddr, MMU_DATA_LOAD); +} + +/* + * Provide signed versions of the load routines as well. We can of course + * avoid this for 64-bit data, or for 32-bit data on 32-bit host. + */ + +tcg_target_ulong helper_ldsb_mmu(CPUArchState *env, uint64_t addr, MemOpIdx oi, uintptr_t retaddr) { + return (int8_t) helper_ldub_mmu(env, addr, oi, retaddr); +} + +tcg_target_ulong helper_ldsw_mmu(CPUArchState *env, uint64_t addr, MemOpIdx oi, uintptr_t retaddr) { + return (int16_t) helper_lduw_mmu(env, addr, oi, retaddr); +} + +tcg_target_ulong helper_ldsl_mmu(CPUArchState *env, uint64_t addr, MemOpIdx oi, uintptr_t retaddr) { + return (int32_t) helper_ldul_mmu(env, addr, oi, retaddr); +} + +Int128 helper_ld16_mmu(CPUArchState *env, uint64_t addr, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_128); + return do_ld16_mmu(env_cpu(env), addr, oi, retaddr); +} + +Int128 helper_ld_i128(CPUArchState *env, uint64_t addr, uint32_t oi) { + return helper_ld16_mmu(env, addr, oi, GETPC()); +} + +/* + * Store helpers for tcg-ldst.h + */ + +void helper_stb_mmu(CPUArchState *env, uint64_t addr, uint32_t val, MemOpIdx oi, uintptr_t ra) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_8); + do_st1_mmu(env_cpu(env), addr, val, oi, ra); +} + +void helper_stw_mmu(CPUArchState *env, uint64_t addr, uint32_t val, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_16); + do_st2_mmu(env_cpu(env), addr, val, oi, retaddr); +} + +void helper_stl_mmu(CPUArchState *env, uint64_t addr, uint32_t val, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_32); + do_st4_mmu(env_cpu(env), addr, val, oi, retaddr); +} + +void helper_stq_mmu(CPUArchState *env, uint64_t addr, uint64_t val, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_64); + do_st8_mmu(env_cpu(env), addr, val, oi, retaddr); +} + +void helper_st16_mmu(CPUArchState *env, uint64_t addr, Int128 val, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_128); + do_st16_mmu(env_cpu(env), addr, val, oi, retaddr); +} + +void helper_st_i128(CPUArchState *env, uint64_t addr, Int128 val, MemOpIdx oi) { + helper_st16_mmu(env, addr, val, oi, GETPC()); +} + +/* + * Load helpers for cpu_ldst.h + */ + +static void plugin_load_cb(CPUArchState *env, vaddr addr, uint64_t value_low, uint64_t value_high, MemOpIdx oi) { + if (cpu_plugin_mem_cbs_enabled(env_cpu(env))) { + qemu_plugin_vcpu_mem_cb(env_cpu(env), addr, value_low, value_high, oi, QEMU_PLUGIN_MEM_R); + } +} + +uint8_t cpu_ldb_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra) { + uint8_t ret; + + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_UB); + ret = do_ld1_mmu(env_cpu(env), addr, oi, ra, MMU_DATA_LOAD); + plugin_load_cb(env, addr, ret, 0, oi); + return ret; +} + +uint16_t cpu_ldw_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra) { + uint16_t ret; + + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_16); + ret = do_ld2_mmu(env_cpu(env), addr, oi, ra, MMU_DATA_LOAD); + plugin_load_cb(env, addr, ret, 0, oi); + return ret; +} + +uint32_t cpu_ldl_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra) { + uint32_t ret; + + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_32); + ret = do_ld4_mmu(env_cpu(env), addr, oi, ra, MMU_DATA_LOAD); + plugin_load_cb(env, addr, ret, 0, oi); + return ret; +} + +uint64_t cpu_ldq_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra) { + uint64_t ret; + + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_64); + ret = do_ld8_mmu(env_cpu(env), addr, oi, ra, MMU_DATA_LOAD); + plugin_load_cb(env, addr, ret, 0, oi); + return ret; +} + +Int128 cpu_ld16_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi, uintptr_t ra) { + Int128 ret; + + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_128); + ret = do_ld16_mmu(env_cpu(env), addr, oi, ra); + plugin_load_cb(env, addr, int128_getlo(ret), int128_gethi(ret), oi); + return ret; +} + +/* + * Store helpers for cpu_ldst.h + */ + +static void plugin_store_cb(CPUArchState *env, vaddr addr, uint64_t value_low, uint64_t value_high, MemOpIdx oi) { + if (cpu_plugin_mem_cbs_enabled(env_cpu(env))) { + qemu_plugin_vcpu_mem_cb(env_cpu(env), addr, value_low, value_high, oi, QEMU_PLUGIN_MEM_W); + } +} + +void cpu_stb_mmu(CPUArchState *env, vaddr addr, uint8_t val, MemOpIdx oi, uintptr_t retaddr) { + helper_stb_mmu(env, addr, val, oi, retaddr); + plugin_store_cb(env, addr, val, 0, oi); +} + +void cpu_stw_mmu(CPUArchState *env, vaddr addr, uint16_t val, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_16); + do_st2_mmu(env_cpu(env), addr, val, oi, retaddr); + plugin_store_cb(env, addr, val, 0, oi); +} + +void cpu_stl_mmu(CPUArchState *env, vaddr addr, uint32_t val, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_32); + do_st4_mmu(env_cpu(env), addr, val, oi, retaddr); + plugin_store_cb(env, addr, val, 0, oi); +} + +void cpu_stq_mmu(CPUArchState *env, vaddr addr, uint64_t val, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_64); + do_st8_mmu(env_cpu(env), addr, val, oi, retaddr); + plugin_store_cb(env, addr, val, 0, oi); +} + +void cpu_st16_mmu(CPUArchState *env, vaddr addr, Int128 val, MemOpIdx oi, uintptr_t retaddr) { + tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_128); + do_st16_mmu(env_cpu(env), addr, val, oi, retaddr); + plugin_store_cb(env, addr, int128_getlo(val), int128_gethi(val), oi); +} diff --git a/libcpu/src/accel/tlb-bounds.h b/libcpu/src/accel/tlb-bounds.h new file mode 100644 index 000000000..bb0f011b1 --- /dev/null +++ b/libcpu/src/accel/tlb-bounds.h @@ -0,0 +1,13 @@ +/* + * softmmu size bounds + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifndef ACCEL_TCG_TLB_BOUNDS_H +#define ACCEL_TCG_TLB_BOUNDS_H + +#define CPU_TLB_DYN_MIN_BITS 6 +#define CPU_TLB_DYN_MAX_BITS (32 - TARGET_PAGE_BITS) +#define CPU_TLB_DYN_DEFAULT_BITS 8 + +#endif /* ACCEL_TCG_TLB_BOUNDS_H */ From c9a6e75183f28f92ff08679d428324a48d074eab Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:39:14 +0200 Subject: [PATCH 38/52] libtcg: imported tlb-common.h from QEMU v11.1.0 The file is the output of scripts/upgrade/normalize.sh, without any change. Nothing includes it yet. Co-Authored-By: Claude Opus 5.5 --- libtcg/include/tcg/exec/tlb-common.h | 56 ++++++++++++++++++++++++++++ libtcg/scripts/upgrade/mapping.tsv | 1 + 2 files changed, 57 insertions(+) create mode 100644 libtcg/include/tcg/exec/tlb-common.h diff --git a/libtcg/include/tcg/exec/tlb-common.h b/libtcg/include/tcg/exec/tlb-common.h new file mode 100644 index 000000000..03b5a8ffc --- /dev/null +++ b/libtcg/include/tcg/exec/tlb-common.h @@ -0,0 +1,56 @@ +/* + * Common definitions for the softmmu tlb + * + * Copyright (c) 2003 Fabrice Bellard + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ +#ifndef EXEC_TLB_COMMON_H +#define EXEC_TLB_COMMON_H 1 + +#define CPU_TLB_ENTRY_BITS (HOST_LONG_BITS == 32 ? 4 : 5) + +/* Minimalized TLB entry for use by TCG fast path. */ +typedef union CPUTLBEntry { + struct { + uintptr_t addr_read; + uintptr_t addr_write; + uintptr_t addr_code; + /* + * Addend to virtual address to get host address. IO accesses + * use the corresponding iotlb value. + */ + uintptr_t addend; + }; + /* + * Padding to get a power of two size, as well as index + * access to addr_{read,write,code}. + */ + uintptr_t addr_idx[(1 << CPU_TLB_ENTRY_BITS) / sizeof(uintptr_t)]; +} CPUTLBEntry; + +QEMU_BUILD_BUG_ON(sizeof(CPUTLBEntry) != (1 << CPU_TLB_ENTRY_BITS)); + +/* + * Data elements that are per MMU mode, accessed by the fast path. + * The structure is aligned to aid loading the pair with one insn. + */ +typedef struct CPUTLBDescFast { + /* Contains (n_entries - 1) << CPU_TLB_ENTRY_BITS */ + uintptr_t mask; + /* The array of tlb entries itself. */ + CPUTLBEntry *table; +} CPUTLBDescFast QEMU_ALIGNED(2 * sizeof(void *)); + +#endif /* EXEC_TLB_COMMON_H */ diff --git a/libtcg/scripts/upgrade/mapping.tsv b/libtcg/scripts/upgrade/mapping.tsv index d18b97ee6..952ce5f52 100644 --- a/libtcg/scripts/upgrade/mapping.tsv +++ b/libtcg/scripts/upgrade/mapping.tsv @@ -73,6 +73,7 @@ include/tcg/utils/cpu-float.h include/qemu/cpu-float.h include/tcg/utils/bswap.h include/qemu/bswap.h include/tcg/utils/target-info.h include/qemu/target-info.h include/tcg/exec/tswap.h include/exec/tswap.h +include/tcg/exec/tlb-common.h include/exec/tlb-common.h src/elf.h include/elf.h # Heavily reduced S2E-specific subsets, still v8.1.0-era: these are hand # written rather than vendored, so merge by hand, not mechanically. From 44e97a15b7112b2fdb43d5c7122a0c9e1e19c8b1 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:42:20 +0200 Subject: [PATCH 39/52] libcpu,libtcg: adapted the imported softmmu headers The includes point at the libcpu, libtcg and libutils headers. The TLB entry gains se_addend, the comparator gains the S2E flags, and the TLB size is pinned. cpu-mmu-index.h is hand written. Nothing compiles these files yet. Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/accel/cpu-ldst-common.h | 8 ++-- libcpu/include/cpu/accel/cpu-ldst.h | 7 ++-- libcpu/include/cpu/accel/cpu-mmu-index.h | 38 +++++++++++++++++ libcpu/include/cpu/accel/cpu-ops.h | 25 +++++++---- libcpu/include/cpu/accel/probe.h | 4 +- libcpu/include/cpu/exec/cputlb.h | 8 ++-- libcpu/include/cpu/exec/tlb-flags.h | 48 +++++++++++++++++++--- libcpu/src/accel/atomic_template.h | 2 - libcpu/src/accel/ldst_atomicity.c.inc | 4 +- libcpu/src/accel/tlb-bounds.h | 12 ++++-- libtcg/include/tcg/exec/tlb-common.h | 25 +++++++++++ 11 files changed, 146 insertions(+), 35 deletions(-) create mode 100644 libcpu/include/cpu/accel/cpu-mmu-index.h diff --git a/libcpu/include/cpu/accel/cpu-ldst-common.h b/libcpu/include/cpu/accel/cpu-ldst-common.h index d33b9a0e8..89170ca56 100644 --- a/libcpu/include/cpu/accel/cpu-ldst-common.h +++ b/libcpu/include/cpu/accel/cpu-ldst-common.h @@ -11,10 +11,10 @@ #error Can only include this header with TCG #endif -#include "exec/memopidx.h" -#include "exec/mmu-access-type.h" -#include "exec/vaddr.h" -#include "qemu/int128.h" +#include +#include +#include +#include uint8_t cpu_ldb_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); uint16_t cpu_ldw_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); diff --git a/libcpu/include/cpu/accel/cpu-ldst.h b/libcpu/include/cpu/accel/cpu-ldst.h index a22819c83..52edc3aae 100644 --- a/libcpu/include/cpu/accel/cpu-ldst.h +++ b/libcpu/include/cpu/accel/cpu-ldst.h @@ -65,10 +65,9 @@ #error Can only include this header with TCG #endif -#include "accel/tcg/cpu-ldst-common.h" -#include "accel/tcg/cpu-mmu-index.h" -#include "exec/abi_ptr.h" -#include "exec/cpu-common.h" +#include +#include +#include static inline uint32_t cpu_ldub_mmuidx_ra(CPUArchState *env, abi_ptr addr, int mmu_idx, uintptr_t ra) { MemOpIdx oi = make_memop_idx(MO_UB, mmu_idx); diff --git a/libcpu/include/cpu/accel/cpu-mmu-index.h b/libcpu/include/cpu/accel/cpu-mmu-index.h new file mode 100644 index 000000000..c6bd87d6c --- /dev/null +++ b/libcpu/include/cpu/accel/cpu-mmu-index.h @@ -0,0 +1,38 @@ +/// Copyright (C) 2026 Vitaly Chipounov +/// Copyrights of all contributions belong to their respective owners. +/// +/// This library is free software; you can redistribute it and/or +/// modify it under the terms of the GNU Library General Public +/// License as published by the Free Software Foundation; either +/// version 2 of the License, or (at your option) any later version. +/// +/// This library is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +/// Library General Public License for more details. +/// +/// You should have received a copy of the GNU Library General Public +/// License along with this library; if not, see . + +/// @file +/// Returns the MMU index of the current CPU mode. +/// +/// Upstream's header of the same name calls cpu->cc->tcg_ops->mmu_index(). +/// This version computes the index directly. The accessors of cpu-ldst.h +/// inline it into helpers that also run as bitcode inside KLEE, where the +/// tcg_ops table cannot be read (it is not registered as a KLEE object). + +#ifndef S2E_CPU_MMU_INDEX_H +#define S2E_CPU_MMU_INDEX_H + +#include + +/// @param cpu the CPU +/// @param ifetch true for a code fetch. x86 uses the same index for code and +/// data until the 11.1 frontend arrives. +/// @return the MMU index for the current privilege level +static inline int cpu_mmu_index(CPUState *cpu, bool ifetch) { + return x86_mmu_index(cpu_env(cpu)); +} + +#endif diff --git a/libcpu/include/cpu/accel/cpu-ops.h b/libcpu/include/cpu/accel/cpu-ops.h index 96898bb1c..09ac3e143 100644 --- a/libcpu/include/cpu/accel/cpu-ops.h +++ b/libcpu/include/cpu/accel/cpu-ops.h @@ -14,14 +14,23 @@ #error Can only include this header with TCG #endif -#include "accel/tcg/tb-cpu-state.h" -#include "exec/breakpoint.h" -#include "exec/hwaddr.h" -#include "exec/memattrs.h" -#include "exec/memop.h" -#include "exec/mmu-access-type.h" -#include "exec/vaddr.h" -#include "tcg/tcg-mo.h" +#include +#include +#include +#include +#include +#include + +/* S2E: libcpu's CPUState is hand-written (cpu/state.h) and only knows this + structure by name. TCGTBCPUState belongs to upstream's TB lookup, which is + not imported yet. */ +struct CPUState; +typedef struct CPUState CPUState; +struct CPUTLBEntryFull; +typedef struct CPUTLBEntryFull CPUTLBEntryFull; +typedef struct TranslationBlock TranslationBlock; +typedef struct TCGTBCPUState TCGTBCPUState; +typedef struct TCGCPUOps TCGCPUOps; struct TCGCPUOps { /** diff --git a/libcpu/include/cpu/accel/probe.h b/libcpu/include/cpu/accel/probe.h index 0ec468388..da2fe5a18 100644 --- a/libcpu/include/cpu/accel/probe.h +++ b/libcpu/include/cpu/accel/probe.h @@ -11,8 +11,8 @@ #error Can only include this header with TCG #endif -#include "exec/mmu-access-type.h" -#include "exec/vaddr.h" +#include +#include /** * probe_access: diff --git a/libcpu/include/cpu/exec/cputlb.h b/libcpu/include/cpu/exec/cputlb.h index ab095c3a3..3cdec1d2a 100644 --- a/libcpu/include/cpu/exec/cputlb.h +++ b/libcpu/include/cpu/exec/cputlb.h @@ -20,13 +20,11 @@ #ifndef CPUTLB_H #define CPUTLB_H -#include "exec/cpu-common.h" -#include "exec/hwaddr.h" -#include "exec/memattrs.h" -#include "exec/vaddr.h" +#include +#include +#include #ifndef CONFIG_USER_ONLY -#include "system/ram_addr.h" void tlb_reset_dirty(CPUState *cpu, uintptr_t start, uintptr_t length); void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length); diff --git a/libcpu/include/cpu/exec/tlb-flags.h b/libcpu/include/cpu/exec/tlb-flags.h index 016c5963c..9c4c04840 100644 --- a/libcpu/include/cpu/exec/tlb-flags.h +++ b/libcpu/include/cpu/exec/tlb-flags.h @@ -19,6 +19,8 @@ #ifndef TLB_FLAGS_H #define TLB_FLAGS_H +#include + /* * Flags returned for lookup of a TLB virtual address. */ @@ -54,7 +56,20 @@ /* Set if TLB entry is an IO callback. */ #define TLB_MMIO (1 << 4) -#define TLB_SLOW_FLAGS_MASK (TLB_BSWAP | TLB_WATCHPOINT | TLB_CHECK_ALIGNED | TLB_DISCARD_WRITE | TLB_MMIO) +#ifdef CONFIG_SYMBEX +/* + * S2E: set if the page is RAM that contains symbolic MMIO or DMA ranges. + * tlb_set_page_full() sets the flag when it fills the entry. This is the + * only bit that upstream leaves free here: the slow flags are merged with + * the comparator flags below, which start at bit 6. + */ +#define TLB_SYMB_MMIO (1 << 5) +#else +#define TLB_SYMB_MMIO 0 +#endif + +#define TLB_SLOW_FLAGS_MASK \ + (TLB_BSWAP | TLB_WATCHPOINT | TLB_CHECK_ALIGNED | TLB_DISCARD_WRITE | TLB_MMIO | TLB_SYMB_MMIO) /* * Flags stored in CPUTLBEntry.addr_idx[x]. @@ -64,17 +79,40 @@ */ /* Zero if TLB entry is valid. */ -#define TLB_INVALID_MASK (1 << 6) +#define TLB_INVALID_MASK (1 << 6) /* Set if TLB entry references a clean RAM page. */ -#define TLB_NOTDIRTY (1 << 7) +#define TLB_NOTDIRTY (1 << 7) /* Set if the slow path must be used; more flags in CPUTLBEntryFull. */ -#define TLB_FORCE_SLOW (1 << 8) +#define TLB_FORCE_SLOW (1 << 8) + +#ifdef CONFIG_SYMBEX +/* + * S2E flags. They live in the comparator, above upstream's flags and below + * TARGET_PAGE_BITS, so that libs2ecore can set and clear them with one write + * and the inline fast path fails while any of them is set. + */ + +/* Set if the page holds symbolic data. */ +#define TLB_SYMB (1 << 9) +/* Set on the write comparator if the KLEE object that backs the page is + shared with another state and must be copied before a store. */ +#define TLB_NOT_OURS (1 << 10) +/* Set if a plugin subscribed to memory access events. */ +#define TLB_MEM_TRACE (1 << 11) + +#define TLB_SE_FLAGS_MASK (TLB_SYMB | TLB_NOT_OURS | TLB_MEM_TRACE) +#else +#define TLB_SE_FLAGS_MASK 0 +#endif /* * Use this mask to check interception with an alignment mask * in a TCG backend. */ -#define TLB_FLAGS_MASK (TLB_INVALID_MASK | TLB_NOTDIRTY | TLB_FORCE_SLOW) +#define TLB_FLAGS_MASK (TLB_INVALID_MASK | TLB_NOTDIRTY | TLB_FORCE_SLOW | TLB_SE_FLAGS_MASK) + +/* S2E: every comparator flag must lie below the page number. */ +QEMU_BUILD_BUG_ON(TLB_FLAGS_MASK >= (1 << 12)); /* The two sets of flags must not overlap. */ QEMU_BUILD_BUG_ON(TLB_FLAGS_MASK &TLB_SLOW_FLAGS_MASK); diff --git a/libcpu/src/accel/atomic_template.h b/libcpu/src/accel/atomic_template.h index 8516e6236..d29fd7e26 100644 --- a/libcpu/src/accel/atomic_template.h +++ b/libcpu/src/accel/atomic_template.h @@ -18,8 +18,6 @@ * License along with this library; if not, see . */ -#include "qemu/plugin.h" - #if DATA_SIZE == 16 #define SUFFIX o #define DATA_TYPE Int128 diff --git a/libcpu/src/accel/ldst_atomicity.c.inc b/libcpu/src/accel/ldst_atomicity.c.inc index 5f8652f2b..e56ae6156 100644 --- a/libcpu/src/accel/ldst_atomicity.c.inc +++ b/libcpu/src/accel/ldst_atomicity.c.inc @@ -9,8 +9,8 @@ * See the COPYING file in the top-level directory. */ -#include "host/load-extract-al16-al8.h.inc" -#include "host/store-insert-al16.h.inc" +#include +#include /** * required_atomicity: diff --git a/libcpu/src/accel/tlb-bounds.h b/libcpu/src/accel/tlb-bounds.h index bb0f011b1..3dace3743 100644 --- a/libcpu/src/accel/tlb-bounds.h +++ b/libcpu/src/accel/tlb-bounds.h @@ -6,8 +6,14 @@ #ifndef ACCEL_TCG_TLB_BOUNDS_H #define ACCEL_TCG_TLB_BOUNDS_H -#define CPU_TLB_DYN_MIN_BITS 6 -#define CPU_TLB_DYN_MAX_BITS (32 - TARGET_PAGE_BITS) -#define CPU_TLB_DYN_DEFAULT_BITS 8 +/* + * S2E: the three bounds are equal, which pins the size of the TLB. The tables + * are static arrays that libs2ecore registers once with KLEE, so they cannot + * be reallocated. tlb_mmu_resize_locked() then always finds that the new + * size equals the old one and returns. + */ +#define CPU_TLB_DYN_MIN_BITS CPU_TLB_BITS +#define CPU_TLB_DYN_MAX_BITS CPU_TLB_BITS +#define CPU_TLB_DYN_DEFAULT_BITS CPU_TLB_BITS #endif /* ACCEL_TCG_TLB_BOUNDS_H */ diff --git a/libtcg/include/tcg/exec/tlb-common.h b/libtcg/include/tcg/exec/tlb-common.h index 03b5a8ffc..bd0da36e6 100644 --- a/libtcg/include/tcg/exec/tlb-common.h +++ b/libtcg/include/tcg/exec/tlb-common.h @@ -19,7 +19,19 @@ #ifndef EXEC_TLB_COMMON_H #define EXEC_TLB_COMMON_H 1 +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef CONFIG_SYMBEX +/* S2E: se_addend makes the entry larger than 32 bytes. */ +#define CPU_TLB_ENTRY_BITS 6 +#else #define CPU_TLB_ENTRY_BITS (HOST_LONG_BITS == 32 ? 4 : 5) +#endif /* Minimalized TLB entry for use by TCG fast path. */ typedef union CPUTLBEntry { @@ -32,6 +44,14 @@ typedef union CPUTLBEntry { * use the corresponding iotlb value. */ uintptr_t addend; +#ifdef CONFIG_SYMBEX + /* + * S2E: host address of the page in the concrete buffer of the KLEE + * object that backs it in the current state, minus the guest address. + * Natively executed code uses it in place of addend. + */ + uintptr_t se_addend; +#endif }; /* * Padding to get a power of two size, as well as index @@ -40,6 +60,7 @@ typedef union CPUTLBEntry { uintptr_t addr_idx[(1 << CPU_TLB_ENTRY_BITS) / sizeof(uintptr_t)]; } CPUTLBEntry; +/* S2E: this also fails if se_addend does not fit in CPU_TLB_ENTRY_BITS. */ QEMU_BUILD_BUG_ON(sizeof(CPUTLBEntry) != (1 << CPU_TLB_ENTRY_BITS)); /* @@ -53,4 +74,8 @@ typedef struct CPUTLBDescFast { CPUTLBEntry *table; } CPUTLBDescFast QEMU_ALIGNED(2 * sizeof(void *)); +#ifdef __cplusplus +} +#endif + #endif /* EXEC_TLB_COMMON_H */ From 898b13a24e703840e0e925e78a64b186f8990ef2 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:42:20 +0200 Subject: [PATCH 40/52] libcpu: added the S2E deviations to cputlb.c Each deviation carries a comment that starts with "S2E:". The glue that stands in for the QEMU code that is not ported is in src/s2e/cputlb-deps.h, and the symbolic execution half is in the two cputlb-symbex files. Nothing compiles these files yet. Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/se_softmmu.h | 75 ++++ libcpu/src/accel/cputlb.c | 225 +++++++---- libcpu/src/s2e/cputlb-deps.h | 509 ++++++++++++++++++++++++ libcpu/src/s2e/cputlb-symbex-ldst.c.inc | 128 ++++++ libcpu/src/s2e/cputlb-symbex.c.inc | 232 +++++++++++ 5 files changed, 1099 insertions(+), 70 deletions(-) create mode 100644 libcpu/include/cpu/se_softmmu.h create mode 100644 libcpu/src/s2e/cputlb-deps.h create mode 100644 libcpu/src/s2e/cputlb-symbex-ldst.c.inc create mode 100644 libcpu/src/s2e/cputlb-symbex.c.inc diff --git a/libcpu/include/cpu/se_softmmu.h b/libcpu/include/cpu/se_softmmu.h new file mode 100644 index 000000000..13eac5874 --- /dev/null +++ b/libcpu/include/cpu/se_softmmu.h @@ -0,0 +1,75 @@ +/// Copyright (C) 2026 Vitaly Chipounov +/// Copyrights of all contributions belong to their respective owners. +/// +/// This library is free software; you can redistribute it and/or +/// modify it under the terms of the GNU Library General Public +/// License as published by the Free Software Foundation; either +/// version 2 of the License, or (at your option) any later version. +/// +/// This library is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +/// Library General Public License for more details. +/// +/// You should have received a copy of the GNU Library General Public +/// License along with this library; if not, see . + +/// @file +/// The native softmmu functions that libs2ecore uses. +/// +/// The softmmu (src/accel/cputlb.c) is compiled natively and as LLVM bitcode. +/// The bitcode copy keeps the access path and calls the native copy for +/// everything that reaches device models, the dirty bitmap or the translation +/// block cache. libs2ecore registers these native functions with KLEE so that +/// the bitcode can call them, and its own memory access handlers +/// (MMUFunctionHandlers.cpp) call them too. + +#ifndef S2E_CPU_SE_SOFTMMU_H +#define S2E_CPU_SE_SOFTMMU_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/// Records a store to a page that may hold translated code, and invalidates +/// the translation blocks that the store overwrites. +void notdirty_write(CPUState *cpu, vaddr mem_vaddr, unsigned size, CPUTLBEntryFull *full, uintptr_t retaddr); + +/// Reads up to 8 bytes from a device, most significant byte first, and +/// appends them to ret_be. +uint64_t do_ld_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, int mmu_idx, + MMUAccessType type, uintptr_t ra); + +/// Writes the low size bytes of val_le to a device, least significant byte +/// first, and returns the remaining bytes. +uint64_t do_st_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t val_le, vaddr addr, int size, int mmu_idx, + uintptr_t ra); + +/// Raises a debug exception if the access hits a watchpoint. +void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len, MemTxAttrs attrs, int flags, uintptr_t ra); + +/// Fills the TLB for one page, or raises the guest exception if the access +/// faults and probe is false. +bool x86_cpu_tlb_fill(CPUState *cs, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, bool probe, + uintptr_t retaddr); + +/// The native guest memory accessors. ra is 0 when the caller is not +/// generated code. +uint8_t cpu_ldb_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); +uint16_t cpu_ldw_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); +uint32_t cpu_ldl_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); +uint64_t cpu_ldq_mmu(CPUArchState *env, vaddr ptr, MemOpIdx oi, uintptr_t ra); + +void cpu_stb_mmu(CPUArchState *env, vaddr ptr, uint8_t val, MemOpIdx oi, uintptr_t ra); +void cpu_stw_mmu(CPUArchState *env, vaddr ptr, uint16_t val, MemOpIdx oi, uintptr_t ra); +void cpu_stl_mmu(CPUArchState *env, vaddr ptr, uint32_t val, MemOpIdx oi, uintptr_t ra); +void cpu_stq_mmu(CPUArchState *env, vaddr ptr, uint64_t val, MemOpIdx oi, uintptr_t ra); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libcpu/src/accel/cputlb.c b/libcpu/src/accel/cputlb.c index dafa9368d..5467a897e 100644 --- a/libcpu/src/accel/cputlb.c +++ b/libcpu/src/accel/cputlb.c @@ -17,42 +17,13 @@ * License along with this library; if not, see . */ -#include "exec/cputlb.h" -#include "accel/tcg/cpu-ldst-common.h" -#include "accel/tcg/cpu-loop.h" -#include "accel/tcg/cpu-mmu-index.h" -#include "accel/tcg/cpu-ops.h" -#include "accel/tcg/iommu.h" -#include "accel/tcg/probe.h" -#include "exec/helper-proto-common.h" -#include "exec/log.h" -#include "exec/mmu-access-type.h" -#include "exec/page-protection.h" -#include "exec/tb-flush.h" -#include "exec/tlb-common.h" -#include "exec/tlb-flags.h" -#include "exec/vaddr.h" -#include "internal-common.h" -#include "qemu/atomic.h" -#include "qemu/atomic128.h" -#include "qemu/error-report.h" -#include "qemu/main-loop.h" -#include "qemu/osdep.h" -#include "qemu/target-info.h" -#include "system-page-protection.h" -#include "system/memory.h" -#include "system/physmem.h" -#include "system/ramblock.h" -#include "tb-hash.h" -#include "tb-internal.h" -#include "tcg/tcg.h" +/* + * S2E: the include block is replaced. cputlb-deps.h stands in for the QEMU + * subsystems that libcpu does not have (memory API, dirty tracking, work + * queues, plugins, tracing). + */ +#include "s2e/cputlb-deps.h" #include "tlb-bounds.h" -#include "trace.h" -#ifdef CONFIG_PLUGIN -#include "qemu/plugin-memory.h" -#endif -#include "backend-ldst.h" -#include "tcg/tcg-ldst.h" /* DEBUG defines, enable DEBUG_TLB_LOG to log to the CPU_LOG_MMU target */ /* #define DEBUG_TLB */ @@ -120,7 +91,8 @@ static inline uint64_t tlb_addr_write(const CPUTLBEntry *entry) { static inline uintptr_t tlb_index(CPUState *cpu, uintptr_t mmu_idx, vaddr addr) { uintptr_t size_mask = cpu_tlb_fast(cpu, mmu_idx)->mask >> CPU_TLB_ENTRY_BITS; - return (addr >> TARGET_PAGE_BITS) & size_mask; + /* S2E: the bitcode build forks on the page number, see cputlb-deps.h. */ + return SE_CONCRETE_PAGE(addr >> TARGET_PAGE_BITS) & size_mask; } /* Find the TLB entry corresponding to the mmu_idx + address pair. */ @@ -128,23 +100,18 @@ static inline CPUTLBEntry *tlb_entry(CPUState *cpu, uintptr_t mmu_idx, vaddr add return &cpu_tlb_fast(cpu, mmu_idx)->table[tlb_index(cpu, mmu_idx, addr)]; } +#ifndef SYMBEX_LLVM_LIB /* S2E: native only, see cputlb-deps.h */ static void tlb_window_reset(CPUTLBDesc *desc, int64_t ns, size_t max_entries) { desc->window_begin_ns = ns; desc->window_max_entries = max_entries; } static void tb_jmp_cache_clear_page(CPUState *cpu, vaddr page_addr) { - CPUJumpCache *jc = cpu->tb_jmp_cache; - int i, i0; - - if (unlikely(!jc)) { - return; - } + /* S2E: the jump cache is still QEMU 1.0's array of TB pointers in neg. + Upstream's CPUJumpCache arrives with cpu-exec.c. */ + unsigned int i0 = tb_jmp_cache_hash_page(page_addr); - i0 = tb_jmp_cache_hash_page(page_addr); - for (i = 0; i < TB_JMP_PAGE_SIZE; i++) { - qatomic_set(&jc->array[i0 + i].tb, NULL); - } + memset(&cpu->neg.tb_jmp_cache[i0], 0, TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *)); } /** @@ -273,6 +240,9 @@ static void tlb_flush_one_mmuidx_locked(CPUState *cpu, int mmu_idx, int64_t now) CPUTLBDesc *desc = &cpu->neg.tlb.d[mmu_idx]; CPUTLBDescFast *fast = cpu_tlb_fast(cpu, mmu_idx); + /* S2E: libs2ecore drops its references to the entries of this index. */ + se_tlb_drop_mmuidx(cpu, mmu_idx); + tlb_mmu_resize_locked(desc, fast, now); tlb_mmu_flush_locked(desc, fast); } @@ -283,8 +253,11 @@ static void tlb_mmu_init(CPUTLBDesc *desc, CPUTLBDescFast *fast, int64_t now) { tlb_window_reset(desc, now, 0); desc->n_used_entries = 0; fast->mask = (n_entries - 1) << CPU_TLB_ENTRY_BITS; - fast->table = g_new(CPUTLBEntry, n_entries); - desc->fulltlb = g_new(CPUTLBEntryFull, n_entries); + /* S2E: the tables are static arrays inside neg, so that the KLEE object + registered over neg covers them. tlb-bounds.h pins their size. */ + QEMU_BUILD_BUG_ON(ARRAY_SIZE(desc->se_table) != (1 << CPU_TLB_DYN_DEFAULT_BITS)); + fast->table = desc->se_table; + desc->fulltlb = desc->se_fulltlb; tlb_mmu_flush_locked(desc, fast); } @@ -318,8 +291,9 @@ void tlb_destroy(CPUState *cpu) { CPUTLBDesc *desc = &cpu->neg.tlb.d[i]; CPUTLBDescFast *fast = cpu_tlb_fast(cpu, i); - g_free(fast->table); - g_free(desc->fulltlb); + /* S2E: the tables are static (tlb_mmu_init), there is nothing to free. */ + fast->table = NULL; + desc->fulltlb = NULL; } } @@ -345,6 +319,11 @@ static void tlb_flush_by_mmuidx_async_work(CPUState *cpu, run_on_cpu_data data) MMUIdxMap all_dirty, work, to_clean; int64_t now = get_clock_realtime(); + /* S2E: no flush while libs2ecore switches states, see cputlb-deps.h. */ + if (se_tlb_flush_disabled()) { + return; + } + assert_cpu_is_self(cpu); tlb_debug("mmu_idx:0x%04" PRIx16 "\n", asked); @@ -460,6 +439,10 @@ static void tlb_flush_page_locked(CPUState *cpu, int midx, vaddr page) { tlb_debug("forcing full flush midx %d (%016" VADDR_PRIx "/%016" VADDR_PRIx ")\n", midx, lp_addr, lp_mask); tlb_flush_one_mmuidx_locked(cpu, midx, get_clock_realtime()); } else { + /* S2E: libs2ecore drops its reference before the entry is cleared. */ + if (tlb_hit_page_anyprot(tlb_entry(cpu, midx, page), page)) { + se_tlb_drop_entry(cpu, midx, tlb_index(cpu, midx, page)); + } if (tlb_flush_entry_locked(tlb_entry(cpu, midx, page), page)) { tlb_n_used_entries_dec(cpu, midx); } @@ -479,6 +462,11 @@ static void tlb_flush_page_locked(CPUState *cpu, int midx, vaddr page) { static void tlb_flush_page_by_mmuidx_async_0(CPUState *cpu, vaddr addr, MMUIdxMap idxmap) { int mmu_idx; + /* S2E: no flush while libs2ecore switches states, see cputlb-deps.h. */ + if (se_tlb_flush_disabled()) { + return; + } + assert_cpu_is_self(cpu); tlb_debug("page addr: %016" VADDR_PRIx " mmu_map:0x%x\n", addr, idxmap); @@ -632,6 +620,10 @@ static void tlb_flush_range_locked(CPUState *cpu, int midx, vaddr addr, vaddr le vaddr page = addr + i; CPUTLBEntry *entry = tlb_entry(cpu, midx, page); + /* S2E: libs2ecore drops its reference before the entry is cleared. */ + if (tlb_hit_page_mask_anyprot(entry, page, mask)) { + se_tlb_drop_entry(cpu, midx, tlb_index(cpu, midx, page)); + } if (tlb_flush_entry_mask_locked(entry, page, mask)) { tlb_n_used_entries_dec(cpu, midx); } @@ -649,6 +641,11 @@ typedef struct { static void tlb_flush_range_by_mmuidx_async_0(CPUState *cpu, TLBFlushRangeData d) { int mmu_idx; + /* S2E: no flush while libs2ecore switches states, see cputlb-deps.h. */ + if (se_tlb_flush_disabled()) { + return; + } + assert_cpu_is_self(cpu); tlb_debug("range: %016" VADDR_PRIx "/%u+%016" VADDR_PRIx " mmu_map:0x%x\n", d.addr, d.bits, d.len, d.idxmap); @@ -1012,12 +1009,12 @@ void tlb_set_page_full(CPUState *cpu, int mmu_idx, vaddr addr, CPUTLBEntryFull * * different page; otherwise just overwrite the stale data. */ if (!tlb_hit_page_anyprot(te, addr_page) && !tlb_entry_is_empty(te)) { - unsigned vidx = desc->vindex++ % CPU_VTLB_SIZE; - CPUTLBEntry *tv = &desc->vtable[vidx]; - - /* Evict the old entry into the victim tlb. */ - copy_tlb_helper_locked(tv, te); - desc->vfulltlb[vidx] = desc->fulltlb[index]; + /* + * S2E: the victim TLB is disabled, the old entry is dropped. libs2ecore + * records where each KLEE object is referenced in the TLB and cannot + * follow an entry that moves. The victim table stays empty, so + * victim_tlb_hit() never finds anything. + */ tlb_n_used_entries_dec(cpu, mmu_idx); } @@ -1035,6 +1032,10 @@ void tlb_set_page_full(CPUState *cpu, int mmu_idx, vaddr addr, CPUTLBEntryFull * * subtract here is that of the page base, and not the same as the * vaddr we add back in io_prepare()/get_page_addr_code(). */ + /* S2E: libs2ecore drops its reference to the entry being replaced. This + must come first: the reference is found through the old full entry. */ + se_tlb_drop_entry(cpu, mmu_idx, index); + desc->fulltlb[index] = *full; full = &desc->fulltlb[index]; full->xlat_offset = iotlb - addr_page; @@ -1046,6 +1047,9 @@ void tlb_set_page_full(CPUState *cpu, int mmu_idx, vaddr addr, CPUTLBEntryFull * tlb_set_compare(full, &tn, addr_page, read_flags, MMU_INST_FETCH, prot & PAGE_EXEC); + /* S2E: flags for loads and stores only, the code comparator is set. */ + se_tlb_fill_flags(paddr_page, &read_flags, &write_flags); + if (wp_flags & BP_MEM_READ) { read_flags |= TLB_WATCHPOINT; } @@ -1061,6 +1065,11 @@ void tlb_set_page_full(CPUState *cpu, int mmu_idx, vaddr addr, CPUTLBEntryFull * copy_tlb_helper_locked(te, &tn); tlb_n_used_entries_inc(cpu, mmu_idx); + + /* S2E: libs2ecore records the KLEE object behind the page and completes + the entry (se_addend, TLB_SYMB, TLB_NOT_OURS). */ + se_tlb_set_entry(cpu, mmu_idx, addr_page, (is_ram || is_romd) ? addend : 0); + qemu_spin_unlock(&tlb->c.lock); } @@ -1075,6 +1084,7 @@ void tlb_set_page_with_attrs(CPUState *cpu, vaddr addr, hwaddr paddr, MemTxAttrs void tlb_set_page(CPUState *cpu, vaddr addr, hwaddr paddr, int prot, int mmu_idx, vaddr size) { tlb_set_page_with_attrs(cpu, addr, paddr, MEMTXATTRS_UNSPECIFIED, prot, mmu_idx, size); } +#endif /* !SYMBEX_LLVM_LIB */ /** * tlb_hit_page: return true if page aligned @addr is a hit against the @@ -1105,10 +1115,12 @@ static inline bool tlb_hit(uint64_t tlb_addr, vaddr addr) { */ static bool tlb_fill_align(CPUState *cpu, vaddr addr, MMUAccessType type, int mmu_idx, MemOp memop, int size, bool probe, uintptr_t ra) { + /* S2E: SE_TCG_HAS_OP() and SE_TCG_OP() select the bitcode copies of the + target hooks in the bitcode build, see cputlb-deps.h. */ const TCGCPUOps *ops = cpu->cc->tcg_ops; CPUTLBEntryFull full; - if (ops->tlb_fill_align) { + if (SE_TCG_HAS_OP(ops, tlb_fill_align)) { if (ops->tlb_fill_align(cpu, &full, addr, type, mmu_idx, memop, size, probe, ra)) { tlb_set_page_full(cpu, mmu_idx, addr, &full); return true; @@ -1116,9 +1128,9 @@ static bool tlb_fill_align(CPUState *cpu, vaddr addr, MMUAccessType type, int mm } else { /* Legacy behaviour is alignment before paging. */ if (addr & ((1u << memop_alignment_bits(memop)) - 1)) { - ops->do_unaligned_access(cpu, addr, type, mmu_idx, ra); + SE_TCG_OP(cpu, do_unaligned_access)(cpu, addr, type, mmu_idx, ra); } - if (ops->tlb_fill(cpu, addr, size, type, mmu_idx, probe, ra)) { + if (SE_TCG_OP(cpu, tlb_fill)(cpu, addr, size, type, mmu_idx, probe, ra)) { return true; } } @@ -1128,9 +1140,10 @@ static bool tlb_fill_align(CPUState *cpu, vaddr addr, MMUAccessType type, int mm static inline void cpu_unaligned_access(CPUState *cpu, vaddr addr, MMUAccessType access_type, int mmu_idx, uintptr_t retaddr) { - cpu->cc->tcg_ops->do_unaligned_access(cpu, addr, access_type, mmu_idx, retaddr); + SE_TCG_OP(cpu, do_unaligned_access)(cpu, addr, access_type, mmu_idx, retaddr); /* S2E, see tlb_fill_align() */ } +#ifndef SYMBEX_LLVM_LIB /* S2E: native only, see cputlb-deps.h */ static MemoryRegionSection *io_prepare(hwaddr *out_offset, CPUState *cpu, CPUTLBEntryFull *full, vaddr addr, uintptr_t retaddr) { MemoryRegionSection *section; @@ -1189,7 +1202,7 @@ static bool victim_tlb_hit(CPUState *cpu, size_t mmu_idx, size_t index, MMUAcces return false; } -static void notdirty_write(CPUState *cpu, vaddr mem_vaddr, unsigned size, CPUTLBEntryFull *full, uintptr_t retaddr) { +SE_NATIVE void notdirty_write(CPUState *cpu, vaddr mem_vaddr, unsigned size, CPUTLBEntryFull *full, uintptr_t retaddr) { ram_addr_t ram_addr = mem_vaddr + full->xlat_offset; trace_memory_notdirty_write_access(mem_vaddr, ram_addr, size); @@ -1249,6 +1262,17 @@ static int probe_access_internal(CPUState *cpu, vaddr addr, int fault_size, MMUA *pfull = full = &cpu->neg.tlb.d[mmu_idx].fulltlb[index]; flags |= full->slow_flags[access_type]; + /* + * S2E: a code page that carries S2E flags is still RAM that code can be + * translated from. libs2ecore sets TLB_SYMB on the code comparator so that + * the code fetch functions concretize symbolic code bytes; without this, + * get_page_addr_code_hostp() would refuse every code page that holds + * symbolic data. + */ + if (access_type == MMU_INST_FETCH) { + flags &= ~(TLB_SE_FLAGS_MASK | TLB_SYMB_MMIO); + } + /* Fold all "mmio-like" bits into TLB_MMIO. This is not RAM. */ if (unlikely(flags & ~(TLB_WATCHPOINT | TLB_NOTDIRTY | TLB_CHECK_ALIGNED)) || (access_type != MMU_INST_FETCH && force_mmio)) { @@ -1387,6 +1411,7 @@ tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr, void **ho return qemu_ram_addr_from_host_nofail(p); } +#endif /* !SYMBEX_LLVM_LIB */ /* Load/store with atomicity primitives. */ #include "ldst_atomicity.c.inc" @@ -1449,6 +1474,9 @@ typedef struct MMULookupLocals { int mmu_idx; } MMULookupLocals; +/* S2E: se_mmu_resolve(), and plain load and store primitives. */ +#include "s2e/cputlb-symbex.c.inc" + /** * mmu_lookup1: translate one page * @cpu: generic cpu state @@ -1499,7 +1527,13 @@ static bool mmu_lookup1(CPUState *cpu, MMULookupPageData *data, MemOp memop, int data->full = full; data->flags = flags; /* Compute haddr speculatively; depending on flags it might be invalid. */ +#if defined(CONFIG_SYMBEX_MP) && !defined(SYMBEX_LLVM_LIB) + /* S2E: natively executed code accesses the concrete buffer of the KLEE + object that backs the page in the current state. */ + data->haddr = (void *) ((uintptr_t) addr + entry->se_addend); +#else data->haddr = (void *) ((uintptr_t) addr + entry->addend); +#endif return maybe_resized; } @@ -1557,6 +1591,14 @@ static bool mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMU tcg_debug_assert(l->mmu_idx < NB_MMU_MODES); +#if defined(SYMBEX_LLVM_LIB) + /* S2E: with fork-on-symbolic-address, a symbolic address is replaced by + one of its values and the state forks on the others. */ + if (*g_sqi.mode.fork_on_symbolic_address) { + addr = tcg_llvm_fork_and_concretize(addr, 0, (target_ulong) -1, 0); + } +#endif + l->page[0].addr = addr; l->page[0].size = memop_size(l->memop); l->page[1].addr = 0; @@ -1581,7 +1623,7 @@ static bool mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMU int size0 = addr1 - addr; l->page[1].size = l->page[0].size - size0; l->page[0].size = size0; - l->page[1].addr = cpu->cc->tcg_ops->pointer_wrap(cpu, l->mmu_idx, addr1, addr); + l->page[1].addr = SE_TCG_OP(cpu, pointer_wrap)(cpu, l->mmu_idx, addr1, addr); /* S2E, see tlb_fill_align() */ /* * Lookup and recognize exceptions from the second page. @@ -1607,9 +1649,13 @@ static bool mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMU tcg_debug_assert((flags & TLB_BSWAP) == 0); } + /* S2E: symbolic data, shared KLEE objects and symbolic hardware. */ + se_mmu_resolve(cpu, l, type, ra); + return crosspage; } +#ifndef SYMBEX_LLVM_LIB /* S2E: native only, see cputlb-deps.h */ /* * Probe for an atomic operation. Do not allow unaligned operations, * or io operations to proceed. Return the host address. @@ -1713,6 +1759,7 @@ static void *atomic_mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi, int size, stop_the_world: cpu_loop_exit_atomic(cpu, retaddr); } +#endif /* !SYMBEX_LLVM_LIB */ /* * Load Helpers @@ -1731,6 +1778,7 @@ static void *atomic_mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi, int size, * We don't bother with this widened value for SOFTMMU_CODE_ACCESS. */ +#ifndef SYMBEX_LLVM_LIB /* S2E: native only, see cputlb-deps.h */ /** * do_ld_mmio_beN: * @cpu: generic cpu state @@ -1775,14 +1823,20 @@ static uint64_t int_ld_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t r return ret_be; } -static uint64_t do_ld_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, int mmu_idx, - MMUAccessType type, uintptr_t ra) { +SE_NATIVE uint64_t do_ld_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, + int mmu_idx, MMUAccessType type, uintptr_t ra) { MemoryRegionSection *section; MemoryRegion *mr; hwaddr mr_offset; tcg_debug_assert(size > 0 && size <= 8); + /* S2E: a RAM page that natively executed code cannot access directly is + routed here by se_mmu_resolve() and accessed through libs2ecore. */ + if (se_ram_ld_beN(cpu, full, &ret_be, addr, size, mmu_idx)) { + return ret_be; + } + section = io_prepare(&mr_offset, cpu, full, addr, ra); mr = section->mr; @@ -1790,8 +1844,8 @@ static uint64_t do_ld_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t re return int_ld_mmio_beN(cpu, full, ret_be, addr, size, mmu_idx, type, ra, mr, mr_offset); } -static Int128 do_ld16_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, int mmu_idx, - uintptr_t ra) { +SE_NATIVE Int128 do_ld16_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, + int mmu_idx, uintptr_t ra) { MemoryRegionSection *section; MemoryRegion *mr; hwaddr mr_offset; @@ -1799,6 +1853,14 @@ static Int128 do_ld16_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t re tcg_debug_assert(size > 8 && size <= 16); + /* S2E: a RAM page that natively executed code cannot access directly is + routed here by se_mmu_resolve() and accessed through libs2ecore. */ + if (se_ram_ld_beN(cpu, full, &ret_be, addr, size - 8, mmu_idx)) { + b = 0; + se_ram_ld_beN(cpu, full, &b, addr + size - 8, 8, mmu_idx); + return int128_make128(b, ret_be); + } + section = io_prepare(&mr_offset, cpu, full, addr, ra); mr = section->mr; @@ -1807,6 +1869,7 @@ static Int128 do_ld16_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t re b = int_ld_mmio_beN(cpu, full, ret_be, addr + size - 8, 8, mmu_idx, MMU_DATA_LOAD, ra, mr, mr_offset + size - 8); return int128_make128(b, a); } +#endif /* !SYMBEX_LLVM_LIB */ /** * do_ld_bytes_beN @@ -2202,6 +2265,7 @@ static Int128 do_ld16_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra) * Store Helpers */ +#ifndef SYMBEX_LLVM_LIB /* S2E: native only, see cputlb-deps.h */ /** * do_st_mmio_leN: * @cpu: generic cpu state @@ -2246,14 +2310,20 @@ static uint64_t int_st_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t v return val_le; } -static uint64_t do_st_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t val_le, vaddr addr, int size, int mmu_idx, - uintptr_t ra) { +SE_NATIVE uint64_t do_st_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t val_le, vaddr addr, int size, + int mmu_idx, uintptr_t ra) { MemoryRegionSection *section; hwaddr mr_offset; MemoryRegion *mr; tcg_debug_assert(size > 0 && size <= 8); + /* S2E: a RAM page that natively executed code cannot access directly is + routed here by se_mmu_resolve() and accessed through libs2ecore. */ + if (se_ram_st_leN(cpu, full, &val_le, addr, size, mmu_idx)) { + return val_le; + } + section = io_prepare(&mr_offset, cpu, full, addr, ra); mr = section->mr; @@ -2261,14 +2331,23 @@ static uint64_t do_st_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t va return int_st_mmio_leN(cpu, full, val_le, addr, size, mmu_idx, ra, mr, mr_offset); } -static uint64_t do_st16_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, Int128 val_le, vaddr addr, int size, int mmu_idx, - uintptr_t ra) { +SE_NATIVE uint64_t do_st16_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, Int128 val_le, vaddr addr, int size, + int mmu_idx, uintptr_t ra) { MemoryRegionSection *section; MemoryRegion *mr; hwaddr mr_offset; tcg_debug_assert(size > 8 && size <= 16); + /* S2E: a RAM page that natively executed code cannot access directly is + routed here by se_mmu_resolve() and accessed through libs2ecore. */ + uint64_t se_lo = int128_getlo(val_le); + if (se_ram_st_leN(cpu, full, &se_lo, addr, 8, mmu_idx)) { + uint64_t se_hi = int128_gethi(val_le); + se_ram_st_leN(cpu, full, &se_hi, addr + 8, size - 8, mmu_idx); + return se_hi; + } + section = io_prepare(&mr_offset, cpu, full, addr, ra); mr = section->mr; @@ -2276,6 +2355,7 @@ static uint64_t do_st16_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, Int128 va int_st_mmio_leN(cpu, full, int128_getlo(val_le), addr, 8, mmu_idx, ra, mr, mr_offset); return int_st_mmio_leN(cpu, full, int128_gethi(val_le), addr + 8, size - 8, mmu_idx, ra, mr, mr_offset + 8); } +#endif /* !SYMBEX_LLVM_LIB */ /* * Wrapper for the above. @@ -2552,8 +2632,12 @@ static void do_st16_mmu(CPUState *cpu, vaddr addr, Int128 val, MemOpIdx oi, uint } } +/* S2E: memory tracing wrappers around do_{ld,st}{1,2,4,8}_mmu(). */ +#include "s2e/cputlb-symbex-ldst.c.inc" + #include "ldst_common.c.inc" +#ifndef SYMBEX_LLVM_LIB /* S2E: native only, see cputlb-deps.h */ /* * First set of functions passes in OI and RETADDR. * This makes them callable from other helpers. @@ -2581,6 +2665,7 @@ static void do_st16_mmu(CPUState *cpu, vaddr addr, Int128 val, MemOpIdx oi, uint #define DATA_SIZE 16 #include "atomic_template.h" #endif +#endif /* !SYMBEX_LLVM_LIB */ /* Code access functions. */ diff --git a/libcpu/src/s2e/cputlb-deps.h b/libcpu/src/s2e/cputlb-deps.h new file mode 100644 index 000000000..71a8aa34c --- /dev/null +++ b/libcpu/src/s2e/cputlb-deps.h @@ -0,0 +1,509 @@ +/// Copyright (C) 2026 Vitaly Chipounov +/// Copyrights of all contributions belong to their respective owners. +/// +/// This library is free software; you can redistribute it and/or +/// modify it under the terms of the GNU Library General Public +/// License as published by the Free Software Foundation; either +/// version 2 of the License, or (at your option) any later version. +/// +/// This library is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +/// Library General Public License for more details. +/// +/// You should have received a copy of the GNU Library General Public +/// License along with this library; if not, see . + +/// @file +/// Everything that src/accel/cputlb.c needs from the rest of QEMU and that +/// libcpu does not have yet. +/// +/// cputlb.c is upstream's softmmu. It expects QEMU's memory API, its physical +/// memory dirty tracking, its multi-CPU work queues, its plugin interface and +/// its trace points. This header provides each of them in the smallest form +/// that keeps the imported file close to upstream's text: +/// +/// - The memory API is a set of inline functions over MemoryDesc +/// (cpu/memory.h). A region is either RAM, backed by a MemoryDesc, or MMIO, +/// which is forwarded to cpu_mmio_read() and cpu_mmio_write(). +/// - Dirty tracking maps onto the one-byte-per-page mask of exec-ram.h. +/// - libcpu has one vCPU, so work that upstream queues on another CPU runs +/// in place and the TLB lock is not taken. +/// - Plugins, tracing, icount and record/replay do not exist. Their entry +/// points compile to nothing. +/// +/// Only cputlb.c includes this header. Each section disappears when the +/// upstream code it stands in for is imported. + +#ifndef S2E_CPUTLB_DEPS_H +#define S2E_CPUTLB_DEPS_H + +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include "cpu.h" + +// clang-format off +#include +#include +#include +#include +#include +// clang-format on + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cpu-all.h" +#include "exec-all.h" +#include "exec-ram.h" +#include "exec-tb.h" + +#ifdef CONFIG_SYMBEX +#include +#include +#include +#endif + +/* + * Logging and tracing. + */ + +#define CPU_LOG_MMU 0 +#define qemu_log_mask(mask, ...) libcpu_log_mask(mask, __VA_ARGS__) +#define error_report(fmt, ...) fprintf(stderr, fmt "\n", ##__VA_ARGS__) +#define trace_memory_notdirty_write_access(a, b, c) ((void) 0) +#define trace_memory_notdirty_set_dirty(a) ((void) 0) + +/* + * One vCPU, one thread. The TLB lock is never taken, and work that upstream + * queues on a CPU runs immediately on the calling one. + */ + +#define qemu_spin_init(l) ((void) (l)) +#define qemu_spin_destroy(l) ((void) (l)) +#define qemu_spin_lock(l) ((void) (l)) +#define qemu_spin_unlock(l) ((void) (l)) + +#define qemu_cpu_is_self(cpu) true + +typedef union { + int host_int; + unsigned long host_ulong; + void *host_ptr; + vaddr target_ptr; +} run_on_cpu_data; + +#define RUN_ON_CPU_HOST_INT(i) ((run_on_cpu_data) {.host_int = (i)}) +#define RUN_ON_CPU_HOST_PTR(p) ((run_on_cpu_data) {.host_ptr = (p)}) +#define RUN_ON_CPU_TARGET_PTR(v) ((run_on_cpu_data) {.target_ptr = (v)}) + +typedef void (*run_on_cpu_func)(CPUState *cpu, run_on_cpu_data data); + +/* There is no other CPU to iterate over. */ +#define CPU_FOREACH(cpu) for ((cpu) = NULL; false;) + +static inline void async_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data) { + func(cpu, data); +} + +static inline void async_safe_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data) { + func(cpu, data); +} + +/* Upstream asks whether other vCPUs may run concurrently, to decide how much + atomicity a load or store needs. */ +static inline bool cpu_in_serial_context(CPUState *cpu) { + return true; +} + +/* x86 guests on x86 hosts need no memory barrier (upstream: backend-ldst.h). */ +#define cpu_req_mo(cpu, type) ((void) 0) + +/* x86 has one address space. */ +#define cpu_asidx_from_attrs(cpu, attrs) 0 + +/* The global lock that serializes device emulation. MMIO is dispatched on + the vCPU thread, which already owns the device state. */ +#define BQL_LOCK_GUARD() ((void) 0) + +/* Guards the page table of user-mode emulation. */ +#define WITH_MMAP_LOCK_GUARD() + +/* Upstream leaves the CPU loop to redo an access with all other vCPUs + stopped when it cannot give the required atomicity. There are no other + vCPUs, so the access never needs it. */ +#define cpu_loop_exit_atomic(cpu, ra) abort() + +#define trace_load_atom16_or_exit_fallback(ra) ((void) 0) +#define trace_store_atom2_fallback(p, ra) ((void) 0) +#define trace_store_atom4_fallback(p, ra) ((void) 0) +#define trace_store_atom8_fallback(p, ra) ((void) 0) +#define trace_store_atom16_fallback(p, ra) ((void) 0) + +/* + * icount. libcpu never restricts I/O to the last instruction of a TB, so + * neg.can_do_io is always true and this function is never reached. + */ +#undef cpu_io_recompile +#define cpu_io_recompile(cpu, ra) abort() + +/* + * Plugins. + */ + +enum qemu_plugin_mem_rw { + QEMU_PLUGIN_MEM_R = 1, + QEMU_PLUGIN_MEM_W, + QEMU_PLUGIN_MEM_RW, +}; + +static inline bool cpu_plugin_mem_cbs_enabled(const CPUState *cpu) { + return false; +} + +static inline void qemu_plugin_vcpu_mem_cb(CPUState *cpu, uint64_t vaddr, uint64_t value_low, uint64_t value_high, + MemOpIdx oi, enum qemu_plugin_mem_rw rw) { +} + +/* + * TB jump cache. The cache is still QEMU 1.0's array in neg; upstream's + * CPUJumpCache arrives with cpu-exec.c. + */ + +static inline void tcg_flush_jmp_cache(CPUState *cpu) { + memset(cpu->neg.tb_jmp_cache, 0, sizeof(cpu->neg.tb_jmp_cache)); +} + +/* + * TB invalidation. + */ + +/* + * Invalidates the TBs that a store of size bytes at ram_addr overwrites. + * + * The QEMU 1.0 function finds the TB that is doing the store through + * mem_io_pc, to stop it if it overwrites its own code. It tests the store + * against one byte of the bitmap of code bytes, which covers 8 bytes of the + * page, so the store is split where it crosses a multiple of 8. The old + * softmmu only called it for aligned accesses; upstream's does not align. + */ +static inline void tb_invalidate_phys_range_fast(CPUState *cpu, ram_addr_t ram_addr, unsigned size, uintptr_t retaddr) { + cpu->mem_io_pc = retaddr; + while (size) { + unsigned len = MIN(size, 8 - (unsigned) (ram_addr & 7)); + tb_invalidate_phys_page_fast(ram_addr, len); + ram_addr += len; + size -= len; + } +} + +/* + * Watchpoints. Defined in exec-bp.c over the QEMU 1.0 watchpoint list. + */ + +int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len); +void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len, MemTxAttrs attrs, int flags, uintptr_t ra); + +/* + * Memory API. See cpu/memory.h for MemoryRegion and MemoryRegionSection. + */ + +#define MEMTX_OK 0 + +/* Looks up the section of a guest physical page. For RAM, *xlat is the offset + of the page inside the region. For MMIO, it is the guest physical address, + which is what cpu_mmio_read() and cpu_mmio_write() take. */ +static inline MemoryRegionSection *address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr, + hwaddr *xlat, hwaddr *plen, MemTxAttrs attrs, + int *prot) { + const MemoryDesc *desc = mem_desc_find(addr); + if (!desc) { + *xlat = addr; + return &g_mmio_section; + } + + *xlat = mem_desc_get_offset(desc, addr); + return (MemoryRegionSection *) &desc->section; +} + +static inline bool memory_region_is_ram(MemoryRegion *mr) { + return mr->desc != NULL; +} + +/* A ROM device is read like RAM and written like MMIO. libcpu has none. */ +static inline bool memory_region_is_romd(MemoryRegion *mr) { + return false; +} + +static inline void *memory_region_get_ram_ptr(MemoryRegion *mr) { + return (void *) (uintptr_t) mr->desc->kvm.userspace_addr; +} + +static inline ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr) { + return mr->desc->ram_addr & TARGET_PAGE_MASK; +} + +/* + * cpu_mmio_read() and cpu_mmio_write() exchange values with the device model + * in little-endian byte order, which is the guest's. The caller states the + * byte order it wants in op: the softmmu asks for big-endian values when it + * reads and passes little-endian values when it writes. Upstream's memory + * API converts between the two, and so must these functions. + * + * The device interface takes accesses of 1, 2 or 4 bytes. An 8-byte access is + * done as two 4-byte ones, low half first, as the QEMU 1.0 softmmu did. + */ +static inline uint64_t se_mmio_adjust_endianness(uint64_t value, MemOp op) { + if ((op & MO_BSWAP) == MO_LE) { + return value; + } + + switch (op & MO_SIZE) { + case MO_8: + return value; + case MO_16: + return bswap16(value); + case MO_32: + return bswap32(value); + case MO_64: + return bswap64(value); + default: + g_assert_not_reached(); + } +} + +static inline MemTxResult memory_region_dispatch_read(MemoryRegion *mr, hwaddr addr, uint64_t *pval, MemOp op, + MemTxAttrs attrs) { + uint64_t value; + + if (memop_size(op) == 8) { + value = cpu_mmio_read(addr, 4); + value |= cpu_mmio_read(addr + 4, 4) << 32; + } else { + value = cpu_mmio_read(addr, memop_size(op)); + } + + *pval = se_mmio_adjust_endianness(value, op); + return MEMTX_OK; +} + +static inline MemTxResult memory_region_dispatch_write(MemoryRegion *mr, hwaddr addr, uint64_t data, MemOp op, + MemTxAttrs attrs) { + data = se_mmio_adjust_endianness(data, op); + + if (memop_size(op) == 8) { + cpu_mmio_write(addr, (uint32_t) data, 4); + cpu_mmio_write(addr + 4, data >> 32, 4); + } else { + cpu_mmio_write(addr, data, memop_size(op)); + } + return MEMTX_OK; +} + +/* + * Dirty tracking. Upstream keeps one bitmap per client. libcpu keeps one byte + * per page, with one bit per client (exec-ram.h), and the byte reads 0xff + * when the page needs no more tracking. + */ + +#define DIRTY_MEMORY_CODE CODE_DIRTY_FLAG +#define DIRTY_CLIENTS_NOCODE (0xff & ~CODE_DIRTY_FLAG) + +static inline bool physical_memory_is_clean(ram_addr_t addr) { + return !cpu_physical_memory_is_dirty(addr); +} + +static inline bool physical_memory_get_dirty_flag(ram_addr_t addr, unsigned client) { + return (cpu_physical_memory_get_dirty_flags(addr) & client) != 0; +} + +static inline void physical_memory_set_dirty_flag(ram_addr_t addr, unsigned client) { + cpu_physical_memory_set_dirty_flags(addr, client); +} + +static inline void physical_memory_set_dirty_range(ram_addr_t start, ram_addr_t length, uint8_t mask) { + ram_addr_t end = TARGET_PAGE_ALIGN(start + length); + for (ram_addr_t addr = start & TARGET_PAGE_MASK; addr < end; addr += TARGET_PAGE_SIZE) { + cpu_physical_memory_set_dirty_flags(addr, mask); + } +} + +/* Clears the flags of a client and makes the TLB send the next store to each + of these pages through notdirty_write(). cpu_physical_memory_reset_dirty() + does both: it ends in tlb_reset_dirty(). */ +static inline bool physical_memory_test_and_clear_dirty(ram_addr_t start, ram_addr_t length, unsigned client, + void *unused) { + cpu_physical_memory_reset_dirty(start, start + length, client); + return true; +} + +/* + * S2E hooks. + * + * libs2ecore keeps, for every KLEE object that backs a guest page, the list + * of TLB entries that refer to it (S2EExecutionStateTlb). It needs the list + * to repoint the entries when KLEE copies the object. The functions below + * tell libs2ecore when an entry is filled or dropped. cputlb.c calls them + * unconditionally; they compile to nothing in builds without symbolic + * execution and in the bitcode build, which never fills or flushes the TLB. + */ + +#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) + +extern int g_se_disable_tlb_flush; + +/* libs2ecore sets the guard while it saves and restores the device state on + a state switch. A flush requested during that time is dropped: the switch + ends with a full flush. */ +static inline bool se_tlb_flush_disabled(void) { + return g_se_disable_tlb_flush != 0; +} + +/* Called before entry (mmu_idx, index) is overwritten or invalidated. */ +static inline void se_tlb_drop_entry(CPUState *cpu, int mmu_idx, uintptr_t index) { + CPUTLBEntryFull *full = &cpu->neg.tlb.d[mmu_idx].fulltlb[index]; + + if (full->extra.object_state) { + g_sqi.tlb.flush_tlb_cache_page(full->extra.object_state, mmu_idx, index); + full->extra.object_state = NULL; + } +} + +/* Called before all the entries of one MMU index are invalidated. Upstream's + flush clears the fast table only, so the object pointers of the full + entries are cleared here. */ +static inline void se_tlb_drop_mmuidx(CPUState *cpu, int mmu_idx) { + CPUTLBDesc *desc = &cpu->neg.tlb.d[mmu_idx]; + size_t n = (cpu_tlb_fast(cpu, mmu_idx)->mask >> CPU_TLB_ENTRY_BITS) + 1; + +#if defined(SE_ENABLE_TLB) + if (!*g_sqi.mode.single_path_mode) { + g_sqi.tlb.flush_tlb_cache_mmuidx(mmu_idx); + } +#endif + + for (size_t i = 0; i < n; i++) { + desc->fulltlb[i].extra.object_state = NULL; + } +} + +/* Called after the entry for addr_page has been written. host_page is the + host address of the page, or 0 for MMIO, which has no KLEE object. */ +static inline void se_tlb_set_entry(CPUState *cpu, int mmu_idx, vaddr addr_page, uintptr_t host_page) { + cpu_tlb_fast(cpu, mmu_idx) + ->table[(addr_page >> TARGET_PAGE_BITS) & (cpu_tlb_fast(cpu, mmu_idx)->mask >> CPU_TLB_ENTRY_BITS)] + .se_addend = 0; + +#if defined(SE_ENABLE_TLB) && defined(CONFIG_SYMBEX_MP) + if (host_page) { + g_sqi.tlb.update_tlb_entry(cpu_env(cpu), mmu_idx, addr_page, host_page); + } +#endif +} + +/* Adds the S2E flags that are known when an entry is filled. They apply to + loads and stores, not to code fetches. */ +static inline void se_tlb_fill_flags(hwaddr paddr_page, unsigned *read_flags, unsigned *write_flags) { + if (*g_sqi.events.before_memory_access_signals_count || *g_sqi.events.after_memory_access_signals_count) { + *read_flags |= TLB_MEM_TRACE; + *write_flags |= TLB_MEM_TRACE; + } + +#if defined(CONFIG_SYMBEX_MP) + if (g_sqi.mem.is_mmio_symbolic(paddr_page, TARGET_PAGE_SIZE)) { + *read_flags |= TLB_SYMB_MMIO; + *write_flags |= TLB_SYMB_MMIO; + } +#endif +} + +#else + +#define se_tlb_flush_disabled() false +#define se_tlb_drop_entry(cpu, mmu_idx, index) ((void) 0) +#define se_tlb_drop_mmuidx(cpu, mmu_idx) ((void) 0) +#define se_tlb_set_entry(cpu, mmu_idx, addr, host) ((void) 0) +#define se_tlb_fill_flags(paddr, read_flags, write_flags) ((void) 0) + +#endif + +/* + * The bitcode build. + * + * cputlb.c is also compiled to LLVM bitcode, which KLEE interprets when the + * guest computes on symbolic data. In that build the address of an access + * can be symbolic. Three things follow. + * + * The TLB must be indexed with a concrete value, or KLEE would treat the + * lookup as a symbolic pointer into the TLB. SE_CONCRETE_PAGE() forks the + * state on the page number, which leaves the offset in the page symbolic. + * + * The target hooks must be the bitcode copies. A call through cpu->cc->tcg_ops + * reaches the native ones, and KLEE forks once per possible value of each + * symbolic argument of a native function. SE_TCG_OP() calls the x86 function + * by name instead. The ops table itself is native memory that KLEE cannot + * read, so SE_TCG_HAS_OP() answers for it: x86 has the hooks that SE_TCG_OP() + * is used for, and no tlb_fill_align. + * + * The functions that reach device models or the TB cache stay native. Their + * definitions carry SE_NATIVE in place of static, which exports them so that + * the bitcode can call them, and their bodies are compiled out of the + * bitcode. Their prototypes are below. + */ + +#if defined(SYMBEX_LLVM_LIB) + +#define SE_TCG_HAS_OP(ops, op) false +#define SE_TCG_OP(cpu, op) glue(x86_cpu_, op) + +#define SE_CONCRETE_PAGE(page) tcg_llvm_fork_and_concretize(page, 0, ((target_ulong) - 1) >> TARGET_PAGE_BITS, 0) + +/* The victim TLB is disabled and always empty (tlb_set_page_full()). */ +#define victim_tlb_hit(cpu, mmu_idx, index, access_type, page) false + +#else + +#define SE_TCG_HAS_OP(ops, op) ((ops)->op != NULL) +#define SE_TCG_OP(cpu, op) ((cpu)->cc->tcg_ops->op) +#define SE_CONCRETE_PAGE(page) (page) + +#endif + +#if defined(CONFIG_SYMBEX) + +#define SE_NATIVE + +void notdirty_write(CPUState *cpu, vaddr mem_vaddr, unsigned size, CPUTLBEntryFull *full, uintptr_t retaddr); +uint64_t do_ld_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, int mmu_idx, + MMUAccessType type, uintptr_t ra); +Int128 do_ld16_mmio_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, int mmu_idx, + uintptr_t ra); +uint64_t do_st_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t val_le, vaddr addr, int size, int mmu_idx, + uintptr_t ra); +uint64_t do_st16_mmio_leN(CPUState *cpu, CPUTLBEntryFull *full, Int128 val_le, vaddr addr, int size, int mmu_idx, + uintptr_t ra); + +#else + +#define SE_NATIVE static + +#endif + +#endif diff --git a/libcpu/src/s2e/cputlb-symbex-ldst.c.inc b/libcpu/src/s2e/cputlb-symbex-ldst.c.inc new file mode 100644 index 000000000..9e9870dbc --- /dev/null +++ b/libcpu/src/s2e/cputlb-symbex-ldst.c.inc @@ -0,0 +1,128 @@ +/// Copyright (C) 2026 Vitaly Chipounov +/// Copyrights of all contributions belong to their respective owners. +/// +/// This library is free software; you can redistribute it and/or +/// modify it under the terms of the GNU Library General Public +/// License as published by the Free Software Foundation; either +/// version 2 of the License, or (at your option) any later version. +/// +/// This library is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +/// Library General Public License for more details. +/// +/// You should have received a copy of the GNU Library General Public +/// License along with this library; if not, see . + +/// @file +/// Reports guest memory accesses to the S2E plugins. +/// +/// accel/cputlb.c includes this file after the definitions of +/// do_{ld,st}{1,2,4,8}_mmu() and before the entry points that call them +/// (ldst_common.c.inc and the code fetch functions). Each function below +/// wraps one of them and reports the access, and the macros at the end make +/// the entry points call the wrappers. The upstream functions are not edited. +/// +/// The slow path only runs for the accesses that plugins want to see: when a +/// plugin subscribes to memory accesses, tlb_set_page_full() marks every page +/// with TLB_MEM_TRACE, which keeps generated code off the inline fast path. +/// +/// Natively executed code reports an access after it happened, with its +/// value. Bitcode also reports it before, while the address can still be +/// symbolic, and reports accesses to symbolic hardware. + +#if defined(CONFIG_SYMBEX) + +#if defined(SYMBEX_LLVM_LIB) + +static inline void se_trace_before(vaddr addr, uint64_t value, unsigned size, unsigned flags) { + if (*g_sqi.events.before_memory_access_signals_count) { + tcg_llvm_before_memory_access(addr, value, size, flags); + } +} + +/* Returns true if the first page of an access is a device or holds + symbolic MMIO or DMA ranges. The access has just completed, so the page + is in the TLB. */ +static inline bool se_page_is_hw(CPUState *cpu, vaddr addr, MemOpIdx oi, MMUAccessType type) { + int mmu_idx = get_mmuidx(oi); + uintptr_t index = tlb_index(cpu, mmu_idx, addr); + + if (!tlb_hit(tlb_read_idx(tlb_entry(cpu, mmu_idx, addr), type), addr)) { + return false; + } + return (cpu->neg.tlb.d[mmu_idx].fulltlb[index].slow_flags[type] & (TLB_MMIO | TLB_SYMB_MMIO)) != 0; +} + +static inline void se_trace_after(CPUState *cpu, vaddr addr, MemOpIdx oi, uint64_t value, unsigned size, + unsigned flags) { + bool is_write = (flags & MEM_TRACE_FLAG_WRITE) != 0; + + if (*g_sqi.events.after_memory_access_signals_count) { + tcg_llvm_after_memory_access(addr, value, size, flags, 0); + } + + if (se_page_is_hw(cpu, addr, oi, is_write ? MMU_DATA_STORE : MMU_DATA_LOAD)) { + tcg_llvm_trace_mmio_access(addr, value, size, is_write); + } +} + +#else + +#define se_trace_before(addr, value, size, flags) ((void) 0) + +static inline void se_trace_after(CPUState *cpu, vaddr addr, MemOpIdx oi, uint64_t value, unsigned size, + unsigned flags) { +#if defined(SE_ENABLE_MEM_TRACING) + if (unlikely(*g_sqi.events.after_memory_access_signals_count)) { + g_sqi.events.after_memory_access(addr, value, size, flags, 0); + } +#endif +} + +#endif + +/* Code fetches are not reported. */ +#define SE_GEN_LD(n, type) \ + static type se_do_ld##n##_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMUAccessType access) { \ + type ret; \ + if (access == MMU_INST_FETCH) { \ + return do_ld##n##_mmu(cpu, addr, oi, ra, access); \ + } \ + se_trace_before(addr, 0, n, 0); \ + ret = do_ld##n##_mmu(cpu, addr, oi, ra, access); \ + se_trace_after(cpu, addr, oi, ret, n, 0); \ + return ret; \ + } + +#define SE_GEN_ST(n, type) \ + static void se_do_st##n##_mmu(CPUState *cpu, vaddr addr, type val, MemOpIdx oi, uintptr_t ra) { \ + se_trace_before(addr, val, n, MEM_TRACE_FLAG_WRITE); \ + do_st##n##_mmu(cpu, addr, val, oi, ra); \ + se_trace_after(cpu, addr, oi, val, n, MEM_TRACE_FLAG_WRITE); \ + } + +SE_GEN_LD(1, uint8_t) +SE_GEN_LD(2, uint16_t) +SE_GEN_LD(4, uint32_t) +SE_GEN_LD(8, uint64_t) + +SE_GEN_ST(1, uint8_t) +SE_GEN_ST(2, uint16_t) +SE_GEN_ST(4, uint32_t) +SE_GEN_ST(8, uint64_t) + +#undef SE_GEN_LD +#undef SE_GEN_ST + +#define do_ld1_mmu se_do_ld1_mmu +#define do_ld2_mmu se_do_ld2_mmu +#define do_ld4_mmu se_do_ld4_mmu +#define do_ld8_mmu se_do_ld8_mmu + +#define do_st1_mmu se_do_st1_mmu +#define do_st2_mmu se_do_st2_mmu +#define do_st4_mmu se_do_st4_mmu +#define do_st8_mmu se_do_st8_mmu + +#endif diff --git a/libcpu/src/s2e/cputlb-symbex.c.inc b/libcpu/src/s2e/cputlb-symbex.c.inc new file mode 100644 index 000000000..24f52fd7c --- /dev/null +++ b/libcpu/src/s2e/cputlb-symbex.c.inc @@ -0,0 +1,232 @@ +/// Copyright (C) 2026 Vitaly Chipounov +/// Copyrights of all contributions belong to their respective owners. +/// +/// This library is free software; you can redistribute it and/or +/// modify it under the terms of the GNU Library General Public +/// License as published by the Free Software Foundation; either +/// version 2 of the License, or (at your option) any later version. +/// +/// This library is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +/// Library General Public License for more details. +/// +/// You should have received a copy of the GNU Library General Public +/// License along with this library; if not, see . + +/// @file +/// The symbolic execution cases of the softmmu lookup. +/// +/// accel/cputlb.c includes this file after the definition of +/// MMULookupLocals, and mmu_lookup() calls se_mmu_resolve() once it has +/// translated the page or pages of an access. +/// +/// A page can need attention for three reasons, which the TLB flags tell +/// apart (cpu/exec/tlb-flags.h): +/// +/// - TLB_SYMB: the page holds symbolic data. Natively executed code can +/// only handle concrete bytes. +/// - TLB_NOT_OURS: the KLEE object that backs the page is shared with +/// another execution state and must be copied before it is written. +/// - TLB_MMIO and TLB_SYMB_MMIO: the access may hit a device register or a +/// DMA range that a plugin declared symbolic. +/// +/// se_mmu_resolve() either leaves for symbolic execution, or decides how +/// natively executed code reaches the bytes of each page: directly, through +/// the host address that mmu_lookup() computed, or through libs2ecore. For +/// the second case it sets TLB_MMIO in the flags of the lookup result. This +/// is a local copy of the flags, the TLB is not changed. The upstream load +/// and store code already sends every access to a page with TLB_MMIO to +/// do_ld_mmio_beN() or do_st_mmio_leN(), with the value for a store. These +/// two functions call se_ram_ld_beN() and se_ram_st_leN() below, which do +/// the access through libs2ecore when the page is RAM. The upstream load and +/// store functions therefore need no S2E change, and no state is kept +/// between the lookup and the access. +/// +/// The file also replaces the atomic load and store primitives of +/// ldst_atomicity.c.inc in builds with symbolic execution. + +#if defined(CONFIG_SYMBEX) + +/* + * The upstream primitives give an access the atomicity that its instruction + * promises to other vCPUs. An unaligned load does this by reading the 16 + * aligned bytes around the address, relying on the host page offset of the + * pointer to stay inside the page. This does not hold for a KLEE concrete + * buffer, which is a 4096-byte heap block with no particular alignment: the + * load could read past its end. In bitcode, the alignment test is a branch on + * a possibly symbolic pointer and makes KLEE fork for no reason. libcpu has + * one vCPU, so plain loads and stores of the exact size are enough. + */ + +static inline Int128 se_ld16_he_p(const void *ptr) { + Int128 r; + __builtin_memcpy(&r, ptr, sizeof(r)); + return r; +} + +static inline void se_st16_he_p(void *ptr, Int128 v) { + __builtin_memcpy(ptr, &v, sizeof(v)); +} + +#define load_atom_2(cpu, ra, pv, memop) lduw_he_p(pv) +#define load_atom_4(cpu, ra, pv, memop) ((uint32_t) ldl_he_p(pv)) +#define load_atom_8(cpu, ra, pv, memop) ldq_he_p(pv) +#define load_atom_16(cpu, ra, pv, memop) se_ld16_he_p(pv) + +#define store_atom_2(cpu, ra, pv, memop, val) stw_he_p(pv, val) +#define store_atom_4(cpu, ra, pv, memop, val) stl_he_p(pv, val) +#define store_atom_8(cpu, ra, pv, memop, val) stq_he_p(pv, val) +#define store_atom_16(cpu, ra, pv, memop, val) se_st16_he_p(pv, val) + +#endif + +#if defined(CONFIG_SYMBEX) && defined(CONFIG_SYMBEX_MP) && !defined(SYMBEX_LLVM_LIB) + +#define SE_RESOLVE_FLAGS (TLB_SYMB | TLB_NOT_OURS | TLB_MMIO | TLB_SYMB_MMIO) + +/* Returns true if the accessed bytes of a RAM page are all concrete. */ +static inline bool se_page_bytes_concrete(const MMULookupPageData *p) { + void *object_state = p->full->extra.object_state; + + return !object_state || _se_check_concrete(object_state, p->addr & ~SE_RAM_OBJECT_MASK, p->size); +} + +/* + * First pass over one page of an access: leave for symbolic execution if + * natively executed code cannot do the access. + * + * switch_to_symbolic() does not return: KLEE executes the whole instruction + * again. Only generated code can switch. A helper may already have changed + * the CPU state, which cannot be rolled back. + */ +static void se_mmu_check_page(MMULookupPageData *p, MMUAccessType type, uintptr_t ra) { + if (!p->size || !(p->flags & SE_RESOLVE_FLAGS)) { + return; + } + + if (p->flags & (TLB_MMIO | TLB_SYMB_MMIO)) { + /* A device model can only be given concrete values. */ + hwaddr paddr = p->full->phys_addr | (p->addr & ~TARGET_PAGE_MASK); + if (g_sqi.mem.is_mmio_symbolic(paddr, p->size)) { + g_sqi.exec.switch_to_symbolic((void *) ra); + } + } + + if (!(p->flags & TLB_MMIO) && type != MMU_DATA_STORE && !se_page_bytes_concrete(p)) { + g_sqi.exec.switch_to_symbolic((void *) ra); + } +} + +/* + * Second pass: decide whether the access to a RAM page can go directly to + * the concrete buffer of its KLEE object, at haddr. + * + * It cannot in two cases. A store to a shared object must first make KLEE + * copy the object. A load or a store that touches symbolic bytes must go + * through KLEE, which concretizes the bytes of a load and records that a + * store made them concrete. Both are done by libs2ecore, at the time of the + * access (se_ram_ld_beN() and se_ram_st_leN()). + */ +static void se_mmu_resolve_page(MMULookupPageData *p, MMUAccessType type) { + if (!p->size || !(p->flags & SE_RESOLVE_FLAGS) || (p->flags & TLB_MMIO)) { + return; + } + + bool direct = se_page_bytes_concrete(p); + if (type == MMU_DATA_STORE && (p->flags & TLB_NOT_OURS)) { + direct = false; + } + + if (!direct) { + p->flags |= TLB_MMIO; + } +} + +static inline void se_mmu_resolve(CPUState *cpu, MMULookupLocals *l, MMUAccessType type, uintptr_t ra) { + if (likely(!((l->page[0].flags | l->page[1].flags) & SE_RESOLVE_FLAGS))) { + return; + } + + if (tcg_is_dyngen_addr((void *) ra)) { + se_mmu_check_page(&l->page[0], type, ra); + se_mmu_check_page(&l->page[1], type, ra); + } + + se_mmu_resolve_page(&l->page[0], type); + se_mmu_resolve_page(&l->page[1], type); +} + +/* Returns the address of a guest byte in the guest RAM as QEMU mapped it. + KLEE binds the object of the page at this address, and libs2ecore takes it + as argument. haddr is a different address: it points into the concrete + buffer of the object. */ +static inline uintptr_t se_host_ram_addr(CPUState *cpu, vaddr addr, int mmu_idx) { + return addr + tlb_entry(cpu, mmu_idx, addr)->addend; +} + +/* + * Loads size bytes of a RAM page through libs2ecore, which picks concrete + * values for the symbolic ones and constrains the state accordingly. + * do_ld_mmio_beN() calls it first. + * + * @param ret_be the bytes are appended to it, most significant first + * @return false if the page is not RAM; the caller then reads the device + */ +static inline bool se_ram_ld_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t *ret_be, vaddr addr, int size, + int mmu_idx) { + uint8_t buf[8]; + + if (!memory_region_is_ram(full->section->mr)) { + return false; + } + + g_sqi.mem.read_ram_concrete(se_host_ram_addr(cpu, addr, mmu_idx), buf, size); + for (int i = 0; i < size; i++) { + *ret_be = (*ret_be << 8) | buf[i]; + } + return true; +} + +/* + * Stores the low size bytes of a value to a RAM page through libs2ecore, + * which makes KLEE copy the object if it is shared and marks the bytes + * concrete. do_st_mmio_leN() calls it first. + * + * @param val_le the bytes are taken from it, least significant first, and + * shifted out + * @return false if the page is not RAM; the caller then writes the device + */ +static inline bool se_ram_st_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t *val_le, vaddr addr, int size, + int mmu_idx) { + uint8_t buf[8]; + + if (!memory_region_is_ram(full->section->mr)) { + return false; + } + + for (int i = 0; i < size; i++) { + buf[i] = *val_le; + *val_le >>= 8; + } + g_sqi.mem.write_ram_concrete(se_host_ram_addr(cpu, addr, mmu_idx), buf, size); + return true; +} + +#else + +/* KLEE handles symbolic data and copies shared objects itself, and the other + builds have neither. */ +#define se_mmu_resolve(cpu, l, type, ra) ((void) 0) + +static inline bool se_ram_ld_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t *ret_be, vaddr addr, int size, + int mmu_idx) { + return false; +} + +static inline bool se_ram_st_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t *val_le, vaddr addr, int size, + int mmu_idx) { + return false; +} + +#endif From 9c144ea920f17b8d44e84368090ee9370d87df2b Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:45:14 +0200 Subject: [PATCH 41/52] libcpu,libtcg,libs2ecore,libs2e: replaced the softmmu with QEMU v11.1.0's cputlb.c The TLB layout is shared by cputlb.c, the libtcg backend and libs2ecore, so the three change together. libcpu compiles accel/cputlb.c natively and as bitcode, takes upstream's TLB structures in cpu/state.h, and provides the TCGCPUOps hooks and the watchpoint functions that cputlb.c calls. softmmu-compat.h maps the old accessor names onto the new API. The softmmu template headers, exec-tlb.c, exec-phys.c and the unused ld*_raw_symb accessors are removed. x86_cpu_tlb_fill() aborts when a probe faults, because the page walk has already recorded the fault in CR2. libtcg calls helper_{ld,st}*_mmu directly, as upstream does. tcg/tlb.h, tcg/cpu.h, the helper override tables and the atomic helper stubs are removed. The atomic templates now live in libcpu. The LLVM translator aborts on a 128-bit memory operation, which it has no helper for. libs2ecore reads the KLEE object of a TLB entry from CPUTLBEntryFull and its MMU function handlers follow the new TLB layout and helper arguments. g_sqi.mem.read_ram_concrete_check lost its last user and is removed. libs2e links libcpu.a and libtcg.a as a group, because libtcg refers to helpers that libcpu defines. Co-Authored-By: Claude Opus 5.5 --- libcpu/CMakeLists.txt | 1 + libcpu/include/cpu/exec.h | 14 +- libcpu/include/cpu/se_libcpu.h | 1 - libcpu/include/cpu/softmmu_defs.h | 125 ----- libcpu/include/cpu/state.h | 149 +++++- libcpu/include/cpu/tlb.h | 4 +- libcpu/src/CMakeLists.txt | 19 +- libcpu/src/cpu-all.h | 28 +- libcpu/src/exec-all.h | 43 +- libcpu/src/exec-bp.c | 106 ++-- libcpu/src/exec-phys.c | 56 -- libcpu/src/exec-phys.h | 33 -- libcpu/src/exec-tb.c | 15 +- libcpu/src/exec-tlb.c | 317 ----------- libcpu/src/exec-tlb.h | 64 --- libcpu/src/exec.c | 254 +-------- libcpu/src/exec.h | 6 +- libcpu/src/softmmu-compat.h | 123 +++++ libcpu/src/softmmu_exec.h | 152 ------ libcpu/src/softmmu_header.h | 323 ------------ libcpu/src/softmmu_template.h | 647 ----------------------- libcpu/src/target-i386/cpu.h | 8 + libcpu/src/target-i386/helper.c | 12 +- libcpu/src/target-i386/op_helper.c | 158 +++--- libcpu/src/translate-all.c | 36 +- libs2e/src/CMakeLists.txt | 5 +- libs2e/src/s2e-kvm-vcpu.cpp | 2 +- libs2e/src/s2e-libcpu-interface.cpp | 1 - libs2ecore/include/s2e/s2e_libcpu.h | 6 - libs2ecore/src/ExprInterface.cpp | 3 +- libs2ecore/src/FunctionHandlers.cpp | 18 +- libs2ecore/src/MMUFunctionHandlers.cpp | 664 ++++++------------------ libs2ecore/src/S2EExecutionState.cpp | 8 +- libs2ecore/src/S2EExecutionStateTlb.cpp | 65 ++- libs2ecore/src/S2EExecutor.cpp | 28 +- libtcg/include/tcg/cpu.h | 33 -- libtcg/include/tcg/tcg.h | 27 +- libtcg/include/tcg/tlb.h | 97 ---- libtcg/scripts/upgrade/mapping.tsv | 4 +- libtcg/src/CMakeLists.txt | 2 +- libtcg/src/atomic-helpers.c | 61 --- libtcg/src/atomic_common.c.inc | 51 -- libtcg/src/atomic_template.h | 219 -------- libtcg/src/region.c | 1 - libtcg/src/tcg-llvm.cpp | 37 +- libtcg/src/x86_64/tcg-target.c.inc | 4 +- 46 files changed, 706 insertions(+), 3324 deletions(-) delete mode 100644 libcpu/include/cpu/softmmu_defs.h delete mode 100644 libcpu/src/exec-phys.c delete mode 100644 libcpu/src/exec-phys.h delete mode 100644 libcpu/src/exec-tlb.c delete mode 100644 libcpu/src/exec-tlb.h create mode 100644 libcpu/src/softmmu-compat.h delete mode 100644 libcpu/src/softmmu_exec.h delete mode 100644 libcpu/src/softmmu_header.h delete mode 100644 libcpu/src/softmmu_template.h delete mode 100644 libtcg/include/tcg/cpu.h delete mode 100644 libtcg/include/tcg/tlb.h delete mode 100644 libtcg/src/atomic-helpers.c delete mode 100644 libtcg/src/atomic_common.c.inc delete mode 100644 libtcg/src/atomic_template.h diff --git a/libcpu/CMakeLists.txt b/libcpu/CMakeLists.txt index b23bd263d..363946eee 100644 --- a/libcpu/CMakeLists.txt +++ b/libcpu/CMakeLists.txt @@ -59,6 +59,7 @@ file(WRITE ${CONFIG_TARGET_H} #define TARGET_BIG_ENDIAN 0 #define TARGET_PHYS_ADDR_BITS 64 #define CONFIG_SOFTMMU 1 +#define CONFIG_TCG 1 #define CONFIG_I386_DIS 1 " ) diff --git a/libcpu/include/cpu/exec.h b/libcpu/include/cpu/exec.h index 8ab0a85a1..531aa66b5 100644 --- a/libcpu/include/cpu/exec.h +++ b/libcpu/include/cpu/exec.h @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -48,10 +47,6 @@ void cpu_exit(CPUArchState *s); void cpu_exec_init_all(void); void tcg_exec_init(unsigned long tb_size); -void tlb_flush(CPUArchState *env, int flush_global); -void tlb_flush_page(CPUArchState *env, target_ulong addr); -void tlb_fill(CPUArchState *env1, target_ulong addr, target_ulong page_addr, int is_write, int mmu_idx, void *retaddr); - void tb_flush(CPUArchState *env); /* page related stuff */ @@ -91,12 +86,9 @@ void cpu_physical_memory_get_dirty_bitmap(uint8_t *bitmap, ram_addr_t start, int void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t end, int dirty_flags); -const struct MemoryDescOps *phys_get_ops(target_phys_addr_t index); -bool is_notdirty_ops(const struct MemoryDescOps *ops); - -#ifdef CONFIG_SYMBEX -bool se_ismemfunc(const struct MemoryDescOps *ops, int isWrite); -#endif +/* tlb_flush(), tlb_flush_page() and tlb_set_page(). The header is upstream's + and has no C++ guard of its own, so it is included inside this one. */ +#include #ifdef __cplusplus } diff --git a/libcpu/include/cpu/se_libcpu.h b/libcpu/include/cpu/se_libcpu.h index 49a349049..607e613f1 100644 --- a/libcpu/include/cpu/se_libcpu.h +++ b/libcpu/include/cpu/se_libcpu.h @@ -118,7 +118,6 @@ struct se_libcpu_interface_t { void (*read_ram_concrete)(uint64_t host_address, void *buf, uint64_t size); void (*write_ram_concrete)(uint64_t host_address, const uint8_t *buf, uint64_t size); - void (*read_ram_concrete_check)(uint64_t host_address, uint8_t *buf, uint64_t size); uint64_t (*read_mem_io_vaddr)(int masked); int (*is_port_symbolic)(uint64_t port); diff --git a/libcpu/include/cpu/softmmu_defs.h b/libcpu/include/cpu/softmmu_defs.h deleted file mode 100644 index 1f39cd6a7..000000000 --- a/libcpu/include/cpu/softmmu_defs.h +++ /dev/null @@ -1,125 +0,0 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -/* - * Software MMU support - * - * Declare helpers used by TCG for qemu_ld/st ops. - * - * Used by softmmu_exec.h, TCG targets and exec-all.h. - * - */ -#ifndef SOFTMMU_DEFS_H -#define SOFTMMU_DEFS_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef CONFIG_SYMBEX -uintptr_t se_notdirty_mem_write(target_phys_addr_t ram_addr, int size); -uintptr_t se_notdirty_mem_read(target_phys_addr_t ram_addr); -#endif - -#if defined(CONFIG_SYMBEX_MP) -uint8_t helper_ldb_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stb_mmu_symb(CPUArchState *env, target_ulong addr, uint8_t val, int mmu_idx, void *retaddr); -uint16_t helper_ldw_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stw_mmu_symb(CPUArchState *env, target_ulong addr, uint16_t val, int mmu_idx, void *retaddr); -uint32_t helper_ldl_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stl_mmu_symb(CPUArchState *env, target_ulong addr, uint32_t val, int mmu_idx, void *retaddr); -uint64_t helper_ldq_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stq_mmu_symb(CPUArchState *env, target_ulong addr, uint64_t val, int mmu_idx, void *retaddr); - -uint8_t io_make_symbolicb_mmu(const char *name); -uint16_t io_make_symbolicw_mmu(const char *name); -uint32_t io_make_symbolicl_mmu(const char *name); -uint64_t io_make_symbolicq_mmu(const char *name); - -uint8_t io_read_chk_symb_b_mmu(const char *label, target_ulong physaddr, uintptr_t pa); -uint16_t io_read_chk_symb_w_mmu(const char *label, target_ulong physaddr, uintptr_t pa); -uint32_t io_read_chk_symb_l_mmu(const char *label, target_ulong physaddr, uintptr_t pa); -uint64_t io_read_chk_symb_q_mmu(const char *label, target_ulong physaddr, uintptr_t pa); - -uint8_t io_readb_mmu_symb(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writeb_mmu_symb(CPUArchState *env, target_phys_addr_t physaddr, uint8_t val, target_ulong addr, void *retaddr); -uint16_t io_readw_mmu_symb(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writew_mmu_symb(CPUArchState *env, target_phys_addr_t physaddr, uint16_t val, target_ulong addr, void *retaddr); -uint32_t io_readl_mmu_symb(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writel_mmu_symb(CPUArchState *env, target_phys_addr_t physaddr, uint32_t val, target_ulong addr, void *retaddr); -uint64_t io_readq_mmu_symb(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writeq_mmu_symb(CPUArchState *env, target_phys_addr_t physaddr, uint64_t val, target_ulong addr, void *retaddr); - -#endif - -uint8_t helper_ldb_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stb_mmu(CPUArchState *env, target_ulong addr, uint8_t val, int mmu_idx, void *retaddr); -uint16_t helper_ldw_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stw_mmu(CPUArchState *env, target_ulong addr, uint16_t val, int mmu_idx, void *retaddr); -uint32_t helper_ldl_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stl_mmu(CPUArchState *env, target_ulong addr, uint32_t val, int mmu_idx, void *retaddr); -uint64_t helper_ldq_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stq_mmu(CPUArchState *env, target_ulong addr, uint64_t val, int mmu_idx, void *retaddr); - -uint8_t helper_ldb_cmmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stb_cmmu(CPUArchState *env, target_ulong addr, uint8_t val, int mmu_idx, void *retaddr); -uint16_t helper_ldw_cmmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stw_cmmu(CPUArchState *env, target_ulong addr, uint16_t val, int mmu_idx, void *retaddr); -uint32_t helper_ldl_cmmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stl_cmmu(CPUArchState *env, target_ulong addr, uint32_t val, int mmu_idx, void *retaddr); -uint64_t helper_ldq_cmmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -void helper_stq_cmmu(CPUArchState *env, target_ulong addr, uint64_t val, int mmu_idx, void *retaddr); - -uint8_t io_readb_mmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writeb_mmu(CPUArchState *env, target_phys_addr_t physaddr, uint8_t val, target_ulong addr, void *retaddr); -uint16_t io_readw_mmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writew_mmu(CPUArchState *env, target_phys_addr_t physaddr, uint16_t val, target_ulong addr, void *retaddr); -uint32_t io_readl_mmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writel_mmu(CPUArchState *env, target_phys_addr_t physaddr, uint32_t val, target_ulong addr, void *retaddr); -uint64_t io_readq_mmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writeq_mmu(CPUArchState *env, target_phys_addr_t physaddr, uint64_t val, target_ulong addr, void *retaddr); - -uint8_t io_readb_cmmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writeb_cmmu(CPUArchState *env, target_phys_addr_t physaddr, uint8_t val, target_ulong addr, void *retaddr); -uint16_t io_readw_cmmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writew_cmmu(CPUArchState *env, target_phys_addr_t physaddr, uint16_t val, target_ulong addr, void *retaddr); -uint32_t io_readl_cmmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writel_cmmu(CPUArchState *env, target_phys_addr_t physaddr, uint32_t val, target_ulong addr, void *retaddr); -uint64_t io_readq_cmmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -void io_writeq_cmmu(CPUArchState *env, target_phys_addr_t physaddr, uint64_t val, target_ulong addr, void *retaddr); - -void io_write_chkb_mmu(CPUArchState *env, target_phys_addr_t physaddr, uint8_t val, target_ulong addr, void *retaddr); -void io_write_chkw_mmu(CPUArchState *env, target_phys_addr_t physaddr, uint16_t val, target_ulong addr, void *retaddr); -void io_write_chkl_mmu(CPUArchState *env, target_phys_addr_t physaddr, uint32_t val, target_ulong addr, void *retaddr); -void io_write_chkq_mmu(CPUArchState *env, target_phys_addr_t physaddr, uint64_t val, target_ulong addr, void *retaddr); - -uint8_t io_read_chkb_mmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -uint16_t io_read_chkw_mmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -uint32_t io_read_chkl_mmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -uint64_t io_read_chkq_mmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); - -uint8_t io_read_chkb_cmmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -uint16_t io_read_chkw_cmmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -uint32_t io_read_chkl_cmmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); -uint64_t io_read_chkq_cmmu(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, void *retaddr); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libcpu/include/cpu/state.h b/libcpu/include/cpu/state.h index d66115b09..c4880fdab 100644 --- a/libcpu/include/cpu/state.h +++ b/libcpu/include/cpu/state.h @@ -49,9 +49,12 @@ * execution fields through tcg_env at a negative offset, computed as * offsetof(ArchCPU, parent_obj.field) - offsetof(ArchCPU, env). * - * The TLB keeps the QEMU 1.0 organization (fixed size, iotlb, no victim TLB, - * no CPUTLBEntryFull); upstream's algorithms arrive with the cputlb.c import - * (PORTING.md phase 2). + * The TLB structures are upstream's (accel/tcg/cputlb.c), with two + * differences. The tables of each MMU mode are static arrays inside neg + * instead of heap allocations, so that the KLEE object registered over neg + * covers them and the softmmu can read them as bitcode. Their size is + * therefore pinned (src/accel/tlb-bounds.h). MemoryRegionSection is a small + * libcpu structure over MemoryDesc (cpu/memory.h), not upstream's. * * This header is included at the end of cpu/i386/cpu.h: ArchCPU embeds * CPUArchState by value, so the complete CPUX86State must be visible first. @@ -59,13 +62,18 @@ #include #include +#include #include #include #include #include +#include +#include +#include #include +#include #include #include #include @@ -81,21 +89,117 @@ extern "C" { struct TCGCPUOps; struct TranslationBlock; -/* Data elements that are per MMU mode, minus the bits accessed by the TCG fast path. */ +/* The part of upstream's CPUClass that accel/tcg reads. */ +typedef struct CPUClass { + const struct TCGCPUOps *tcg_ops; +} CPUClass; + +typedef uint32_t MMUIdxMap; + +/* Size of the victim TLB. The victim TLB is disabled (src/accel/cputlb.c), + the arrays only exist so that the upstream code compiles unchanged. */ +#define CPU_VTLB_SIZE 8 + +/* + * The full TLB entry, which is not accessed by generated TCG code, + * so the layout is not as critical as that of CPUTLBEntry. This is + * also why we don't want to combine the two structs. + */ +typedef struct CPUTLBEntryFull { + /* + * @xlat_offset: TARGET_PAGE_BITS aligned offset which must be added to + * the virtual address to obtain: + * + the ram_addr_t of the target RAM (if the section is RAM) + * + the guest physical address of the MMIO access (otherwise) + */ + hwaddr xlat_offset; + + /* @section contains physical section. */ + MemoryRegionSection *section; + + /* @phys_addr contains the physical address of the page. */ + hwaddr phys_addr; + + /* @attrs contains the memory transaction attributes for the page. */ + MemTxAttrs attrs; + + /* @prot contains the complete protections for the page. */ + uint8_t prot; + + /* @lg_page_size contains the log2 of the page size. */ + uint8_t lg_page_size; + + /* Additional tlb flags requested by tlb_fill. */ + uint8_t tlb_fill_flags; + + /* + * Additional tlb flags for use by the slow path. If non-zero, + * the corresponding CPUTLBEntry comparator must have TLB_FORCE_SLOW. + */ + uint8_t slow_flags[MMU_ACCESS_COUNT]; + + /* Target-specific and S2E additions. */ + struct { + /* The KLEE ObjectState that backs the page in the current state, or + NULL. libs2ecore owns the field (S2EExecutionStateTlb). */ + void *object_state; + } extra; +} CPUTLBEntryFull; + +/* + * Data elements that are per MMU mode, minus the bits accessed by + * the TCG fast path. + */ typedef struct CPUTLBDesc { - target_phys_addr_t iotlb[CPU_TLB_SIZE]; - /* Backing store for the fast-path table; f[i].table points here. */ - CPUTLBEntry table[CPU_TLB_SIZE]; + /* + * Describe a region covering all of the large pages allocated + * into the tlb. When any page within this region is flushed, + * we must flush the entire tlb. The region is matched if + * (addr & large_page_mask) == large_page_addr. + */ + vaddr large_page_addr; + vaddr large_page_mask; + /* host time (in ns) at the beginning of the time window */ + int64_t window_begin_ns; + /* maximum number of entries observed in the window */ + size_t window_max_entries; + size_t n_used_entries; + /* The next index to use in the tlb victim table. */ + size_t vindex; + /* The tlb victim table, in two parts. */ + CPUTLBEntry vtable[CPU_VTLB_SIZE]; + CPUTLBEntryFull vfulltlb[CPU_VTLB_SIZE]; + /* Points at se_fulltlb below. */ + CPUTLBEntryFull *fulltlb; + + /* Backing store of f[i].table and of fulltlb (S2E). */ + CPUTLBEntry se_table[CPU_TLB_SIZE]; + CPUTLBEntryFull se_fulltlb[CPU_TLB_SIZE]; } CPUTLBDesc; +/* + * Data elements that are shared between all MMU modes. + */ +typedef struct CPUTLBCommon { + /* Upstream serializes TLB updates with this lock. libcpu has one vCPU + and never takes it. */ + int lock; + /* + * Within dirty, for each bit N, modifications have been made to + * mmu_idx N since the last time that mmu_idx was flushed. + */ + MMUIdxMap dirty; + /* Statistics. */ + size_t full_flush_count; + size_t part_flush_count; + size_t elide_flush_count; +} CPUTLBCommon; + /* The entire softmmu tlb, for all MMU modes. */ typedef struct CPUTLB { + CPUTLBCommon c; CPUTLBDesc d[NB_MMU_MODES]; CPUTLBDescFast f[NB_MMU_MODES]; - /* Region covered by large pages, one pair for all MMU modes; invalidating - it forces a full flush (upstream 11.1 tracks this per CPUTLBDesc). */ - target_ulong tlb_flush_addr; - target_ulong tlb_flush_mask; } CPUTLB; /* @@ -109,11 +213,10 @@ typedef struct CPUNegativeOffsetState { /* The RAM TLB has no CPUTLBDescFast and keeps its own pinned size (PORTING.md 9.2). */ CPUTLBRAMEntry se_ram_tlb[CPU_TLB_SIZE]; #endif - /* Cached by the softmmu IO path; points into the tables above, so it - lives and dies with them (PORTING.md 9.6). */ - CPUTLBEntry *se_tlb_current; - struct TranslationBlock *tb_jmp_cache[TB_JMP_CACHE_SIZE]; + + /* Always true: libcpu has no icount mode. */ + bool can_do_io; } CPUNegativeOffsetState; /* @@ -126,9 +229,13 @@ typedef struct CPUNegativeOffsetState { * exception_index, generate_llvm) survive a reset. */ typedef struct CPUState { - /* Replaces upstream's cpu->cc->tcg_ops; wired up when the 11.1 accel/tcg - code lands (PORTING.md 3.1). */ - const struct TCGCPUOps *tcg_ops; + /* Gives the accel/tcg code its cpu->cc->tcg_ops. Bitcode must not follow + the pointer: the class is not registered with KLEE. */ + const CPUClass *cc; + + /* Fields that the accel/tcg code reads and that libcpu never changes. */ + bool created; + bool ignore_memory_transaction_failures; int cpu_index; @@ -149,9 +256,9 @@ typedef struct CPUState { function still names the original TB (S2E). */ struct TranslationBlock *se_current_tb; - /* Softmmu support: the host pc and the guest virtual address of the - memory access being handled, so that the MMIO helpers can restore the - CPU state without more arguments. */ + /* Softmmu support: the return address into generated code of the memory + access being handled, so that the MMIO and TB invalidation code can + restore the CPU state without more arguments. */ uintptr_t mem_io_pc; target_ulong mem_io_vaddr; diff --git a/libcpu/include/cpu/tlb.h b/libcpu/include/cpu/tlb.h index 611d39b4b..cfc6d2d19 100644 --- a/libcpu/include/cpu/tlb.h +++ b/libcpu/include/cpu/tlb.h @@ -23,12 +23,14 @@ #include #include -#include +#include +#include #ifdef __cplusplus extern "C" { #endif +/* The TLB size is pinned (src/accel/tlb-bounds.h must agree). */ #define CPU_TLB_BITS 10 #define CPU_TLB_SIZE (1 << CPU_TLB_BITS) diff --git a/libcpu/src/CMakeLists.txt b/libcpu/src/CMakeLists.txt index e8f13a8e3..a58c8e99e 100644 --- a/libcpu/src/CMakeLists.txt +++ b/libcpu/src/CMakeLists.txt @@ -2,12 +2,16 @@ # This work is licensed under the terms of the GNU LGPL, version 2.1 or later. add_library( - cpu cpu-exec.c cpus.c exec.c exec-bp.c exec-memdbg.c exec-phys.c exec-phystb.c exec-ram.c exec-tb.c exec-tlb.c ioport.c memory.c timer.c translate-all.c - precise-pc.c + cpu cpu-exec.c cpus.c exec.c exec-bp.c exec-memdbg.c exec-phystb.c exec-ram.c exec-tb.c ioport.c memory.c timer.c translate-all.c + precise-pc.c accel/cputlb.c target-i386/cpuid.c target-i386/helper.c target-i386/op_helper.c target-i386/translate.c disas.c ) +# cputlb.c replaces the load and store primitives of ldst_atomicity.c.inc in +# builds with symbolic execution, which leaves the upstream ones unused. +set_source_files_properties(accel/cputlb.c PROPERTIES COMPILE_OPTIONS "-Wno-unused-function") + target_include_directories (cpu PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/../include @@ -37,11 +41,16 @@ foreach(dir ${dirs}) endforeach() separate_arguments(BC_INC_DIRS) +# The bitcode library that KLEE interprets: the helpers, the softmmu access +# path (accel/cputlb.c) and softfloat. +set(BC_FLAGS ${CARGS_LIST} -Wno-unused-function -O3 -DSYMBEX_LLVM_LIB -march=x86-64 -emit-llvm ${BC_INC_DIRS} -fno-slp-vectorize -fno-tree-vectorize) + add_custom_target( op_helper_bc ALL - clang-19 ${CMAKE_CURRENT_SOURCE_DIR}/target-i386/op_helper.c -c ${CARGS_LIST} -Wno-unused-function -O3 -DSYMBEX_LLVM_LIB -march=x86-64 -emit-llvm -o ${CMAKE_CURRENT_BINARY_DIR}/op_helper-org.bc ${BC_INC_DIRS} -fno-slp-vectorize -fno-tree-vectorize - COMMAND llvm-link-19 ${CMAKE_CURRENT_BINARY_DIR}/op_helper-org.bc ${LIBTCG_DIR}/src/softfloat.bc -o ${CMAKE_CURRENT_BINARY_DIR}/op_helper.bc - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/target-i386/op_helper.c + clang-19 ${CMAKE_CURRENT_SOURCE_DIR}/target-i386/op_helper.c -c ${BC_FLAGS} -o ${CMAKE_CURRENT_BINARY_DIR}/op_helper-org.bc + COMMAND clang-19 ${CMAKE_CURRENT_SOURCE_DIR}/accel/cputlb.c -c ${BC_FLAGS} -o ${CMAKE_CURRENT_BINARY_DIR}/cputlb.bc + COMMAND llvm-link-19 ${CMAKE_CURRENT_BINARY_DIR}/op_helper-org.bc ${CMAKE_CURRENT_BINARY_DIR}/cputlb.bc ${LIBTCG_DIR}/src/softfloat.bc -o ${CMAKE_CURRENT_BINARY_DIR}/op_helper.bc + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/target-i386/op_helper.c ${CMAKE_CURRENT_SOURCE_DIR}/accel/cputlb.c ) endif (WITH_SYMBEX) diff --git a/libcpu/src/cpu-all.h b/libcpu/src/cpu-all.h index cf761cb77..61c514801 100644 --- a/libcpu/src/cpu-all.h +++ b/libcpu/src/cpu-all.h @@ -21,8 +21,8 @@ #include #include +#include #include -#include #include #include #include "qemu-common.h" @@ -164,8 +164,6 @@ static inline void *_se_check_translate_ram_access(const void *p, unsigned size) return NULL; } -/* Functions suffixed with symb abort execution if it is in concrete mode */ - /* host endianness */ #define _symbex_define_ld_raw(ct, t, s) \ static inline ct ld##t##_raw(const void *p) { \ @@ -176,11 +174,6 @@ static inline void *_se_check_translate_ram_access(const void *p, unsigned size) uint8_t buf[s]; \ g_sqi.mem.read_ram_concrete((uint64_t) p, buf, s); \ return ld##t##_p(buf); /* read right type of value from buf */ \ - } \ - static inline ct ld##t##_raw_symb(const void *p) { \ - uint8_t buf[s]; \ - g_sqi.mem.read_ram_concrete_check((uint64_t) p, buf, s); \ - return ld##t##_p(buf); \ } /* explicit little endian */ @@ -189,11 +182,6 @@ static inline void *_se_check_translate_ram_access(const void *p, unsigned size) uint8_t buf[s]; \ g_sqi.mem.read_ram_concrete((uint64_t) p, buf, s); \ return ld##t##_le_p(buf); /* read right type of value from buf */ \ - } \ - static inline ct ld##t##_le_raw_symb(const void *p) { \ - uint8_t buf[s]; \ - g_sqi.mem.read_ram_concrete_check((uint64_t) p, buf, s); \ - return ld##t##_le_p(buf); \ } /* explicit big endian */ @@ -202,11 +190,6 @@ static inline void *_se_check_translate_ram_access(const void *p, unsigned size) uint8_t buf[s]; \ g_sqi.mem.read_ram_concrete((uint64_t) p, buf, s); \ return ld##t##_be_p(buf); /* read right type of value from buf */ \ - } \ - static inline ct ld##t##_be_raw_symb(const void *p) { \ - uint8_t buf[s]; \ - g_sqi.mem.read_ram_concrete_check((uint64_t) p, buf, s); \ - return ld##t##_be_p(buf); \ } /* host endianness */ @@ -220,9 +203,6 @@ static inline void *_se_check_translate_ram_access(const void *p, unsigned size) uint8_t buf[s]; \ st##t##_p(buf, v); \ g_sqi.mem.write_ram_concrete((uint64_t) p, buf, s); \ - } \ - static inline void st##t##_raw_symb(void *p, ct v) { \ - st##t##_raw(p, v); \ } /* explicit little endian */ @@ -231,9 +211,6 @@ static inline void *_se_check_translate_ram_access(const void *p, unsigned size) uint8_t buf[s]; \ st##t##_le_p(buf, v); \ g_sqi.mem.write_ram_concrete((uint64_t) p, buf, s); \ - } \ - static inline void st##t##_le_raw_symb(void *p, ct v) { \ - st##t##_le_raw(p, v); \ } /* explicit big endian */ @@ -242,9 +219,6 @@ static inline void *_se_check_translate_ram_access(const void *p, unsigned size) uint8_t buf[s]; \ st##t##_be_p(buf, v); \ g_sqi.mem.write_ram_concrete((uint64_t) p, buf, s); \ - } \ - static inline void st##t##_be_raw_symb(void *p, ct v) { \ - st##t##_be_raw(p, v); \ } // clang-format off diff --git a/libcpu/src/exec-all.h b/libcpu/src/exec-all.h index 0a22e677b..d9130dd06 100644 --- a/libcpu/src/exec-all.h +++ b/libcpu/src/exec-all.h @@ -77,9 +77,6 @@ void cpu_exec_init(CPUArchState *env); int page_unprotect(target_ulong address, uintptr_t pc, void *puc); void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end, int is_cpu_write_access); -void tlb_set_page(CPUArchState *env, target_ulong vaddr, target_phys_addr_t paddr, int prot, int mmu_idx, - target_ulong size); - #define CODE_GEN_ALIGN 16 /* must be >= of the size of a icache line */ #define CODE_GEN_PHYS_HASH_BITS 15 @@ -122,29 +119,27 @@ extern int tb_invalidated_flag; #include -#include #include -#define ACCESS_TYPE (NB_MMU_MODES + 1) -#define MEMSUFFIX _code - -#define DATA_SIZE 1 -#include "softmmu_header.h" - -#define DATA_SIZE 2 -#include "softmmu_header.h" - -#define DATA_SIZE 4 -#include "softmmu_header.h" - -#define DATA_SIZE 8 -#include "softmmu_header.h" - -#undef ACCESS_TYPE -#undef MEMSUFFIX -#undef env - -tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr); +#include "softmmu-compat.h" + +/* Entry points of accel/cputlb.c that upstream declares in + accel/tcg/internal-common.h. */ +void tlb_init(CPUState *cpu); +void tlb_destroy(CPUState *cpu); +tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr, void **hostp); + +/* Returns the ram address of the code page at addr, filling the TLB and + raising a guest exception if needed. libcpu cannot execute code from MMIO: + it has no way to translate one instruction at a time without caching. */ +static inline tb_page_addr_t get_page_addr_code(CPUArchState *env, target_ulong addr) { + void *host; + tb_page_addr_t ret = get_page_addr_code_hostp(env, addr, &host); + if (ret == -1) { + cpu_abort(env, "Trying to execute code outside RAM or ROM at 0x" TARGET_FMT_lx "\n", addr); + } + return ret; +} typedef void(CPUDebugExcpHandler)(CPUArchState *env); diff --git a/libcpu/src/exec-bp.c b/libcpu/src/exec-bp.c index b3cc6223a..007847afb 100644 --- a/libcpu/src/exec-bp.c +++ b/libcpu/src/exec-bp.c @@ -65,7 +65,7 @@ int cpu_watchpoint_insert(CPUArchState *env, target_ulong addr, target_ulong len else QTAILQ_INSERT_TAIL(&env_cpu(env)->watchpoints, wp, entry); - tlb_flush_page(env, addr); + tlb_flush_page(env_cpu(env), addr); if (watchpoint) *watchpoint = wp; @@ -90,7 +90,7 @@ int cpu_watchpoint_remove(CPUArchState *env, target_ulong addr, target_ulong len void cpu_watchpoint_remove_by_ref(CPUArchState *env, CPUWatchpoint *watchpoint) { QTAILQ_REMOVE(&env_cpu(env)->watchpoints, watchpoint, entry); - tlb_flush_page(env, watchpoint->vaddr); + tlb_flush_page(env_cpu(env), watchpoint->vaddr); g_free(watchpoint); } @@ -185,16 +185,47 @@ void cpu_single_step(CPUArchState *env, int enabled) { #endif } -/* Generate a debug exception if a watchpoint has been hit. */ -static void check_watchpoint(int offset, int len_mask, int flags) { - CPUArchState *env = cpu_single_env; +/* Returns the length of the range that a watchpoint covers. */ +static inline vaddr watchpoint_len(const CPUWatchpoint *wp) { + return (vaddr) (target_ulong) ~wp->len_mask + 1; +} + +static inline bool watchpoint_address_matches(const CPUWatchpoint *wp, vaddr addr, vaddr len) { + /* Compare the last bytes of the two ranges instead of their ends, so + that a range that ends at the top of the address space does not wrap + around to zero. */ + vaddr wpend = wp->vaddr + watchpoint_len(wp) - 1; + vaddr addrend = addr + len - 1; + + return !(addr > wpend || wp->vaddr > addrend); +} + +/* Returns the flags of the watchpoints that overlap [addr, addr + len). + tlb_set_page_full() calls it to decide whether accesses to a page must + take the slow path (TLB_WATCHPOINT). */ +int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len) { + CPUWatchpoint *wp; + int ret = 0; + + QTAILQ_FOREACH (wp, &cpu->watchpoints, entry) { + if (watchpoint_address_matches(wp, addr, len)) { + ret |= wp->flags; + } + } + return ret; +} + +/* Generates a debug exception if the access hits a watchpoint. The softmmu + calls it for accesses to pages that carry TLB_WATCHPOINT. ra is the return + address of the access into generated code. */ +void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len, MemTxAttrs attrs, int flags, uintptr_t ra) { + CPUArchState *env = cpu_env(cpu); target_ulong pc, cs_base; TranslationBlock *tb; - target_ulong vaddr; CPUWatchpoint *wp; int cpu_flags; - if (env_cpu(env)->watchpoint_hit) { + if (cpu->watchpoint_hit) { /* We re-entered the check after replacing the TB. Now raise * the debug interrupt so that is will trigger after the * current instruction. */ @@ -202,28 +233,22 @@ static void check_watchpoint(int offset, int len_mask, int flags) { return; } -#ifdef CONFIG_SYMBEX - vaddr = (g_sqi.mem.read_mem_io_vaddr(1)) + offset; -#else - vaddr = (env_cpu(env)->mem_io_vaddr & TARGET_PAGE_MASK) + offset; -#endif - - QTAILQ_FOREACH (wp, &env_cpu(env)->watchpoints, entry) { - if ((vaddr == (wp->vaddr & len_mask) || (vaddr & wp->len_mask) == wp->vaddr) && (wp->flags & flags)) { + QTAILQ_FOREACH (wp, &cpu->watchpoints, entry) { + if ((wp->flags & flags) && watchpoint_address_matches(wp, addr, len)) { wp->flags |= BP_WATCHPOINT_HIT; - if (!env_cpu(env)->watchpoint_hit) { - env_cpu(env)->watchpoint_hit = wp; - tb = tcg_tb_lookup(env_cpu(env)->mem_io_pc); + if (!cpu->watchpoint_hit) { + cpu->watchpoint_hit = wp; + tb = tcg_tb_lookup(ra); if (!tb) { cpu_abort(env, "check_watchpoint: could not find TB for " "pc=%p", - (void *) env_cpu(env)->mem_io_pc); + (void *) ra); } - cpu_restore_state(env, env_cpu(env)->mem_io_pc); + cpu_restore_state(env, ra); tb_phys_invalidate(tb, -1); if (wp->flags & BP_STOP_BEFORE_ACCESS) { - env_cpu(env)->exception_index = EXCP_DEBUG; + cpu->exception_index = EXCP_DEBUG; cpu_loop_exit(env); } else { cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags); @@ -236,42 +261,3 @@ static void check_watchpoint(int offset, int len_mask, int flags) { } } } - -/* Watchpoint access routines. Watchpoints are inserted using TLB tricks, - so these check for a hit then pass through to the normal out-of-line - phys routines. */ -static uint64_t watch_mem_read(target_phys_addr_t addr, unsigned size) { - check_watchpoint(addr & ~TARGET_PAGE_MASK, ~(size - 1), BP_MEM_READ); - switch (size) { - case 1: - return ldub_phys(addr); - case 2: - return lduw_phys(addr); - case 4: - return ldl_phys(addr); - default: - abort(); - } -} - -static void watch_mem_write(target_phys_addr_t addr, uint64_t val, unsigned size) { - check_watchpoint(addr & ~TARGET_PAGE_MASK, ~(size - 1), BP_MEM_WRITE); - switch (size) { - case 1: - stb_phys(addr, val); - break; - case 2: - stw_phys(addr, val); - break; - case 4: - stl_phys(addr, val); - break; - default: - abort(); - } -} - -const struct MemoryDescOps watch_mem_ops = { - .read = watch_mem_read, - .write = watch_mem_write, -}; diff --git a/libcpu/src/exec-phys.c b/libcpu/src/exec-phys.c deleted file mode 100644 index cd23446c6..000000000 --- a/libcpu/src/exec-phys.c +++ /dev/null @@ -1,56 +0,0 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -#include -#include -#include - -#include -#include "exec.h" -#include "qemu-common.h" - -const uint16_t phys_section_unassigned = 0; -const uint16_t phys_section_notdirty = 1; -const uint16_t phys_section_rom = 2; -const uint16_t phys_section_watch = 3; - -static const uint64_t phys_section_max_dummy = 4; - -static struct MemoryDescOps s_memops[phys_section_max_dummy]; - -//////////////////////////////////////////////////////////////////////////////////////// -/// Public functions - -void phys_register_section(unsigned index, const struct MemoryDescOps *ops) { - assert(index < phys_section_max_dummy); - s_memops[index] = *ops; -} - -const struct MemoryDescOps *phys_get_ops(target_phys_addr_t index) { - unsigned idx = index & ~TARGET_PAGE_MASK; - assert(idx < phys_section_max_dummy); - return &s_memops[idx]; -} - -const MemoryDesc *phys_page_find(target_phys_addr_t index) { - return mem_desc_find(index << TARGET_PAGE_BITS); -} - -bool is_notdirty_ops(const struct MemoryDescOps *ops) { - return &s_memops[phys_section_notdirty] == ops; -} diff --git a/libcpu/src/exec-phys.h b/libcpu/src/exec-phys.h deleted file mode 100644 index 31e0324a5..000000000 --- a/libcpu/src/exec-phys.h +++ /dev/null @@ -1,33 +0,0 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -#ifndef __EXEC_PHYS_H__ - -#define __EXEC_PHYS_H__ - -#include -#include - -extern const uint16_t phys_section_unassigned; -extern const uint16_t phys_section_notdirty; -extern const uint16_t phys_section_rom; -extern const uint16_t phys_section_watch; - -void phys_register_section(unsigned index, const struct MemoryDescOps *ops); - -#endif diff --git a/libcpu/src/exec-tb.c b/libcpu/src/exec-tb.c index 28f3d7d3f..e25268f77 100644 --- a/libcpu/src/exec-tb.c +++ b/libcpu/src/exec-tb.c @@ -445,12 +445,7 @@ void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end, int if (!p->first_tb) { invalidate_page_bitmap(p); if (is_cpu_write_access) { -#ifdef CONFIG_SYMBEX_MP - target_ulong iovaddr = g_sqi.mem.read_mem_io_vaddr(1); - tlb_unprotect_code_phys(env, start, iovaddr); -#else - tlb_unprotect_code_phys(env, start, env_cpu(env)->mem_io_vaddr); -#endif + tlb_unprotect_code(start); } } } @@ -459,14 +454,6 @@ void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end, int void tb_invalidate_phys_page_fast(tb_page_addr_t start, int len) { PageDesc *p; int offset, b; -#if 0 - if (1) { - libcpu_log("modifying code at 0x%x size=%d EIP=%x PC=%08x\n", - env_cpu(cpu_single_env)->mem_io_vaddr, len, - cpu_single_env->eip, - cpu_single_env->eip + (long)cpu_single_env->segs[R_CS].base); - } -#endif p = page_find(start >> TARGET_PAGE_BITS); if (!p) return; diff --git a/libcpu/src/exec-tlb.c b/libcpu/src/exec-tlb.c deleted file mode 100644 index 4f2b1386c..000000000 --- a/libcpu/src/exec-tlb.c +++ /dev/null @@ -1,317 +0,0 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -#include -#include -#include -#include -#include "qemu-common.h" - -#include "exec-phys.h" -#include "exec-ram.h" -#include "exec-tlb.h" -#include "exec.h" - -/* statistics */ -int g_tlb_flush_count; - -static inline void tlb_flush_jmp_cache(CPUArchState *env, target_ulong addr) { - unsigned int i; - - /* Discard jump cache entries for any tb which might potentially - overlap the flushed page. */ - i = tb_jmp_cache_hash_page(addr - TARGET_PAGE_SIZE); - memset(&env_cpu(env)->neg.tb_jmp_cache[i], 0, TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *)); - - i = tb_jmp_cache_hash_page(addr); - memset(&env_cpu(env)->neg.tb_jmp_cache[i], 0, TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *)); -} - -static const CPUTLBEntry s_cputlb_empty_entry = { - .addr_read = -1, - .addr_write = -1, - .addr_code = -1, - .addend = -1, -#ifdef CONFIG_SYMBEX - .objectState = NULL, -#endif -}; - -/* NOTE: - * If flush_global is true (the usual case), flush all tlb entries. - * If flush_global is false, flush (at least) all tlb entries not - * marked global. - * - * Since QEMU doesn't currently implement a global/not-global flag - * for tlb entries, at the moment tlb_flush() will also flush all - * tlb entries in the flush_global == false case. This is OK because - * CPU architectures generally permit an implementation to drop - * entries from the TLB at any time, so flushing more entries than - * required is only an efficiency issue, not a correctness issue. - */ - -#ifdef CONFIG_SYMBEX -int g_se_disable_tlb_flush = 0; -#endif - -void tlb_flush(CPUArchState *env, int flush_global) { - int i; - -#ifdef CONFIG_SYMBEX - if (g_se_disable_tlb_flush) { - return; - } -#endif - -#if defined(DEBUG_TLB) - printf("tlb_flush:\n"); -#endif - /* must reset current TB so that interrupts cannot modify the - links while we are modifying them */ - env_cpu(env)->current_tb = NULL; - - int mmu_idx; - CPUTLB *tlb = env_tlb(env); - for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - tlb->f[mmu_idx].mask = (CPU_TLB_SIZE - 1) << CPU_TLB_ENTRY_BITS; - tlb->f[mmu_idx].table = &tlb->d[mmu_idx].table[0]; - for (i = 0; i < CPU_TLB_SIZE; i++) { - tlb->f[mmu_idx].table[i] = s_cputlb_empty_entry; - } - } - -#if defined(CONFIG_SYMBEX) && defined(SE_ENABLE_TLB) - if (!*g_sqi.mode.single_path_mode) { - g_sqi.tlb.flush_tlb_cache(); - } -#endif - - memset(env_cpu(env)->neg.tb_jmp_cache, 0, TB_JMP_CACHE_SIZE * sizeof(void *)); - - tlb->tlb_flush_addr = -1; - tlb->tlb_flush_mask = 0; - g_tlb_flush_count++; -} - -void tlb_flush_page(CPUArchState *env, target_ulong addr) { - int i; - int mmu_idx; - -#if defined(DEBUG_TLB) - printf("tlb_flush_page: " TARGET_FMT_lx "\n", addr); -#endif - /* Check if we need to flush due to large pages. */ - if ((addr & env_tlb(env)->tlb_flush_mask) == env_tlb(env)->tlb_flush_addr) { -#if defined(DEBUG_TLB) - printf("tlb_flush_page: forced full flush (" TARGET_FMT_lx "/" TARGET_FMT_lx ")\n", - env_tlb(env)->tlb_flush_addr, env_tlb(env)->tlb_flush_mask); -#endif - tlb_flush(env, 1); - return; - } - /* must reset current TB so that interrupts cannot modify the - links while we are modifying them */ - env_cpu(env)->current_tb = NULL; - - addr &= TARGET_PAGE_MASK; - i = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); - for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - CPUTLBEntry *tlb_entry = &env_tlb(env)->f[mmu_idx].table[i]; - if (addr == (tlb_entry->addr_read & (TARGET_PAGE_MASK | TLB_INVALID_MASK)) || - addr == (tlb_entry->addr_write & (TARGET_PAGE_MASK | TLB_INVALID_MASK)) || - addr == (tlb_entry->addr_code & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) { -#if defined(CONFIG_SYMBEX) - g_sqi.tlb.flush_tlb_cache_page(tlb_entry->objectState, mmu_idx, i); -#endif - *tlb_entry = s_cputlb_empty_entry; - } - } - - tlb_flush_jmp_cache(env, addr); -} - -/* update the TLBs so that writes to code in the virtual page 'addr' - can be detected */ -void tlb_protect_code(ram_addr_t ram_addr) { - cpu_physical_memory_reset_dirty(ram_addr, ram_addr + TARGET_PAGE_SIZE, CODE_DIRTY_FLAG); -} - -/* update the TLB so that writes in physical page 'phys_addr' are no longer - tested for self modifying code */ -void tlb_unprotect_code_phys(CPUArchState *env, ram_addr_t ram_addr, target_ulong vaddr) { - cpu_physical_memory_set_dirty_flags(ram_addr, CODE_DIRTY_FLAG); -} - -#ifdef CONFIG_SYMBEX -static inline int tlb_get_dirty1(CPUTLBEntry *tlb_entry, target_ulong vaddr) { - return ((tlb_entry->addr_write & ~TLB_SYMB) == vaddr); -} - -int tlb_is_dirty(CPUArchState *env, target_ulong vaddr) { - int i; - int mmu_idx; - int ret = 1; - - vaddr &= TARGET_PAGE_MASK; - i = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); - for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - ret &= tlb_get_dirty1(&env_tlb(env)->f[mmu_idx].table[i], vaddr); - } - - return ret; -} -#endif - -/* Our TLB does not support large pages, so remember the area covered by - large pages and trigger a full TLB flush if these are invalidated. */ -static void tlb_add_large_page(CPUArchState *env, target_ulong vaddr, target_ulong size) { - target_ulong mask = ~(size - 1); - CPUTLB *tlb = env_tlb(env); - - if (tlb->tlb_flush_addr == (target_ulong) -1) { - tlb->tlb_flush_addr = vaddr & mask; - tlb->tlb_flush_mask = mask; - return; - } - /* Extend the existing region to include the new page. - This is a compromise between unnecessary flushes and the cost - of maintaining a full variable size TLB. */ - mask &= tlb->tlb_flush_mask; - while (((tlb->tlb_flush_addr ^ vaddr) & mask) != 0) { - mask <<= 1; - } - tlb->tlb_flush_addr &= mask; - tlb->tlb_flush_mask = mask; -} - -/* Add a new TLB entry. At most one entry for a given virtual address - is permitted. Only a single TARGET_PAGE_SIZE region is mapped, the - supplied size is only used by tlb_flush_page. */ -void tlb_set_page(CPUArchState *env, target_ulong vaddr, target_phys_addr_t paddr, int prot, int mmu_idx, - target_ulong size) { - unsigned int index; - target_ulong address; - target_ulong code_address; - unsigned long addend; - CPUTLBEntry *te; - CPUWatchpoint *wp; - target_phys_addr_t iotlb; - - assert(size >= TARGET_PAGE_SIZE); - if (size != TARGET_PAGE_SIZE) { - tlb_add_large_page(env, vaddr, size); - } - - const MemoryDesc *sreg = mem_desc_find(paddr); - -#if defined(DEBUG_TLB) - printf("tlb_set_page: vaddr=" TARGET_FMT_lx " paddr=0x" TARGET_FMT_plx " prot=%x idx=%d pd=0x%08lx\n", vaddr, paddr, - prot, mmu_idx, pd); -#endif - - address = vaddr; - - if (sreg) { - // RAM - addend = mem_desc_addend(sreg, paddr); - iotlb = (sreg->ram_addr & TARGET_PAGE_MASK) + mem_desc_get_offset(sreg, paddr); - iotlb |= phys_section_notdirty; - } else { - // Everything else (MMIO) - address |= TLB_MMIO; - addend = 0; - iotlb = paddr; - } - - code_address = address; - /* Make accesses to pages with watchpoints go via the - watchpoint trap routines. */ - QTAILQ_FOREACH (wp, &env_cpu(env)->watchpoints, entry) { - if (vaddr == (wp->vaddr & TARGET_PAGE_MASK)) { - /* Avoid trapping reads of pages with a write breakpoint. */ - if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) { - iotlb = phys_section_watch + paddr; - address |= TLB_MMIO; - break; - } - } - } - - index = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); - env_tlb(env)->d[mmu_idx].iotlb[index] = iotlb - vaddr; - - te = &env_tlb(env)->f[mmu_idx].table[index]; - te->addend = addend - vaddr; - if (prot & PAGE_READ) { - te->addr_read = address; - } else { - te->addr_read = -1; - } - - if (prot & PAGE_EXEC) { - te->addr_code = code_address; - } else { - te->addr_code = -1; - } - - if (prot & PAGE_WRITE) { - if (sreg) { - // RAM - int dirty = cpu_physical_memory_is_dirty(sreg->ram_addr + mem_desc_get_offset(sreg, paddr)); - if (!dirty) { - te->addr_write = address | TLB_NOTDIRTY; - } else { - te->addr_write = address; - } - } else { - // MMIO - te->addr_write = address | TLB_MMIO; - } - } else { - te->addr_write = -1; - } - -#if defined(CONFIG_SYMBEX_MP) - if (g_sqi.mem.is_mmio_symbolic(paddr, 1LL << TARGET_PAGE_BITS)) { - // We hijack qemu's dirty page management to redirect - // all accesses to MMIO memory through our handlers. - // Note: Such ranges can be less than one page long, so we have to - // deal with normal memory accesses as well... - te->addr_read |= TLB_NOTDIRTY; - - // We also need to track writes to DMA memory, - // symbolic hardware might be interested in that. - te->addr_write |= TLB_MMIO; - } -#endif -#if defined(CONFIG_SYMBEX) - - if (*g_sqi.events.before_memory_access_signals_count || *g_sqi.events.after_memory_access_signals_count) { - te->addr_read |= TLB_MEM_TRACE; - te->addr_write |= TLB_MEM_TRACE; - } -#endif - -#if defined(CONFIG_SYMBEX) && defined(SE_ENABLE_TLB) && defined(CONFIG_SYMBEX_MP) - if (addend) { - // I/O devices don't need to have an SE TLB entry because - // MMIO goes directly to the device handlers. - g_sqi.tlb.update_tlb_entry(env, mmu_idx, vaddr, addend); - } -#endif -} diff --git a/libcpu/src/exec-tlb.h b/libcpu/src/exec-tlb.h deleted file mode 100644 index b60dde59b..000000000 --- a/libcpu/src/exec-tlb.h +++ /dev/null @@ -1,64 +0,0 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -#ifndef __EXEC_TLB_H__ - -#define __EXEC_TLB_H__ - -static inline void tlb_set_dirty1(CPUTLBEntry *tlb_entry, target_ulong vaddr) { -#ifdef CONFIG_SYMBEX - if ((tlb_entry->addr_write & ~TLB_SYMB) == (vaddr | TLB_NOTDIRTY)) { -#else - if (tlb_entry->addr_write == (vaddr | TLB_NOTDIRTY)) { -#endif - tlb_entry->addr_write &= ~TLB_NOTDIRTY; - } -} - -/* update the TLB corresponding to virtual page vaddr - so that it is no longer dirty */ -static inline void tlb_set_dirty(CPUArchState *env, target_ulong vaddr) { - int i; - int mmu_idx; - - vaddr &= TARGET_PAGE_MASK; - i = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); - for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - tlb_set_dirty1(&env_tlb(env)->f[mmu_idx].table[i], vaddr); - } -} - -static bool tlb_is_dirty_ram(CPUTLBEntry *tlbe) { - return (tlbe->addr_write & (TLB_INVALID_MASK | TLB_MMIO | TLB_NOTDIRTY)) == 0; -} - -static inline void tlb_reset_dirty_range(CPUTLBEntry *tlb_entry, unsigned long start, unsigned long length) { - unsigned long addr; - if (tlb_is_dirty_ram(tlb_entry)) { - addr = (tlb_entry->addr_write & TARGET_PAGE_MASK) + tlb_entry->addend; - if ((addr - start) < length) { - tlb_entry->addr_write |= TLB_NOTDIRTY; - } - } -} - -#ifdef CONFIG_SYMBEX -int tlb_is_dirty(CPUArchState *env, target_ulong vaddr); -#endif - -#endif diff --git a/libcpu/src/exec.c b/libcpu/src/exec.c index 66a610102..ba964816b 100644 --- a/libcpu/src/exec.c +++ b/libcpu/src/exec.c @@ -33,10 +33,8 @@ #include #include #endif -#include "exec-phys.h" #include "exec-ram.h" #include "exec-tb.h" -#include "exec-tlb.h" #include "exec.h" // #define DEBUG_TB_INVALIDATE @@ -58,16 +56,27 @@ CPUArchState *first_cpu, *cpu_single_env; #ifdef CONFIG_SYMBEX struct se_libcpu_interface_t g_sqi; + +/* Nonzero while libs2ecore switches execution states. The TLB flush + functions of accel/cputlb.c return without doing anything during that + time, see se_tlb_flush_disabled(). */ +int g_se_disable_tlb_flush = 0; #endif -static void io_mem_init(void); +#ifdef CONFIG_SYMBEX +static uint32_t se_ldub_code(CPUArchState *env, target_ulong addr) { + return cpu_ldub_code(env, addr); +} -void cpu_exec_init_all(void) { - io_mem_init(); +static uint32_t se_ldl_code(CPUArchState *env, target_ulong addr) { + return cpu_ldl_code(env, addr); +} +#endif +void cpu_exec_init_all(void) { #ifdef CONFIG_SYMBEX - g_sqi.libcpu.ldub_code = cpu_ldub_code; - g_sqi.libcpu.ldl_code = cpu_ldl_code; + g_sqi.libcpu.ldub_code = se_ldub_code; + g_sqi.libcpu.ldl_code = se_ldl_code; #endif } @@ -79,8 +88,13 @@ void cpu_exec_init(CPUArchState *env) { first_cpu = env; cpu->cpu_index = 0; + cpu->cc = &g_x86_cpu_class; + cpu->created = true; + cpu->neg.can_do_io = true; QTAILQ_INIT(&cpu->breakpoints); QTAILQ_INIT(&cpu->watchpoints); + + tlb_init(cpu); } void cpu_common_reset(CPUState *cpu) { @@ -145,7 +159,6 @@ void cpu_abort(CPUArchState *env, const char *fmt, ...) { void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t end, int dirty_flags) { CPUArchState *env; unsigned long length, start1; - int i; start &= TARGET_PAGE_MASK; end = TARGET_PAGE_ALIGN(end); @@ -166,11 +179,7 @@ void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t end, int dirty env = first_cpu; if (env) { - int mmu_idx; - for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - for (i = 0; i < CPU_TLB_SIZE; i++) - tlb_reset_dirty_range(&env_tlb(env)->f[mmu_idx].table[i], start1, length); - } + tlb_reset_dirty(env_cpu(env), start1, length); } } @@ -183,181 +192,6 @@ uintptr_t se_get_host_address(target_phys_addr_t paddr) { return sreg->kvm.userspace_addr + mem_desc_get_offset(sreg, paddr); } -#if defined(__linux__) && !defined(TARGET_S390X) - -static void unassigned_mem_write(target_phys_addr_t addr, uint64_t val, unsigned size) { -#ifdef DEBUG_UNASSIGNED - printf("Unassigned mem write " TARGET_FMT_plx " = 0x%" PRIx64 "\n", addr, val); -#endif -#if defined(TARGET_ALPHA) || defined(TARGET_SPARC) || defined(TARGET_MICROBLAZE) - cpu_unassigned_access(cpu_single_env, addr, 1, 0, 0, size); -#endif -} - -/** All writes to unassigned memory cause a vm exit */ -static const struct MemoryDescOps unassigned_mem_ops = { - .read = cpu_mmio_read, - .write = cpu_mmio_write, -}; - -static uint64_t error_mem_read(target_phys_addr_t addr, unsigned size) { - abort(); -} - -static const struct MemoryDescOps rom_mem_ops = { - .read = error_mem_read, - .write = unassigned_mem_write, -}; - -static void notdirty_mem_write(target_phys_addr_t ram_addr, uint64_t val, unsigned size) { - int dirty_flags; - dirty_flags = cpu_physical_memory_get_dirty_flags(ram_addr); - if (!(dirty_flags & CODE_DIRTY_FLAG)) { - tb_invalidate_phys_page_fast(ram_addr, size); - dirty_flags = cpu_physical_memory_get_dirty_flags(ram_addr); - } - - switch (size) { - case 1: - stb_raw(qemu_get_ram_ptr(ram_addr), val); - break; - case 2: - stw_raw(qemu_get_ram_ptr(ram_addr), val); - break; - case 4: - stl_raw(qemu_get_ram_ptr(ram_addr), val); - break; - default: - abort(); - } - - dirty_flags |= (0xff & ~CODE_DIRTY_FLAG); - cpu_physical_memory_set_dirty_flags(ram_addr, dirty_flags); - /* we remove the notdirty callback only if the code has been - flushed */ - if (dirty_flags == 0xff) { -#ifdef CONFIG_SYMBEX - target_ulong iovaddr = g_sqi.mem.read_mem_io_vaddr(1); - tlb_set_dirty(cpu_single_env, iovaddr); -#else - tlb_set_dirty(cpu_single_env, env_cpu(cpu_single_env)->mem_io_vaddr); -#endif - } -} - -#ifdef CONFIG_SYMBEX -uintptr_t se_notdirty_mem_write(target_phys_addr_t ram_addr, int size) { - int dirty_flags; - - target_ulong iovaddr = g_sqi.mem.read_mem_io_vaddr(1); - - if (tlb_is_dirty(cpu_single_env, iovaddr)) { - return (uintptr_t) qemu_get_ram_ptr(ram_addr); - } - - dirty_flags = cpu_physical_memory_get_dirty_flags(ram_addr); - - if (!(dirty_flags & CODE_DIRTY_FLAG)) { - tb_invalidate_phys_page_fast(ram_addr, size); - dirty_flags = cpu_physical_memory_get_dirty_flags(ram_addr); - } - - dirty_flags |= (0xff & ~CODE_DIRTY_FLAG); - - cpu_physical_memory_set_dirty_flags(ram_addr, dirty_flags); - - /* we remove the notdirty callback only if the code has been - flushed */ - if (dirty_flags == 0xff) - tlb_set_dirty(cpu_single_env, iovaddr); - - return (uintptr_t) qemu_get_ram_ptr(ram_addr); -} - -uintptr_t se_notdirty_mem_read(target_phys_addr_t ram_addr) { - uintptr_t ret = (uintptr_t) qemu_get_ram_ptr(ram_addr); - // g_sqi.log.debug("se_notdirty_mem_read: %llx => %llx\n", ram_addr, ret); - return ret; -} - -/* Some pages might be partially used for DMA. All read accesses outside DMA - regions in a page go here. */ -static uint64_t se_dma_mem_read(target_phys_addr_t ram_addr, unsigned size) { - switch (size) { - case 1: - return ldub_raw(qemu_get_ram_ptr(ram_addr)); - case 2: - return lduw_raw(qemu_get_ram_ptr(ram_addr)); - case 4: - return ldl_raw(qemu_get_ram_ptr(ram_addr)); - case 8: - return ldq_raw(qemu_get_ram_ptr(ram_addr)); - } - assert(false && "Invalid size"); - return 0; -} - -static void se_dma_mem_write(target_phys_addr_t ram_addr, uint64_t val, unsigned size) { - target_ulong iovaddr = g_sqi.mem.read_mem_io_vaddr(1); - if (!tlb_is_dirty(cpu_single_env, iovaddr)) { - notdirty_mem_write(ram_addr, val, size); - return; - } - - switch (size) { - case 1: - stb_raw(qemu_get_ram_ptr(ram_addr), val); - break; - case 2: - stw_raw(qemu_get_ram_ptr(ram_addr), val); - break; - case 4: - stl_raw(qemu_get_ram_ptr(ram_addr), val); - break; - case 8: - stq_raw(qemu_get_ram_ptr(ram_addr), val); - break; - default: - abort(); - } -} - -#endif - -#ifdef CONFIG_SYMBEX -static const struct MemoryDescOps se_dma_mem_ops = { - .read = se_dma_mem_read, - .write = se_dma_mem_write, -}; - -bool se_ismemfunc(const struct MemoryDescOps *ops, int isWrite) { - if (isWrite) { - return ops->write == se_dma_mem_ops.write; - } else { - return ops->read == se_dma_mem_ops.read; - } -} - -#else -static const struct MemoryDescOps notdirty_mem_ops = { - .read = error_mem_read, - .write = notdirty_mem_write, -}; -#endif - -static void io_mem_init(void) { - phys_register_section(phys_section_rom, &rom_mem_ops); - phys_register_section(phys_section_unassigned, &unassigned_mem_ops); -#ifdef CONFIG_SYMBEX - phys_register_section(phys_section_notdirty, &se_dma_mem_ops); -#else - phys_register_section(phys_section_notdirty, ¬dirty_mem_ops); -#endif - phys_register_section(phys_section_watch, &watch_mem_ops); -} - -#endif - /* warning: addr must be aligned */ static inline uint32_t ldl_phys_internal(target_phys_addr_t addr) { uint8_t *ptr; @@ -533,47 +367,3 @@ void stq_be_phys(target_phys_addr_t addr, uint64_t val) { val = cpu_to_be64(val); cpu_physical_memory_write(addr, &val, 8); } - -/* NOTE: this function can trigger an exception */ -/* NOTE2: the returned address is not exactly the physical address: it - is the offset relative to phys_ram_base */ -tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr) { - int mmu_idx, page_index, pd; - void *p; - - page_index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); - mmu_idx = x86_mmu_index(env1); - if (unlikely(env_tlb(env1)->f[mmu_idx].table[page_index].addr_code != (addr & TARGET_PAGE_MASK))) { - cpu_ldub_code(env1, addr); - } - pd = env_tlb(env1)->d[mmu_idx].iotlb[page_index] & ~TARGET_PAGE_MASK; - if (!mem_desc_find(pd)) { -#if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_SPARC) - cpu_unassigned_access(env1, addr, 0, 1, 0, 4); -#else - cpu_abort(env1, "Trying to execute code outside RAM or ROM at 0x" TARGET_FMT_lx "\n", addr); -#endif - } - p = (void *) ((uintptr_t) addr + env_tlb(env1)->f[mmu_idx].table[page_index].addend); - return qemu_ram_addr_from_host_nofail(p); -} - -#define MMUSUFFIX _cmmu -#undef GETPC -#define GETPC() NULL -#define env cpu_single_env -#define SOFTMMU_CODE_ACCESS - -#define SHIFT 0 -#include "softmmu_template.h" - -#define SHIFT 1 -#include "softmmu_template.h" - -#define SHIFT 2 -#include "softmmu_template.h" - -#define SHIFT 3 -#include "softmmu_template.h" - -#undef env diff --git a/libcpu/src/exec.h b/libcpu/src/exec.h index 924a59fdc..4628b49bd 100644 --- a/libcpu/src/exec.h +++ b/libcpu/src/exec.h @@ -54,10 +54,6 @@ #define SMC_BITMAP_USE_THRESHOLD 10 void tlb_protect_code(ram_addr_t ram_addr); -void tlb_unprotect_code_phys(CPUArchState *env, ram_addr_t ram_addr, target_ulong vaddr); - -const MemoryDesc *phys_page_find(target_phys_addr_t index); - -extern const struct MemoryDescOps watch_mem_ops; +void tlb_unprotect_code(ram_addr_t ram_addr); #endif diff --git a/libcpu/src/softmmu-compat.h b/libcpu/src/softmmu-compat.h new file mode 100644 index 000000000..6468e64dd --- /dev/null +++ b/libcpu/src/softmmu-compat.h @@ -0,0 +1,123 @@ +/// Copyright (C) 2026 Vitaly Chipounov +/// Copyrights of all contributions belong to their respective owners. +/// +/// This library is free software; you can redistribute it and/or +/// modify it under the terms of the GNU Library General Public +/// License as published by the Free Software Foundation; either +/// version 2 of the License, or (at your option) any later version. +/// +/// This library is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +/// Library General Public License for more details. +/// +/// You should have received a copy of the GNU Library General Public +/// License along with this library; if not, see . + +/// @file +/// Maps the QEMU 1.0 guest memory accessors onto the accessors of +/// cpu/accel/cpu-ldst.h. +/// +/// The QEMU 1.0 helpers (target-i386/op_helper.c) and translator +/// (target-i386/translate.c) call per-mode functions such as +/// cpu_ldl_kernel(), the ldl() shorthands, and cpu_ldub_code(). The softmmu +/// behind them is now upstream's cputlb.c, which has one function per access +/// size and takes the MMU index as an argument. This header keeps the old +/// names so that the old callers do not have to be edited before the 11.1 +/// frontend replaces them. It goes away with them. +/// +/// Every accessor passes a return address of 0. This tells the softmmu that +/// the caller is not generated code: a fault does not restore the CPU state +/// from a translation block, and symbolic data is concretized instead of +/// triggering a switch to symbolic execution. + +#ifndef S2E_SOFTMMU_COMPAT_H +#define S2E_SOFTMMU_COMPAT_H + +#include + +/* MMU index of kernel mode, see x86_mmu_index(). */ +#define SOFTMMU_COMPAT_KERNEL_IDX 0 + +/* + * Kernel-mode accessors. + */ + +static inline uint32_t cpu_ldub_kernel(CPUArchState *env, target_ulong ptr) { + return cpu_ldub_mmuidx_ra(env, ptr, SOFTMMU_COMPAT_KERNEL_IDX, 0); +} + +static inline uint32_t cpu_lduw_kernel(CPUArchState *env, target_ulong ptr) { + return cpu_lduw_mmuidx_ra(env, ptr, SOFTMMU_COMPAT_KERNEL_IDX, 0); +} + +static inline uint32_t cpu_ldl_kernel(CPUArchState *env, target_ulong ptr) { + return cpu_ldl_mmuidx_ra(env, ptr, SOFTMMU_COMPAT_KERNEL_IDX, 0); +} + +static inline uint64_t cpu_ldq_kernel(CPUArchState *env, target_ulong ptr) { + return cpu_ldq_mmuidx_ra(env, ptr, SOFTMMU_COMPAT_KERNEL_IDX, 0); +} + +static inline void cpu_stb_kernel(CPUArchState *env, target_ulong ptr, uint32_t v) { + cpu_stb_mmuidx_ra(env, ptr, v, SOFTMMU_COMPAT_KERNEL_IDX, 0); +} + +static inline void cpu_stw_kernel(CPUArchState *env, target_ulong ptr, uint32_t v) { + cpu_stw_mmuidx_ra(env, ptr, v, SOFTMMU_COMPAT_KERNEL_IDX, 0); +} + +static inline void cpu_stl_kernel(CPUArchState *env, target_ulong ptr, uint32_t v) { + cpu_stl_mmuidx_ra(env, ptr, v, SOFTMMU_COMPAT_KERNEL_IDX, 0); +} + +static inline void cpu_stq_kernel(CPUArchState *env, target_ulong ptr, uint64_t v) { + cpu_stq_mmuidx_ra(env, ptr, v, SOFTMMU_COMPAT_KERNEL_IDX, 0); +} + +/* + * Code accessors, used by the translator. + */ + +static inline MemOpIdx softmmu_compat_code_oi(CPUArchState *env, MemOp op) { + return make_memop_idx(op, cpu_mmu_index(env_cpu(env), true)); +} + +static inline uint32_t cpu_ldub_code(CPUArchState *env, target_ulong ptr) { + return cpu_ldb_code_mmu(env, ptr, softmmu_compat_code_oi(env, MO_UB), 0); +} + +static inline uint32_t cpu_lduw_code(CPUArchState *env, target_ulong ptr) { + return cpu_ldw_code_mmu(env, ptr, softmmu_compat_code_oi(env, MO_TEUW), 0); +} + +static inline int cpu_ldsw_code(CPUArchState *env, target_ulong ptr) { + return (int16_t) cpu_lduw_code(env, ptr); +} + +static inline uint32_t cpu_ldl_code(CPUArchState *env, target_ulong ptr) { + return cpu_ldl_code_mmu(env, ptr, softmmu_compat_code_oi(env, MO_TEUL), 0); +} + +static inline uint64_t cpu_ldq_code(CPUArchState *env, target_ulong ptr) { + return cpu_ldq_code_mmu(env, ptr, softmmu_compat_code_oi(env, MO_TEUQ), 0); +} + +/* + * Shorthands of the helpers. They use the global env and the MMU index of + * the current privilege level. + */ + +#define ldub(p) cpu_ldub_data(env, p) +#define ldsb(p) cpu_ldsb_data(env, p) +#define lduw(p) cpu_lduw_data(env, p) +#define ldsw(p) cpu_ldsw_data(env, p) +#define ldl(p) cpu_ldl_data(env, p) +#define ldq(p) cpu_ldq_data(env, p) + +#define stb(p, v) cpu_stb_data(env, p, v) +#define stw(p, v) cpu_stw_data(env, p, v) +#define stl(p, v) cpu_stl_data(env, p, v) +#define stq(p, v) cpu_stq_data(env, p, v) + +#endif diff --git a/libcpu/src/softmmu_exec.h b/libcpu/src/softmmu_exec.h deleted file mode 100644 index 4c24341cf..000000000 --- a/libcpu/src/softmmu_exec.h +++ /dev/null @@ -1,152 +0,0 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -/* Common softmmu definitions and inline routines. */ - -/* XXX: find something cleaner. - * Furthermore, this is false for 64 bits targets - */ -#define ldul_user ldl_user -#define ldul_kernel ldl_kernel -#define ldul_hypv ldl_hypv -#define ldul_executive ldl_executive -#define ldul_supervisor ldl_supervisor - -#include - -#define ACCESS_TYPE 0 -#define MEMSUFFIX MMU_MODE0_SUFFIX -#define DATA_SIZE 1 -#include "softmmu_header.h" - -#define DATA_SIZE 2 -#include "softmmu_header.h" - -#define DATA_SIZE 4 -#include "softmmu_header.h" - -#define DATA_SIZE 8 -#include "softmmu_header.h" -#undef ACCESS_TYPE -#undef MEMSUFFIX - -#define ACCESS_TYPE 1 -#define MEMSUFFIX MMU_MODE1_SUFFIX -#define DATA_SIZE 1 -#include "softmmu_header.h" - -#define DATA_SIZE 2 -#include "softmmu_header.h" - -#define DATA_SIZE 4 -#include "softmmu_header.h" - -#define DATA_SIZE 8 -#include "softmmu_header.h" -#undef ACCESS_TYPE -#undef MEMSUFFIX - -#if (NB_MMU_MODES >= 3) - -#define ACCESS_TYPE 2 -#define MEMSUFFIX MMU_MODE2_SUFFIX -#define DATA_SIZE 1 -#include "softmmu_header.h" - -#define DATA_SIZE 2 -#include "softmmu_header.h" - -#define DATA_SIZE 4 -#include "softmmu_header.h" - -#define DATA_SIZE 8 -#include "softmmu_header.h" -#undef ACCESS_TYPE -#undef MEMSUFFIX -#endif /* (NB_MMU_MODES >= 3) */ - -#if (NB_MMU_MODES >= 4) - -#define ACCESS_TYPE 3 -#define MEMSUFFIX MMU_MODE3_SUFFIX -#define DATA_SIZE 1 -#include "softmmu_header.h" - -#define DATA_SIZE 2 -#include "softmmu_header.h" - -#define DATA_SIZE 4 -#include "softmmu_header.h" - -#define DATA_SIZE 8 -#include "softmmu_header.h" -#undef ACCESS_TYPE -#undef MEMSUFFIX -#endif /* (NB_MMU_MODES >= 4) */ - -#if (NB_MMU_MODES >= 5) - -#define ACCESS_TYPE 4 -#define MEMSUFFIX MMU_MODE4_SUFFIX -#define DATA_SIZE 1 -#include "softmmu_header.h" - -#define DATA_SIZE 2 -#include "softmmu_header.h" - -#define DATA_SIZE 4 -#include "softmmu_header.h" - -#define DATA_SIZE 8 -#include "softmmu_header.h" -#undef ACCESS_TYPE -#undef MEMSUFFIX -#endif /* (NB_MMU_MODES >= 5) */ - -#if (NB_MMU_MODES > 5) -#error "NB_MMU_MODES > 5 is not supported for now" -#endif /* (NB_MMU_MODES > 5) */ - -/* these access are slower, they must be as rare as possible */ -#define ACCESS_TYPE (NB_MMU_MODES) -#define MEMSUFFIX _data -#define DATA_SIZE 1 -#include "softmmu_header.h" - -#define DATA_SIZE 2 -#include "softmmu_header.h" - -#define DATA_SIZE 4 -#include "softmmu_header.h" - -#define DATA_SIZE 8 -#include "softmmu_header.h" -#undef ACCESS_TYPE -#undef MEMSUFFIX - -#define ldub(p) cpu_ldub_data(env, p) -#define ldsb(p) cpu_ldsb_data(env, p) -#define lduw(p) cpu_lduw_data(env, p) -#define ldsw(p) cpu_ldsw_data(env, p) -#define ldl(p) cpu_ldl_data(env, p) -#define ldq(p) cpu_ldq_data(env, p) - -#define stb(p, v) cpu_stb_data(env, p, v) -#define stw(p, v) cpu_stw_data(env, p, v) -#define stl(p, v) cpu_stl_data(env, p, v) -#define stq(p, v) cpu_stq_data(env, p, v) diff --git a/libcpu/src/softmmu_header.h b/libcpu/src/softmmu_header.h deleted file mode 100644 index 674ce8a91..000000000 --- a/libcpu/src/softmmu_header.h +++ /dev/null @@ -1,323 +0,0 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -#if DATA_SIZE == 8 -#define SUFFIX q -#define USUFFIX q -#define DATA_TYPE uint64_t -#elif DATA_SIZE == 4 -#define SUFFIX l -#define USUFFIX l -#define DATA_TYPE uint32_t -#elif DATA_SIZE == 2 -#define SUFFIX w -#define USUFFIX uw -#define DATA_TYPE uint16_t -#define DATA_STYPE int16_t -#elif DATA_SIZE == 1 -#define SUFFIX b -#define USUFFIX ub -#define DATA_TYPE uint8_t -#define DATA_STYPE int8_t -#else -#error unsupported data size -#endif - -#if ACCESS_TYPE < (NB_MMU_MODES) - -#define CPU_MMU_INDEX ACCESS_TYPE -#define MMUSUFFIX _mmu - -#elif ACCESS_TYPE == (NB_MMU_MODES) - -#define CPU_MMU_INDEX (x86_mmu_index(env)) -#define MMUSUFFIX _mmu - -#elif ACCESS_TYPE == (NB_MMU_MODES + 1) - -#define CPU_MMU_INDEX (x86_mmu_index(env)) -#define MMUSUFFIX _cmmu - -#else -#error invalid ACCESS_TYPE -#endif - -#if DATA_SIZE == 8 -#define RES_TYPE uint64_t -#else -#define RES_TYPE uint32_t -#endif - -#if ACCESS_TYPE == (NB_MMU_MODES + 1) -#define ADDR_READ addr_code -#define SE_NO_TRACE -#else -#define ADDR_READ addr_read -#endif - -#define ADDR_MAX ((target_ulong) - 1) - -#ifdef CONFIG_SYMBEX -#include - -// clang-format off -#if defined(SYMBEX_LLVM_LIB) - #define SMHINLINE - #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) \ - if (*g_sqi.events.before_memory_access_signals_count) tcg_llvm_before_memory_access(vaddr, value, size, flags); - #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags) \ - if (*g_sqi.events.after_memory_access_signals_count) tcg_llvm_after_memory_access(vaddr, value, size, flags, 0); - #define INSTR_FORK_AND_CONCRETIZE(val, max) \ - tcg_llvm_fork_and_concretize(val, 0, max, 0) -#else // SYMBEX_LLVM_LIB - #define SMHINLINE inline - #if defined(SE_ENABLE_MEM_TRACING) - #if defined(SE_NO_TRACE) - #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) - #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags) - #else - #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) - #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags) \ - if (unlikely(*g_sqi.events.after_memory_access_signals_count)) INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags, 0); - #endif - #else - #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) - #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags) - #endif - - #define INSTR_FORK_AND_CONCRETIZE(val, max) (val) -#endif // SYMBEX_LLVM_LIB - -#define INSTR_FORK_AND_CONCRETIZE_ADDR(val, max) \ - (*g_sqi.mode.fork_on_symbolic_address ? INSTR_FORK_AND_CONCRETIZE(val, max) : val) - -#define SE_RAM_OBJECT_DIFF (TARGET_PAGE_BITS - SE_RAM_OBJECT_BITS) -// clang-format on -#else // CONFIG_SYMBEX -#define SMHINLINE inline -#define INSTR_BEFORE_MEMORY_ACCESS(...) -#define INSTR_AFTER_MEMORY_ACCESS(...) -#define INSTR_FORK_AND_CONCRETIZE(val, max) (val) -#define INSTR_FORK_AND_CONCRETIZE_ADDR(val, max) (val) - -#define SE_RAM_OBJECT_BITS TARGET_PAGE_BITS -#define SE_RAM_OBJECT_DIFF 0 - -#endif // CONFIG_SYMBEX - -#define CPU_PREFIX cpu_ -#define HELPER_PREFIX helper_ - -/* generic load/store macros */ - -static SMHINLINE RES_TYPE glue(glue(glue(CPU_PREFIX, ld), USUFFIX), MEMSUFFIX)(CPUArchState *env, target_ulong ptr) { -#ifdef CONFIG_SYMBEX_MP - target_ulong object_index; -#endif - - target_ulong page_index; - RES_TYPE res; - target_ulong addr; - target_ulong tlb_addr; - uintptr_t physaddr; - int mmu_idx; - CPUTLBEntry *tlb_entry; - -#ifdef CONFIG_SYMBEX_MP - INSTR_BEFORE_MEMORY_ACCESS(ptr, 0, DATA_SIZE, 0); - addr = INSTR_FORK_AND_CONCRETIZE_ADDR(ptr, ADDR_MAX); - object_index = INSTR_FORK_AND_CONCRETIZE(addr >> SE_RAM_OBJECT_BITS, ADDR_MAX >> SE_RAM_OBJECT_BITS); - page_index = (object_index >> SE_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); -#else - addr = ptr; - page_index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); -#endif - - mmu_idx = CPU_MMU_INDEX; - tlb_entry = &env_tlb(env)->f[mmu_idx].table[page_index]; - tlb_addr = tlb_entry->ADDR_READ & ~TLB_MEM_TRACE; - if (unlikely(tlb_addr != (addr & (TARGET_PAGE_MASK | (DATA_SIZE - 1))))) { - res = glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(env, addr, mmu_idx, NULL); - } else { - // When we get here, the address is aligned with the size of the access, - // which by definition means that it will fall inside the small page, without overflowing. - -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) - physaddr = addr + tlb_entry->se_addend; - res = glue(glue(ld, USUFFIX), _p)((uint8_t *) physaddr); -#else - physaddr = addr + env_tlb(env)->f[mmu_idx].table[page_index].addend; - res = glue(glue(ld, USUFFIX), _p)((uint8_t *) physaddr); -#endif - - INSTR_AFTER_MEMORY_ACCESS(addr, res, DATA_SIZE, 0); - } - return res; -} - -#if DATA_SIZE <= 2 -static SMHINLINE int glue(glue(glue(CPU_PREFIX, lds), SUFFIX), MEMSUFFIX)(CPUArchState *env, target_ulong ptr) { -#ifdef CONFIG_SYMBEX_MP - target_ulong object_index; -#endif - int res; - target_ulong page_index; - target_ulong addr, tlb_addr; - uintptr_t physaddr; - int mmu_idx; - CPUTLBEntry *tlb_entry; - -#ifdef CONFIG_SYMBEX_MP - INSTR_BEFORE_MEMORY_ACCESS(ptr, 0, DATA_SIZE, 0); - addr = INSTR_FORK_AND_CONCRETIZE_ADDR(ptr, ADDR_MAX); - object_index = INSTR_FORK_AND_CONCRETIZE(addr >> SE_RAM_OBJECT_BITS, ADDR_MAX >> SE_RAM_OBJECT_BITS); - page_index = (object_index >> SE_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); -#else - addr = ptr; - page_index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); -#endif - - mmu_idx = CPU_MMU_INDEX; - tlb_entry = &env_tlb(env)->f[mmu_idx].table[page_index]; - tlb_addr = tlb_entry->ADDR_READ & ~TLB_MEM_TRACE; - if (unlikely(tlb_addr != (addr & (TARGET_PAGE_MASK | (DATA_SIZE - 1))))) { - res = (DATA_STYPE) glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(env, addr, mmu_idx, NULL); - } else { - -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) - physaddr = addr + tlb_entry->se_addend; - res = glue(glue(lds, SUFFIX), _p)((uint8_t *) physaddr); -#else - physaddr = addr + tlb_entry->addend; - res = glue(glue(lds, SUFFIX), _p)((uint8_t *) physaddr); -#endif - INSTR_AFTER_MEMORY_ACCESS(addr, res, DATA_SIZE, 0); - } - return res; -} -#endif - -#if ACCESS_TYPE != (NB_MMU_MODES + 1) - -/* generic store macro */ - -static SMHINLINE void glue(glue(glue(CPU_PREFIX, st), SUFFIX), MEMSUFFIX)(CPUArchState *env, target_ulong ptr, - RES_TYPE v) { -#ifdef CONFIG_SYMBEX_MP - target_ulong object_index; -#endif - target_ulong page_index; - target_ulong addr, tlb_addr; - uintptr_t physaddr; - int mmu_idx; - CPUTLBEntry *tlb_entry; - -#ifdef CONFIG_SYMBEX_MP - INSTR_BEFORE_MEMORY_ACCESS(ptr, v, DATA_SIZE, 1); - addr = INSTR_FORK_AND_CONCRETIZE_ADDR(ptr, ADDR_MAX); - object_index = INSTR_FORK_AND_CONCRETIZE(addr >> SE_RAM_OBJECT_BITS, ADDR_MAX >> SE_RAM_OBJECT_BITS); - page_index = (object_index >> SE_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); -#else - addr = ptr; - page_index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); -#endif - - mmu_idx = CPU_MMU_INDEX; - tlb_entry = &env_tlb(env)->f[mmu_idx].table[page_index]; - tlb_addr = tlb_entry->addr_write & ~TLB_MEM_TRACE; - if (unlikely(tlb_addr != (addr & (TARGET_PAGE_MASK | (DATA_SIZE - 1))))) { - glue(glue(glue(HELPER_PREFIX, st), SUFFIX), MMUSUFFIX)(env, addr, v, mmu_idx, NULL); - } else { - -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) - physaddr = addr + tlb_entry->se_addend; - glue(glue(st, SUFFIX), _p)((uint8_t *) physaddr, v); -#else - physaddr = addr + env_tlb(env)->f[mmu_idx].table[page_index].addend; - glue(glue(st, SUFFIX), _p)((uint8_t *) physaddr, v); -#endif - - INSTR_AFTER_MEMORY_ACCESS(addr, v, DATA_SIZE, MEM_TRACE_FLAG_WRITE); - } -} - -#endif /* ACCESS_TYPE != (NB_MMU_MODES + 1) */ - -#if ACCESS_TYPE != (NB_MMU_MODES + 1) - -#if DATA_SIZE == 8 -static SMHINLINE float64 glue(glue(CPU_PREFIX, ldfq), MEMSUFFIX)(CPUArchState *env, target_ulong ptr) { - union { - float64 d; - uint64_t i; - } u; - u.i = glue(glue(CPU_PREFIX, ldq), MEMSUFFIX)(env, ptr); - return u.d; -} - -static SMHINLINE void glue(glue(CPU_PREFIX, stfq), MEMSUFFIX)(CPUArchState *env, target_ulong ptr, float64 v) { - union { - float64 d; - uint64_t i; - } u; - u.d = v; - glue(glue(CPU_PREFIX, stq), MEMSUFFIX)(env, ptr, u.i); -} -#endif /* DATA_SIZE == 8 */ - -#if DATA_SIZE == 4 -static SMHINLINE float32 glue(glue(CPU_PREFIX, ldfl), MEMSUFFIX)(CPUArchState *env, target_ulong ptr) { - union { - float32 f; - uint32_t i; - } u; - u.i = glue(glue(CPU_PREFIX, ldl), MEMSUFFIX)(env, ptr); - return u.f; -} - -static SMHINLINE void glue(glue(CPU_PREFIX, stfl), MEMSUFFIX)(CPUArchState *env, target_ulong ptr, float32 v) { - union { - float32 f; - uint32_t i; - } u; - u.f = v; - glue(glue(CPU_PREFIX, stl), MEMSUFFIX)(env, ptr, u.i); -} -#endif /* DATA_SIZE == 4 */ - -#endif /* ACCESS_TYPE != (NB_MMU_MODES + 1) */ - -#ifndef CONFIG_SYMBEX -#undef SE_RAM_OBJECT_BITS -#endif -#undef SE_RAM_OBJECT_DIFF -#undef INSTR_FORK_AND_CONCRETIZE -#undef INSTR_AFTER_MEMORY_ACCESS -#undef INSTR_BEFORE_MEMORY_ACCESS -#undef ADDR_MAX -#undef RES_TYPE -#undef DATA_TYPE -#undef DATA_STYPE -#undef SUFFIX -#undef USUFFIX -#undef DATA_SIZE -#undef CPU_MMU_INDEX -#undef MMUSUFFIX -#undef ADDR_READ -#undef CPU_PREFIX -#undef HELPER_PREFIX diff --git a/libcpu/src/softmmu_template.h b/libcpu/src/softmmu_template.h deleted file mode 100644 index 7d25d7fab..000000000 --- a/libcpu/src/softmmu_template.h +++ /dev/null @@ -1,647 +0,0 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -#include -#include "exec-phys.h" -#include "exec.h" -#include "timer.h" - -#include - -#define DATA_SIZE (1 << SHIFT) - -#if DATA_SIZE == 8 -#define SUFFIX q -#define USUFFIX q -#define DATA_TYPE uint64_t -#define TCG_DATA_TYPE uint64_t -#elif DATA_SIZE == 4 -#define SUFFIX l -#define USUFFIX l -#define DATA_TYPE uint32_t -#define TCG_DATA_TYPE tcg_target_ulong -#elif DATA_SIZE == 2 -#define SUFFIX w -#define USUFFIX uw -#define DATA_TYPE uint16_t -#define TCG_DATA_TYPE tcg_target_ulong -#elif DATA_SIZE == 1 -#define SUFFIX b -#define USUFFIX ub -#define DATA_TYPE uint8_t -#define TCG_DATA_TYPE tcg_target_ulong -#else -#error unsupported data size -#endif - -#ifdef SOFTMMU_CODE_ACCESS -#define READ_ACCESS_TYPE 2 -#define ADDR_READ addr_code -#else -#define READ_ACCESS_TYPE 0 -#define ADDR_READ addr_read -#endif - -#define CPU_PREFIX cpu_ -#define HELPER_PREFIX helper_ -#define TCG_HELPER_PREFIX tcg_helper_ - -#define ADDR_MAX ((target_ulong) - 1) - -#ifdef CONFIG_SYMBEX -#include - -// clang-format off -#if defined(SYMBEX_LLVM_LIB) - #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) \ - if (*g_sqi.events.before_memory_access_signals_count) tcg_llvm_before_memory_access(vaddr, value, size, flags); - #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags, retaddr) \ - if (*g_sqi.events.after_memory_access_signals_count) tcg_llvm_after_memory_access(vaddr, value, size, flags, 0); - #define INSTR_FORK_AND_CONCRETIZE(val, max) \ - tcg_llvm_fork_and_concretize(val, 0, max, 0) - #define SE_SET_MEM_IO_VADDR(env, addr, reset) \ - tcg_llvm_write_mem_io_vaddr(addr, reset) -#else // SYMBEX_LLVM_LIB - #if defined(SE_ENABLE_MEM_TRACING) - #ifdef SOFTMMU_CODE_ACCESS - #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) - #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags, retaddr) - #else - #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) - #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags, retaddr) \ - if (unlikely(*g_sqi.events.after_memory_access_signals_count)) g_sqi.events.after_memory_access(vaddr, value, size, flags, (uintptr_t) 0); - #endif - #else - #define INSTR_BEFORE_MEMORY_ACCESS(vaddr, value, size, flags) - #define INSTR_AFTER_MEMORY_ACCESS(vaddr, value, size, flags, retaddr) - #endif - - #define INSTR_FORK_AND_CONCRETIZE(val, max) (val) - - #define SE_SET_MEM_IO_VADDR(env, addr, reset) \ - env_cpu(env)->mem_io_vaddr = addr; - -#endif // SYMBEX_LLVM_LIB - -#define INSTR_FORK_AND_CONCRETIZE_ADDR(val, max) \ - (*g_sqi.mode.fork_on_symbolic_address ? INSTR_FORK_AND_CONCRETIZE(val, max) : val) - -#define SE_RAM_OBJECT_DIFF (TARGET_PAGE_BITS - SE_RAM_OBJECT_BITS) -// clang-format on -#else // CONFIG_SYMBEX - -#define INSTR_BEFORE_MEMORY_ACCESS(...) -#define INSTR_AFTER_MEMORY_ACCESS(...) -#define INSTR_FORK_AND_CONCRETIZE(val, max) (val) -#define INSTR_FORK_AND_CONCRETIZE_ADDR(val, max) (val) - -#define SE_RAM_OBJECT_BITS TARGET_PAGE_BITS -#define SE_RAM_OBJECT_SIZE TARGET_PAGE_SIZE -#define SE_RAM_OBJECT_MASK TARGET_PAGE_MASK -#define SE_RAM_OBJECT_DIFF 0 - -#define SE_SET_MEM_IO_VADDR(env, addr, reset) env_cpu(env)->mem_io_vaddr = addr; - -#endif // CONFIG_SYMBEX - -static DATA_TYPE glue(glue(slow_ld, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, int mmu_idx, - void *retaddr); - -DATA_TYPE glue(glue(io_read, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, - void *retaddr); - -#if !defined(SYMBEX_LLVM_LIB) -DATA_TYPE glue(glue(io_read, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, - void *retaddr) { - DATA_TYPE res; - const struct MemoryDescOps *ops = phys_get_ops(physaddr); - - physaddr = (physaddr & TARGET_PAGE_MASK) + addr; - -#if defined(CONFIG_SYMBEX) && defined(CONFIG_SYMBEX_MP) - // Can't handle symbolic mmio from helpers - if (unlikely(tcg_is_dyngen_addr(retaddr) && g_sqi.mem.is_mmio_symbolic(addr, DATA_SIZE))) { - g_sqi.exec.switch_to_symbolic(retaddr); - } - - if (is_notdirty_ops(ops)) { - CPUTLBEntry *e = env_cpu(env)->neg.se_tlb_current; - if (likely(_se_check_concrete(e->objectState, addr & ~SE_RAM_OBJECT_MASK, DATA_SIZE))) { - return glue(glue(ld, USUFFIX), _p)((uint8_t *) (addr + (e->se_addend))); - } else if (!tcg_is_dyngen_addr(retaddr)) { - /** - * Concretize any symbolic data touched by helpers. - * It is not possible to switch to symbolic mode in the middle - * of helper code because execution would resume at instruction - * boundary without rolling back any possible changes that - * the helper had done. - */ - return glue(glue(ld, USUFFIX), _raw)((uint8_t *) (addr + (e->addend))); - } else { - g_sqi.exec.switch_to_symbolic(retaddr); - } - } -#endif - - env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; - - SE_SET_MEM_IO_VADDR(env, addr, 0); -#if SHIFT <= 2 - res = ops->read(physaddr, 1 << SHIFT); -#else -#ifdef TARGET_WORDS_BIGENDIAN - res = ops->read(physaddr, 4) << 32; - res |= ops->read(physaddr + 4, 4); -#else - res = ops->read(physaddr, 4); - res |= ops->read(physaddr + 4, 4) << 32; -#endif -#endif /* SHIFT > 2 */ - return res; -} - -DATA_TYPE glue(glue(io_read_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, - void *retaddr) { - return glue(glue(io_read, SUFFIX), MMUSUFFIX)(env, physaddr, addr, retaddr); -} - -#elif defined(SYMBEX_LLVM_LIB) // SYMBEX_LLVM_LIB - -DATA_TYPE glue(glue(io_read_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, target_ulong addr, - void *retaddr) { - // Putting together two 32-bit values involves an or and a shift, - // which produces hard-to-simplify symbolic expressions. - // Instead, we use a union to force casting, which will generate - // simpler concats and extract expression. The union must be volatile, - // otherwise the compiler would optimize away this trick. - volatile union { - DATA_TYPE res; - uint8_t raw[DATA_SIZE]; - } res; - - target_phys_addr_t origaddr = physaddr; - const struct MemoryDescOps *ops = phys_get_ops(physaddr); - - target_ulong naddr = (physaddr & TARGET_PAGE_MASK) + addr; - - // If it is not DMA, then check if it is normal memory - env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; - - SE_SET_MEM_IO_VADDR(env, addr, 0); -#if SHIFT <= 2 - if (se_ismemfunc(ops, 0)) { - uintptr_t pa = se_notdirty_mem_read(naddr); - res.res = glue(glue(ld, USUFFIX), _raw)((uint8_t *) (intptr_t) (pa)); - goto end; - } -#else -#ifdef TARGET_WORDS_BIGENDIAN - if (se_ismemfunc(ops, 0)) { - uintptr_t pa = se_notdirty_mem_read(naddr); - *(uint32_t *) &res.raw[sizeof(uint32_t)] = glue(glue(ld, USUFFIX), _raw)((uint8_t *) (intptr_t) (pa)); - - pa = se_notdirty_mem_read(naddr + 4); - *(uint32_t *) &res.raw[0] = glue(glue(ld, USUFFIX), _raw)((uint8_t *) (intptr_t) (pa)); - goto end; - } -#else - if (se_ismemfunc(ops, 0)) { - uintptr_t pa = se_notdirty_mem_read(naddr); - *(uint32_t *) &res.raw[0] = glue(glue(ld, USUFFIX), _raw)((uint8_t *) (intptr_t) (pa)); - - pa = se_notdirty_mem_read(naddr + 4); - *(uint32_t *) &res.raw[sizeof(uint32_t)] = glue(glue(ld, USUFFIX), _raw)((uint8_t *) (intptr_t) (pa)); - goto end; - } -#endif -#endif /* SHIFT > 2 */ - - // By default, call the original io_read function, which is external - res.res = glue(glue(io_read, SUFFIX), MMUSUFFIX)(env, origaddr, addr, retaddr); - -end: - tcg_llvm_trace_mmio_access(addr, res.res, DATA_SIZE, 0); - - SE_SET_MEM_IO_VADDR(env, 0, 1); - return res.res; -} - -#endif - -/* handle all cases except unaligned access which span two pages */ -DATA_TYPE -glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, int mmu_idx, - void *retaddr) { - DATA_TYPE res; - target_ulong object_index, index; - target_ulong tlb_addr; - target_phys_addr_t ioaddr; - CPUTLBEntry *tlb_entry; - - mmu_idx = get_mmuidx(mmu_idx); - -/* test if there is match for unaligned or IO access */ -/* XXX: could done more in memory macro in a non portable way */ -#ifdef CONFIG_SYMBEX_MP - INSTR_BEFORE_MEMORY_ACCESS(addr, 0, DATA_SIZE, 0); - addr = INSTR_FORK_AND_CONCRETIZE_ADDR(addr, ADDR_MAX); - object_index = INSTR_FORK_AND_CONCRETIZE(addr >> SE_RAM_OBJECT_BITS, ADDR_MAX >> SE_RAM_OBJECT_BITS); - index = (object_index >> SE_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); -#else - index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); - object_index = index; -#endif - -redo: - tlb_entry = &env_tlb(env)->f[mmu_idx].table[index]; - tlb_addr = tlb_entry->ADDR_READ & ~TLB_MEM_TRACE; - if (likely((addr & TARGET_PAGE_MASK) == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK)))) { - if (unlikely(tlb_addr & ~TARGET_PAGE_MASK)) { - /* IO access */ - if ((addr & (DATA_SIZE - 1)) != 0) - goto do_unaligned_access; - ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; -#ifdef CONFIG_SYMBEX - env_cpu(env)->neg.se_tlb_current = tlb_entry; -#endif - res = glue(glue(io_read_chk, SUFFIX), MMUSUFFIX)(env, ioaddr, addr, retaddr); - - INSTR_AFTER_MEMORY_ACCESS(addr, res, DATA_SIZE, MEM_TRACE_FLAG_IO, retaddr); - - } else if (unlikely(((addr & ~SE_RAM_OBJECT_MASK) + DATA_SIZE - 1) >= SE_RAM_OBJECT_SIZE)) { - /* slow unaligned access (it spans two pages or IO) */ - do_unaligned_access: -#ifdef ALIGNED_ONLY - do_unaligned_access(env, addr, READ_ACCESS_TYPE, mmu_idx, retaddr); -#endif - res = glue(glue(slow_ld, SUFFIX), MMUSUFFIX)(env, addr, mmu_idx, retaddr); - } else { -/* unaligned/aligned access in the same page */ -#ifdef ALIGNED_ONLY - if ((addr & (DATA_SIZE - 1)) != 0) { - do_unaligned_access(env, addr, READ_ACCESS_TYPE, mmu_idx, retaddr); - } -#endif - -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) - res = glue(glue(ld, USUFFIX), _p)((uint8_t *) (intptr_t) (addr + tlb_entry->se_addend)); -#else - res = glue(glue(ld, USUFFIX), _p)((uint8_t *) (intptr_t) (addr + tlb_entry->addend)); -#endif - INSTR_AFTER_MEMORY_ACCESS(addr, res, DATA_SIZE, 0, retaddr); - } - } else { -/* the page is not in the TLB : fill it */ -#ifdef ALIGNED_ONLY - if ((addr & (DATA_SIZE - 1)) != 0) - do_unaligned_access(env, addr, READ_ACCESS_TYPE, mmu_idx, retaddr); -#endif - tlb_fill(env, addr, object_index << SE_RAM_OBJECT_BITS, READ_ACCESS_TYPE, mmu_idx, retaddr); - goto redo; - } - - return res; -} - -TCG_DATA_TYPE -glue(glue(glue(TCG_HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, int mmu_idx, - void *retaddr) { - return (TCG_DATA_TYPE) glue(glue(glue(HELPER_PREFIX, ld), SUFFIX), MMUSUFFIX)(env, addr, mmu_idx, retaddr); -} - -/* handle all unaligned cases */ -static DATA_TYPE glue(glue(slow_ld, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, int mmu_idx, - void *retaddr) { - DATA_TYPE res, res1, res2; - target_ulong object_index, index, shift; - target_phys_addr_t ioaddr; - target_ulong tlb_addr, addr1, addr2; - CPUTLBEntry *tlb_entry; - - INSTR_BEFORE_MEMORY_ACCESS(addr, 0, DATA_SIZE, 0); - addr = INSTR_FORK_AND_CONCRETIZE_ADDR(addr, ADDR_MAX); - object_index = INSTR_FORK_AND_CONCRETIZE(addr >> SE_RAM_OBJECT_BITS, ADDR_MAX >> SE_RAM_OBJECT_BITS); - index = (object_index >> SE_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); -redo: - tlb_entry = &env_tlb(env)->f[mmu_idx].table[index]; - tlb_addr = tlb_entry->ADDR_READ & ~TLB_MEM_TRACE; - - if ((addr & TARGET_PAGE_MASK) == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) { - if (tlb_addr & ~TARGET_PAGE_MASK) { - /* IO access */ - if ((addr & (DATA_SIZE - 1)) != 0) - goto do_unaligned_access; - ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; - -#ifdef CONFIG_SYMBEX - env_cpu(env)->neg.se_tlb_current = tlb_entry; -#endif - res = glue(glue(io_read_chk, SUFFIX), MMUSUFFIX)(env, ioaddr, addr, retaddr); - - INSTR_AFTER_MEMORY_ACCESS(addr, res, DATA_SIZE, MEM_TRACE_FLAG_IO, retaddr); - } else if (((addr & ~SE_RAM_OBJECT_MASK) + DATA_SIZE - 1) >= SE_RAM_OBJECT_SIZE) { - - do_unaligned_access: - /* slow unaligned access (it spans two pages) */ - addr1 = addr & ~(DATA_SIZE - 1); - addr2 = addr1 + DATA_SIZE; - res1 = glue(glue(slow_ld, SUFFIX), MMUSUFFIX)(env, addr1, mmu_idx, retaddr); - res2 = glue(glue(slow_ld, SUFFIX), MMUSUFFIX)(env, addr2, mmu_idx, retaddr); - shift = (addr & (DATA_SIZE - 1)) * 8; -#ifdef TARGET_WORDS_BIGENDIAN - res = (res1 << shift) | (res2 >> ((DATA_SIZE * 8) - shift)); -#else - res = (res1 >> shift) | (res2 << ((DATA_SIZE * 8) - shift)); -#endif - res = (DATA_TYPE) res; - } else { -/* unaligned/aligned access in the same page */ -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) - res = glue(glue(ld, USUFFIX), _p)((uint8_t *) (intptr_t) (addr + tlb_entry->se_addend)); -#else - res = glue(glue(ld, USUFFIX), _p)((uint8_t *) (intptr_t) (addr + tlb_entry->addend)); -#endif - INSTR_AFTER_MEMORY_ACCESS(addr, res, DATA_SIZE, 0, retaddr); - } - } else { - /* the page is not in the TLB : fill it */ - tlb_fill(env, addr, object_index << SE_RAM_OBJECT_BITS, READ_ACCESS_TYPE, mmu_idx, retaddr); - goto redo; - } - return res; -} - -/*************************************************************************************/ - -#ifndef SOFTMMU_CODE_ACCESS - -static void glue(glue(slow_st, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, DATA_TYPE val, int mmu_idx, - void *retaddr); - -void glue(glue(io_write, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, DATA_TYPE val, - target_ulong addr, void *retaddr); -#if !defined(SYMBEX_LLVM_LIB) - -void glue(glue(io_write, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, DATA_TYPE val, - target_ulong addr, void *retaddr) { - const struct MemoryDescOps *ops = phys_get_ops(physaddr); - - physaddr = (physaddr & TARGET_PAGE_MASK) + addr; - -#if defined(CONFIG_SYMBEX) && defined(CONFIG_SYMBEX_MP) - // XXX: avoid switch to symbolic mode here, not needed for writes - if (unlikely(tcg_is_dyngen_addr(retaddr) && g_sqi.mem.is_mmio_symbolic(addr, DATA_SIZE))) { - g_sqi.exec.switch_to_symbolic(retaddr); - } - - if (unlikely(is_notdirty_ops(ops))) { - CPUTLBEntry *e = env_cpu(env)->neg.se_tlb_current; - if (!(e->addr_write & (TLB_NOT_OURS | TLB_NOTDIRTY))) { - if (likely(_se_check_concrete(e->objectState, addr & ~SE_RAM_OBJECT_MASK, DATA_SIZE))) { - glue(glue(st, SUFFIX), _p)((uint8_t *) (addr + (e->se_addend)), val); - return; - } - // The symbolic value will be overwritten by the concrete one - // in the slow path for not-dirty pages. - } - } -#endif - - SE_SET_MEM_IO_VADDR(env, addr, 0); - env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; -#if SHIFT <= 2 - ops->write(physaddr, val, 1 << SHIFT); -#else -#ifdef TARGET_WORDS_BIGENDIAN - ops->write(physaddr, (val >> 32), 4); - ops->write(physaddr + 4, (uint32_t) val, 4); -#else - ops->write(physaddr, (uint32_t) val, 4); - ops->write(physaddr + 4, val >> 32, 4); -#endif -#endif /* SHIFT > 2 */ -} - -void glue(glue(io_write_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, DATA_TYPE val, - target_ulong addr, void *retaddr) { - // XXX: check symbolic memory mapped devices and write log here. - glue(glue(io_write, SUFFIX), MMUSUFFIX)(env, physaddr, val, addr, retaddr); -} - -#else -/** - * Only if compiling for LLVM. - * This function checks whether a write goes to a clean memory page. - * If yes, does the write directly. - * This avoids symbolic values flowing outside the LLVM code and killing the states. - * - * It also deals with writes to memory-mapped devices that are symbolic - */ -void glue(glue(io_write_chk, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_phys_addr_t physaddr, DATA_TYPE val, - target_ulong addr, void *retaddr) { - target_phys_addr_t origaddr = physaddr; - const struct MemoryDescOps *ops = phys_get_ops(physaddr); - - physaddr = (physaddr & TARGET_PAGE_MASK) + addr; - - SE_SET_MEM_IO_VADDR(env, addr, 0); - env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; -#if SHIFT <= 2 - if (se_ismemfunc(ops, 1)) { - uintptr_t pa = se_notdirty_mem_write(physaddr, 1 << SHIFT); - glue(glue(st, SUFFIX), _raw)((uint8_t *) (intptr_t) (pa), val); - goto end; - } -#else -#ifdef TARGET_WORDS_BIGENDIAN -#error Big endian not supported -#else - if (se_ismemfunc(ops, 1)) { - uintptr_t pa = se_notdirty_mem_write(physaddr, 1 << SHIFT); - stl_raw((uint8_t *) (intptr_t) (pa), val); - pa = se_notdirty_mem_write(physaddr + 4, 1 << SHIFT); - stl_raw((uint8_t *) (intptr_t) (pa), val >> 32); - goto end; - } -#endif -#endif /* SHIFT > 2 */ - - // By default, call the original io_write function, which is external - glue(glue(io_write, SUFFIX), MMUSUFFIX)(env, origaddr, val, addr, retaddr); - -end: - tcg_llvm_trace_mmio_access(addr, val, DATA_SIZE, 1); - SE_SET_MEM_IO_VADDR(env, 0, 1); -} - -#endif - -void glue(glue(glue(HELPER_PREFIX, st), SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, DATA_TYPE val, - int mmu_idx, void *retaddr) { - target_phys_addr_t ioaddr; - target_ulong tlb_addr; - target_ulong object_index, index; - CPUTLBEntry *tlb_entry; - - mmu_idx = get_mmuidx(mmu_idx); - -#ifdef CONFIG_SYMBEX_MP - INSTR_BEFORE_MEMORY_ACCESS(addr, val, DATA_SIZE, 1); - addr = INSTR_FORK_AND_CONCRETIZE_ADDR(addr, ADDR_MAX); - object_index = INSTR_FORK_AND_CONCRETIZE(addr >> SE_RAM_OBJECT_BITS, ADDR_MAX >> SE_RAM_OBJECT_BITS); - index = (object_index >> SE_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); -#else - index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1); - object_index = index; -#endif - -redo: - tlb_entry = &env_tlb(env)->f[mmu_idx].table[index]; - tlb_addr = tlb_entry->addr_write & ~TLB_MEM_TRACE; - - if (likely((addr & TARGET_PAGE_MASK) == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK)))) { - if (unlikely(tlb_addr & ~TARGET_PAGE_MASK)) { - /* IO access */ - if ((addr & (DATA_SIZE - 1)) != 0) - goto do_unaligned_access; - - ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; - -#ifdef CONFIG_SYMBEX - env_cpu(env)->neg.se_tlb_current = tlb_entry; -#endif - - glue(glue(io_write_chk, SUFFIX), MMUSUFFIX)(env, ioaddr, val, addr, retaddr); - - INSTR_AFTER_MEMORY_ACCESS(addr, val, DATA_SIZE, MEM_TRACE_FLAG_IO | MEM_TRACE_FLAG_WRITE, retaddr); - } else if (unlikely(((addr & ~SE_RAM_OBJECT_MASK) + DATA_SIZE - 1) >= SE_RAM_OBJECT_SIZE)) { - - do_unaligned_access: - -#ifdef ALIGNED_ONLY - do_unaligned_access(env, addr, 1, mmu_idx, retaddr); -#endif - glue(glue(slow_st, SUFFIX), MMUSUFFIX)(env, addr, val, mmu_idx, retaddr); - } else { -/* aligned/unaligned access in the same page */ -#ifdef ALIGNED_ONLY - if ((addr & (DATA_SIZE - 1)) != 0) { - do_unaligned_access(env, addr, 1, mmu_idx, retaddr); - } -#endif - -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) - glue(glue(st, SUFFIX), _p)((uint8_t *) (addr + tlb_entry->se_addend), val); -#else - glue(glue(st, SUFFIX), _p)((uint8_t *) (addr + tlb_entry->addend), val); -#endif - INSTR_AFTER_MEMORY_ACCESS(addr, val, DATA_SIZE, MEM_TRACE_FLAG_WRITE, retaddr); - } - } else { -/* the page is not in the TLB : fill it */ -#ifdef ALIGNED_ONLY - if ((addr & (DATA_SIZE - 1)) != 0) - do_unaligned_access(env, addr, 1, mmu_idx, retaddr); -#endif - tlb_fill(env, addr, object_index << SE_RAM_OBJECT_BITS, 1, mmu_idx, retaddr); - goto redo; - } -} - -/* handles all unaligned cases */ -static void glue(glue(slow_st, SUFFIX), MMUSUFFIX)(CPUArchState *env, target_ulong addr, DATA_TYPE val, int mmu_idx, - void *retaddr) { - target_phys_addr_t ioaddr; - target_ulong tlb_addr; - target_ulong object_index, index; - int i; - CPUTLBEntry *tlb_entry; - - INSTR_BEFORE_MEMORY_ACCESS(addr, val, DATA_SIZE, 1); - addr = INSTR_FORK_AND_CONCRETIZE_ADDR(addr, ADDR_MAX); - object_index = INSTR_FORK_AND_CONCRETIZE(addr >> SE_RAM_OBJECT_BITS, ADDR_MAX >> SE_RAM_OBJECT_BITS); - index = (object_index >> SE_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); -redo: - tlb_entry = &env_tlb(env)->f[mmu_idx].table[index]; - tlb_addr = tlb_entry->addr_write & ~TLB_MEM_TRACE; - ; - if ((addr & TARGET_PAGE_MASK) == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) { - if (tlb_addr & ~TARGET_PAGE_MASK) { - /* IO access */ - if ((addr & (DATA_SIZE - 1)) != 0) - goto do_unaligned_access; - ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; -#ifdef CONFIG_SYMBEX - env_cpu(env)->neg.se_tlb_current = tlb_entry; -#endif - glue(glue(io_write_chk, SUFFIX), MMUSUFFIX)(env, ioaddr, val, addr, retaddr); - - INSTR_AFTER_MEMORY_ACCESS(addr, val, DATA_SIZE, MEM_TRACE_FLAG_IO | MEM_TRACE_FLAG_WRITE, retaddr); - } else if (((addr & ~SE_RAM_OBJECT_MASK) + DATA_SIZE - 1) >= SE_RAM_OBJECT_SIZE) { - - do_unaligned_access: - /* XXX: not efficient, but simple */ - /* Note: relies on the fact that tlb_fill() does not remove the - * previous page from the TLB cache. */ - for (i = DATA_SIZE - 1; i >= 0; i--) { -#ifdef TARGET_WORDS_BIGENDIAN - glue(slow_stb, MMUSUFFIX)(env, addr + i, val >> (((DATA_SIZE - 1) * 8) - (i * 8)), mmu_idx, retaddr); -#else - glue(slow_stb, MMUSUFFIX)(env, addr + i, val >> (i * 8), mmu_idx, retaddr); -#endif - } - } else { - /* aligned/unaligned access in the same page */ - -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) && defined(CONFIG_SYMBEX_MP) - glue(glue(st, SUFFIX), _p)((uint8_t *) (addr + tlb_entry->se_addend), val); -#else - glue(glue(st, SUFFIX), _p)((uint8_t *) (addr + tlb_entry->addend), val); -#endif - INSTR_AFTER_MEMORY_ACCESS(addr, val, DATA_SIZE, MEM_TRACE_FLAG_WRITE, retaddr); - } - } else { - /* the page is not in the TLB : fill it */ - tlb_fill(env, addr, object_index << SE_RAM_OBJECT_BITS, 1, mmu_idx, retaddr); - goto redo; - } -} - -#endif /* !defined(SOFTMMU_CODE_ACCESS) */ - -#ifndef CONFIG_SYMBEX -#undef SE_RAM_OBJECT_BITS -#undef SE_RAM_OBJECT_SIZE -#undef SE_RAM_OBJECT_MASK -#endif -#undef INSTR_FORK_AND_CONCRETIZE_ADDR -#undef INSTR_FORK_AND_CONCRETIZE -#undef INSTR_AFTER_MEMORY_ACCESS -#undef INSTR_BEFORE_MEMORY_ACCESS -#undef ADDR_MAX -#undef READ_ACCESS_TYPE -#undef SHIFT -#undef DATA_TYPE -#undef TCG_DATA_TYPE -#undef SUFFIX -#undef USUFFIX -#undef DATA_SIZE -#undef ADDR_READ -#undef CPU_PREFIX -#undef HELPER_PREFIX -#undef TCG_HELPER_PREFIX diff --git a/libcpu/src/target-i386/cpu.h b/libcpu/src/target-i386/cpu.h index 462dd7a65..ce526f9cc 100644 --- a/libcpu/src/target-i386/cpu.h +++ b/libcpu/src/target-i386/cpu.h @@ -471,6 +471,14 @@ void raise_exception(CPUX86State *env, int exception_index); void raise_exception_err(CPUX86State *env, int exception_index, int error_code); void raise_exception_err_ra(CPUX86State *env, int exception_index, int error_code, uintptr_t retaddr); +/* The softmmu hooks, see op_helper.c. */ +extern const CPUClass g_x86_cpu_class; +bool x86_cpu_tlb_fill(CPUState *cs, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, bool probe, + uintptr_t retaddr); +void LIBCPU_NORETURN x86_cpu_do_unaligned_access(CPUState *cs, vaddr addr, MMUAccessType access_type, int mmu_idx, + uintptr_t retaddr); +vaddr x86_cpu_pointer_wrap(CPUState *cs, int mmu_idx, vaddr result, vaddr base); + void do_smm_enter(CPUX86State *env1); void svm_check_intercept(CPUX86State *env1, uint32_t type); diff --git a/libcpu/src/target-i386/helper.c b/libcpu/src/target-i386/helper.c index fed652b00..5fa2f0969 100644 --- a/libcpu/src/target-i386/helper.c +++ b/libcpu/src/target-i386/helper.c @@ -167,7 +167,7 @@ void cpu_state_reset(CPUX86State *env) { cpu_init_fp_statuses(env); - tlb_flush(env, 1); + tlb_flush(env_cpu(env)); env->old_exception = -1; @@ -488,7 +488,7 @@ void cpu_x86_set_a20(CPUX86State *env, int a20_state) { /* when a20 is changed, all the MMU mappings are invalid, so we must flush everything */ - tlb_flush(env, 1); + tlb_flush(env_cpu(env)); env->a20_mask = ~(1 << 20) | (a20_state << 20); } } @@ -501,7 +501,7 @@ void cpu_x86_update_cr0(CPUX86State *env, uint32_t new_cr0) { #endif if ((new_cr0 & (CR0_PG_MASK | CR0_WP_MASK | CR0_PE_MASK)) != (env->cr[0] & (CR0_PG_MASK | CR0_WP_MASK | CR0_PE_MASK))) { - tlb_flush(env, 1); + tlb_flush(env_cpu(env)); } #ifdef TARGET_X86_64 @@ -545,7 +545,7 @@ void cpu_x86_update_cr3(CPUX86State *env, target_ulong new_cr3) { #if defined(DEBUG_MMU) printf("CR3 update: CR3=" TARGET_FMT_lx "\n", new_cr3); #endif - tlb_flush(env, 0); + tlb_flush(env_cpu(env)); } } @@ -555,7 +555,7 @@ void cpu_x86_update_cr4(CPUX86State *env, uint32_t new_cr4) { #endif if ((new_cr4 & (CR4_PGE_MASK | CR4_PAE_MASK | CR4_PSE_MASK)) != (env->cr[4] & (CR4_PGE_MASK | CR4_PAE_MASK | CR4_PSE_MASK))) { - tlb_flush(env, 1); + tlb_flush(env_cpu(env)); } /* SSE handling */ if (!(env->cpuid.cpuid_features & CPUID_SSE)) @@ -832,7 +832,7 @@ int cpu_x86_handle_mmu_fault(CPUX86State *env, target_ulong addr, int is_write1, paddr = (pte & TARGET_PAGE_MASK) + page_offset; vaddr = virt_addr + page_offset; - tlb_set_page(env, vaddr, paddr, prot, mmu_idx, page_size); + tlb_set_page(env_cpu(env), vaddr, paddr, prot, mmu_idx, page_size); return 0; do_fault_protect: error_code = PG_ERROR_P_MASK; diff --git a/libcpu/src/target-i386/op_helper.c b/libcpu/src/target-i386/op_helper.c index a36fccab6..473fc14b4 100644 --- a/libcpu/src/target-i386/op_helper.c +++ b/libcpu/src/target-i386/op_helper.c @@ -31,34 +31,12 @@ #include #include -#include "softmmu_exec.h" +#include +#include "softmmu-compat.h" // SYMBEX: Keep the environment in a variable struct CPUX86State *env = 0; -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) -#include - -#define ACCESS_TYPE 0 -#define MEMSUFFIX _kernel_symb -#define _raw _raw_symb -#define DATA_SIZE 1 -#include "softmmu_header.h" - -#define DATA_SIZE 2 -#include "softmmu_header.h" - -#define DATA_SIZE 4 -#include "softmmu_header.h" - -#define DATA_SIZE 8 -#include "softmmu_header.h" -#undef _raw -#undef ACCESS_TYPE -#undef MEMSUFFIX - -#endif - // #define DEBUG_PCALL #ifdef DEBUG_PCALL @@ -3193,7 +3171,7 @@ void helper_clts(void) { void helper_invlpg(target_ulong addr) { helper_svm_check_intercept_param(SVM_EXIT_INVLPG, 0); - tlb_flush_page(env, addr); + tlb_flush_page(env_cpu(env), addr); } void helper_rdtsc(void) { @@ -4884,81 +4862,97 @@ void helper_boundl(target_ulong a0, int v) { } } -#define MMUSUFFIX _mmu - -#define SHIFT 0 -#include "softmmu_template.h" - -#define SHIFT 1 -#include "softmmu_template.h" - -#define SHIFT 2 -#include "softmmu_template.h" - -#define SHIFT 3 -#include "softmmu_template.h" - -#if defined(CONFIG_SYMBEX) && !defined(SYMBEX_LLVM_LIB) -#undef MMUSUFFIX -#define MMUSUFFIX _mmu_symb -#define _raw _raw_symb - -#define SHIFT 0 -#include "softmmu_template.h" - -#define SHIFT 1 -#include "softmmu_template.h" - -#define SHIFT 2 -#include "softmmu_template.h" - -#define SHIFT 3 -#include "softmmu_template.h" - -#undef _raw -#endif +/* + * The hooks that the softmmu (accel/cputlb.c) calls through TCGCPUOps. + * + * This file is compiled twice, natively and as LLVM bitcode for KLEE, and so + * is cputlb.c. The native softmmu reaches the hooks through cpu->cc->tcg_ops. + * The bitcode softmmu calls the bitcode copies by name, because the address + * it passes can be symbolic and a native function would force KLEE to fork + * on every possible value. + */ -/* try to fill the TLB and return an exception if error. If retaddr is - NULL, it means that the function was called in C code (i.e. not - from generated code or from helper.c) */ -/* XXX: fix it to restore all registers */ -void tlb_fill(CPUX86State *env1, target_ulong addr, target_ulong page_addr, int is_write, int mmu_idx, void *retaddr) { +/* Fills the TLB for one page, or raises the guest exception if the access + faults. A retaddr of 0 means that the caller is not generated code. */ +bool x86_cpu_tlb_fill(CPUState *cs, vaddr addr, int size, MMUAccessType access_type, int mmu_idx, bool probe, + uintptr_t retaddr) { + CPUX86State *env = cpu_env(cs); int ret; #if defined(CONFIG_SYMBEX) if (unlikely(*g_sqi.events.on_tlb_miss_signals_count)) { - g_sqi.events.on_tlb_miss(addr, is_write, retaddr); + g_sqi.events.on_tlb_miss(addr, access_type, (void *) retaddr); } #endif #if defined(CONFIG_SYMBEX) && defined(CONFIG_SYMBEX_MP) - ret = cpu_x86_handle_mmu_fault(env, page_addr, is_write, mmu_idx); + /* The offset inside the page can be symbolic when this runs in KLEE, and + the page table walk is native code. Only the page address, which is + always concrete, is passed to it. */ + ret = cpu_x86_handle_mmu_fault(env, addr & TARGET_PAGE_MASK, access_type, mmu_idx); #else - ret = cpu_x86_handle_mmu_fault(env1, addr, is_write, mmu_idx); + ret = cpu_x86_handle_mmu_fault(env, addr, access_type, mmu_idx); #endif - if (ret) { + if (!ret) { + return true; + } + + if (probe) { + /* cpu_x86_handle_mmu_fault() has already written the fault to CR2 (or + the VMCB) and to the exception fields, which a probe must not do. */ + cpu_abort(env, "page fault while probing address 0x%" VADDR_PRIx "\n", addr); + } + #if defined(CONFIG_SYMBEX) && defined(CONFIG_SYMBEX_MP) - /* In symbex mode, pass page address instead of addr to cpu_x86_handle_mmu_fault, - since the latter can be symbolic while the former is always concrete. - To compensate, we reset fault address here. */ - if (env_cpu(env)->exception_index == EXCP0E_PAGE) { - if (env->intercept_exceptions & (1 << EXCP0E_PAGE)) - stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), addr); - else - env->cr[2] = addr; + /* The page table walk recorded the page address as the fault address. + Replace it with the address of the access. */ + if (cs->exception_index == EXCP0E_PAGE) { + if (env->intercept_exceptions & (1 << EXCP0E_PAGE)) { + stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), addr); + } else { + env->cr[2] = addr; } + } #endif #if defined(CONFIG_SYMBEX) - if (unlikely(*g_sqi.events.on_page_fault_signals_count)) { - g_sqi.events.on_page_fault(addr, is_write, retaddr); - } -#endif - raise_exception_err_ra(env, env_cpu(env)->exception_index, env->error_code, (uintptr_t) retaddr); + if (unlikely(*g_sqi.events.on_page_fault_signals_count)) { + g_sqi.events.on_page_fault(addr, access_type, (void *) retaddr); } +#endif + raise_exception_err_ra(env, cs->exception_index, env->error_code, retaddr); +} + +/* Raises the exception for an access that violates the alignment its + instruction requires. */ +void x86_cpu_do_unaligned_access(CPUState *cs, vaddr addr, MMUAccessType access_type, int mmu_idx, uintptr_t retaddr) { + raise_exception_err_ra(cpu_env(cs), EXCP0D_GPF, 0, retaddr); } +/* Returns the address of the second page of an access that crosses a page + boundary. Outside of 64-bit code, addresses wrap around at 4GB. */ +vaddr x86_cpu_pointer_wrap(CPUState *cs, int mmu_idx, vaddr result, vaddr base) { + return (cpu_env(cs)->hflags & HF_CS64_MASK) ? result : (uint32_t) result; +} + +#if !defined(SYMBEX_LLVM_LIB) +static int x86_cpu_mmu_index(CPUState *cs, bool ifetch) { + return x86_mmu_index(cpu_env(cs)); +} + +static const TCGCPUOps s_x86_tcg_ops = { + .mmu_index = x86_cpu_mmu_index, + .tlb_fill = x86_cpu_tlb_fill, + .do_unaligned_access = x86_cpu_do_unaligned_access, + .pointer_wrap = x86_cpu_pointer_wrap, +}; + +const CPUClass g_x86_cpu_class = { + .tcg_ops = &s_x86_tcg_ops, +}; +#endif + /* Secure Virtual Machine helpers */ static inline void svm_save_seg(target_phys_addr_t addr, const SegmentCache *sc) { stw_phys(addr + offsetof(struct vmcb_seg, selector), sc->selector); @@ -5094,7 +5088,7 @@ void helper_vmrun(int aflag, int next_eip_addend) { break; case TLB_CONTROL_FLUSH_ALL_ASID: /* FIXME: this is not 100% correct but should work for now */ - tlb_flush(env, 1); + tlb_flush(env_cpu(env)); break; } @@ -5248,7 +5242,7 @@ void helper_invlpga(int aflag) { /* XXX: could use the ASID to see if it is needed to do the flush */ - tlb_flush_page(env, addr); + tlb_flush_page(env_cpu(env), addr); } void helper_svm_check_intercept_param(uint32_t type, uint64_t param) { diff --git a/libcpu/src/translate-all.c b/libcpu/src/translate-all.c index 164e5ca1f..3c43b5c4f 100644 --- a/libcpu/src/translate-all.c +++ b/libcpu/src/translate-all.c @@ -45,6 +45,7 @@ #include #endif +#include "accel/tlb-bounds.h" #include "exec-tb.h" #include "exec.h" @@ -54,42 +55,7 @@ extern TCGContext tcg_init_ctx; but not so small that we can't have a fair number of TB's live. */ #define MIN_CODE_GEN_BUFFER_SIZE (128 * 1024 * 1024) -#if defined(CONFIG_SYMBEX_MP) -tcg_target_ulong tcg_helper_ldb_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -tcg_target_ulong tcg_helper_ldw_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -tcg_target_ulong tcg_helper_ldl_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -uint64_t tcg_helper_ldq_mmu_symb(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); - -static void *qemu_ld_helpers[(MO_SIZE | MO_BSWAP) + 1] = {[MO_UB] = tcg_helper_ldb_mmu_symb, - [MO_LEUW] = tcg_helper_ldw_mmu_symb, - [MO_LEUL] = tcg_helper_ldl_mmu_symb, - [MO_LEUQ] = tcg_helper_ldq_mmu_symb}; - -static void *qemu_st_helpers[(MO_SIZE | MO_BSWAP) + 1] = {[MO_UB] = helper_stb_mmu_symb, - [MO_LEUW] = helper_stw_mmu_symb, - [MO_LEUL] = helper_stl_mmu_symb, - [MO_LEUQ] = helper_stq_mmu_symb}; -#else -tcg_target_ulong tcg_helper_ldb_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -tcg_target_ulong tcg_helper_ldw_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -tcg_target_ulong tcg_helper_ldl_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); -uint64_t tcg_helper_ldq_mmu(CPUArchState *env, target_ulong addr, int mmu_idx, void *retaddr); - -static void *qemu_ld_helpers[(MO_SIZE | MO_BSWAP) + 1] = {[MO_UB] = tcg_helper_ldb_mmu, - [MO_LEUW] = tcg_helper_ldw_mmu, - [MO_LEUL] = tcg_helper_ldl_mmu, - [MO_LEUQ] = tcg_helper_ldq_mmu}; - -/* legacy helper signature: __st_mmu(target_ulong addr, uintxx_t val, - int mmu_idx) */ -static void *qemu_st_helpers[(MO_SIZE | MO_BSWAP) + 1] = { - [MO_UB] = helper_stb_mmu, [MO_LEUW] = helper_stw_mmu, [MO_LEUL] = helper_stl_mmu, [MO_LEUQ] = helper_stq_mmu}; -#endif - static void cpu_gen_init(TCGContext *ctx) { - memcpy(ctx->qemu_ld_helpers, qemu_ld_helpers, sizeof(ctx->qemu_ld_helpers)); - memcpy(ctx->qemu_st_helpers, qemu_st_helpers, sizeof(ctx->qemu_st_helpers)); - extern CPUArchState *env; ctx->tcg_struct_size = sizeof(*ctx); ctx->env_ptr = (uintptr_t) &env; diff --git a/libs2e/src/CMakeLists.txt b/libs2e/src/CMakeLists.txt index 8e484cbf1..be1ee22f7 100644 --- a/libs2e/src/CMakeLists.txt +++ b/libs2e/src/CMakeLists.txt @@ -43,7 +43,10 @@ if(WITH_TARGET MATCHES "s2e") set(LIBS -Wl,--whole-archive ${LIBS2EPLUGINS_LIBRARY_DIR}/libs2eplugins.a ${LIBS2ECORE_LIBRARY_DIR}/libs2ecore.a -Wl,--no-whole-archive ${LIBS}) endif() -set(LIBS ${LIBS} ${LIBCPU_LIBRARY_DIR}/libcpu.a ${LIBTCG_LIBRARY_DIR}/libtcg.a) +# libtcg refers to the softmmu and runtime helpers that libcpu defines +# (helper_*_mmu, helper_atomic_*, helper_lookup_tb_ptr), so the linker must +# search the two archives together. +set(LIBS ${LIBS} -Wl,--start-group ${LIBCPU_LIBRARY_DIR}/libcpu.a ${LIBTCG_LIBRARY_DIR}/libtcg.a -Wl,--end-group) llvm_map_components_to_libnames(LLVM_LIBS core passes support bitreader bitstreamreader bitwriter transformutils scalaropts codegen) diff --git a/libs2e/src/s2e-kvm-vcpu.cpp b/libs2e/src/s2e-kvm-vcpu.cpp index 6f552e5d6..0fc3edb2f 100644 --- a/libs2e/src/s2e-kvm-vcpu.cpp +++ b/libs2e/src/s2e-kvm-vcpu.cpp @@ -990,7 +990,7 @@ void *VCPU::sys_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t } void VCPU::flushTlb() { - tlb_flush(m_env, 1); + tlb_flush(env_cpu(m_env)); } void VCPU::interrupt(int mask, bool reset) { diff --git a/libs2e/src/s2e-libcpu-interface.cpp b/libs2e/src/s2e-libcpu-interface.cpp index 0842ba402..bc33fb9bb 100644 --- a/libs2e/src/s2e-libcpu-interface.cpp +++ b/libs2e/src/s2e-libcpu-interface.cpp @@ -76,7 +76,6 @@ void init_s2e_libcpu_interface(struct se_libcpu_interface_t *sqi) { sqi->mem.dma_write = s2e_dma_write; sqi->mem.read_ram_concrete = s2e_read_ram_concrete; sqi->mem.write_ram_concrete = s2e_write_ram_concrete; - sqi->mem.read_ram_concrete_check = s2e_read_ram_concrete_check; sqi->mem.read_mem_io_vaddr = s2e_read_mem_io_vaddr; sqi->mem.is_port_symbolic = s2e_is_port_symbolic; sqi->mem.is_mmio_symbolic = s2e_is_mmio_symbolic; diff --git a/libs2ecore/include/s2e/s2e_libcpu.h b/libs2ecore/include/s2e/s2e_libcpu.h index 26c28e723..cdac04260 100644 --- a/libs2ecore/include/s2e/s2e_libcpu.h +++ b/libs2ecore/include/s2e/s2e_libcpu.h @@ -110,12 +110,6 @@ void s2e_read_ram_concrete(uint64_t host_address, void *buf, uint64_t size); void s2e_write_ram_concrete(uint64_t host_address, const uint8_t *buf, uint64_t size); -/** This function is called when RAM is read by concretely executed - generated code. If the memory location turns out to be symbolic, - this function will either concretize it of switch to execution - in KLEE */ -void s2e_read_ram_concrete_check(uint64_t host_address, uint8_t *buf, uint64_t size); - void s2e_read_register_concrete(unsigned offset, uint8_t *buf, unsigned size); void s2e_write_register_concrete(unsigned offset, uint8_t *buf, unsigned size); diff --git a/libs2ecore/src/ExprInterface.cpp b/libs2ecore/src/ExprInterface.cpp index c9a9db778..a1bae4b67 100644 --- a/libs2ecore/src/ExprInterface.cpp +++ b/libs2ecore/src/ExprInterface.cpp @@ -181,9 +181,8 @@ template static inline bool s2e_fast_read_mem(uint64_t addr, T *res int mmu_idx; object_index = addr >> SE_RAM_OBJECT_BITS; - page_index = object_index & (CPU_TLB_SIZE - 1); - mmu_idx = x86_mmu_index(env); + page_index = object_index & (env_tlb(env)->f[mmu_idx].mask >> CPU_TLB_ENTRY_BITS); CPUTLBEntry *tlb_entry = &env_tlb(env)->f[mmu_idx].table[page_index]; if (unlikely(env_tlb(env)->f[mmu_idx].table[page_index].addr_read != (addr & (TARGET_PAGE_MASK | (sizeof(*res) - 1))))) { diff --git a/libs2ecore/src/FunctionHandlers.cpp b/libs2ecore/src/FunctionHandlers.cpp index 29db15db8..d1c9cbddf 100644 --- a/libs2ecore/src/FunctionHandlers.cpp +++ b/libs2ecore/src/FunctionHandlers.cpp @@ -125,21 +125,6 @@ static void handleGetValue(klee::Executor *executor, klee::ExecutionState *state state->llvm.bindLocal(target, result); } -static void handlerWriteMemIoVaddr(klee::Executor *executor, klee::ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - S2EExecutionState *s2eState = static_cast(state); - assert(args.size() == 2); - - klee::ConstantExpr *reset = dyn_cast(args[1]); - assert(reset && "Invalid parameter"); - - if (reset->getZExtValue()) { - s2eState->setMemIoVaddr(nullptr); - } else { - s2eState->setMemIoVaddr(args[0]); - } -} - static void handlerBeforeMemoryAccess(klee::Executor *executor, klee::ExecutionState *state, klee::KInstruction *target, std::vector> &args) { if (g_s2e->getCorePlugin()->onBeforeSymbolicDataMemoryAccess.empty()) { @@ -315,8 +300,7 @@ static void handlerTracePortAccess(Executor *executor, ExecutionState *state, kl } } -static Handler s_handlers[] = {{"tcg_llvm_write_mem_io_vaddr", handlerWriteMemIoVaddr, nullptr}, - {"tcg_llvm_before_memory_access", handlerBeforeMemoryAccess, nullptr}, +static Handler s_handlers[] = {{"tcg_llvm_before_memory_access", handlerBeforeMemoryAccess, nullptr}, {"tcg_llvm_after_memory_access", handlerAfterMemoryAccess, nullptr}, {"tcg_llvm_trace_port_access", handlerTracePortAccess, nullptr}, {"tcg_llvm_trace_mmio_access", handlerTraceMmioAccess, nullptr}, diff --git a/libs2ecore/src/MMUFunctionHandlers.cpp b/libs2ecore/src/MMUFunctionHandlers.cpp index a856f1d8a..6380f9ed9 100644 --- a/libs2ecore/src/MMUFunctionHandlers.cpp +++ b/libs2ecore/src/MMUFunctionHandlers.cpp @@ -21,6 +21,17 @@ /// SOFTWARE. /// +/// @file +/// Native replacements for the softmmu entry points that translated code +/// calls when it runs in KLEE. +/// +/// By default, KLEE interprets the bitcode of helper_{ld,st}*_mmu() +/// (libcpu/src/accel/cputlb.c). With the use-fast-helpers option, the handlers +/// below run instead. They do the same TLB lookup in C++ and read or write +/// the KLEE memory object directly, which avoids interpreting the lookup. +/// They make the whole address concrete, where the bitcode keeps the offset +/// inside the page symbolic. + #include #include @@ -34,147 +45,12 @@ #include #include +#include using namespace klee; namespace s2e { -#define S2E_RAM_OBJECT_DIFF (TARGET_PAGE_BITS - SE_RAM_OBJECT_BITS) -#ifdef SOFTMMU_CODE_ACCESS -#define READ_ACCESS_TYPE 2 -#define ADDR_READ addr_code -#else -#define READ_ACCESS_TYPE 0 -#define ADDR_READ addr_read -#endif - -// XXX: Fix this -#define CPU_MMU_INDEX 0 - -// This is an io_write_chkX_mmu function -// XXX: width is redundant -static void io_write_chk(S2EExecutionState *state, CPUArchState *env, target_phys_addr_t physaddr, const ref &val, - target_ulong addr, void *retaddr, Expr::Width width) { - target_phys_addr_t origaddr = physaddr; - uint64_t concreteVal; - const struct MemoryDescOps *ops = phys_get_ops(physaddr); - physaddr = (physaddr & TARGET_PAGE_MASK) + addr; - - state->setMemIoVaddr(ConstantExpr::create(addr, sizeof(target_ulong) * 8)); - env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; - - if (width <= Expr::Int32) { - if (se_ismemfunc(ops, 1)) { - uintptr_t pa = se_notdirty_mem_write(physaddr, Expr::getMinBytesForWidth(width)); - state->mem()->write(pa, val, HostAddress); - goto end; - } - } else { -#ifdef TARGET_WORDS_BIGENDIAN -#error Big endian not supported -#else - if (se_ismemfunc(ops, 1)) { - uintptr_t pa = se_notdirty_mem_write(physaddr, Expr::getMinBytesForWidth(width)); - state->mem()->write(pa, ExtractExpr::create(val, 0, Expr::Int32), HostAddress); - pa = se_notdirty_mem_write(physaddr + 4, Expr::getMinBytesForWidth(width)); - state->mem()->write(pa, LShrExpr::create(val, ConstantExpr::create(32, width)), HostAddress); - goto end; - } -#endif - } - - concreteVal = state->concretize(val, "io_write_chk", false); - switch (width) { - case Expr::Int8: - io_writeb_mmu(env, origaddr, concreteVal, addr, retaddr); - break; - case Expr::Int16: - io_writew_mmu(env, origaddr, concreteVal, addr, retaddr); - break; - case Expr::Int32: - io_writel_mmu(env, origaddr, concreteVal, addr, retaddr); - break; - case Expr::Int64: - io_writeq_mmu(env, origaddr, concreteVal, addr, retaddr); - break; - default: - abort(); - } - -end: - // XXX: handle memory access - // tcg_llvm_trace_mmio_access(addr, val, Expr::getMinBytesForWidth(width), 1); - state->setMemIoVaddr(nullptr); -} - -// This is an io_read_chkX_mmu function -static ref io_read_chk(S2EExecutionState *state, const CPUTLBEntry &tlb, target_phys_addr_t physaddr, - target_ulong addr, void *retaddr, Expr::Width width) { - uint64_t r; - unsigned bw; - ref ret; - target_phys_addr_t origaddr = physaddr; - const struct MemoryDescOps *ops = phys_get_ops(physaddr); - - target_ulong naddr = (physaddr & TARGET_PAGE_MASK) + addr; - - env_cpu(env)->mem_io_pc = (uintptr_t) retaddr; - state->setMemIoVaddr(ConstantExpr::create(addr, sizeof(target_ulong) * 8)); - - if (is_notdirty_ops(ops)) { - ret = state->mem()->read(tlb.addend + addr, width, HostAddress); - goto end; - } - - bw = Expr::getMinBytesForWidth(width); - - if (bw <= 4) { - if (se_ismemfunc(ops, 0)) { - uintptr_t pa = se_notdirty_mem_read(naddr); - ret = state->mem()->read(pa, width, HostAddress); - goto end; - } - } else { -#ifdef TARGET_WORDS_BIGENDIAN - abort(); -#else - if (se_ismemfunc(ops, 0)) { - uintptr_t pa = se_notdirty_mem_read(naddr); - auto e1 = state->mem()->read(pa, width, HostAddress); - - pa = se_notdirty_mem_read(naddr + 4); - auto e2 = state->mem()->read(pa, width, HostAddress); - - ret = ConcatExpr::create(e2, e1); - goto end; - } -#endif - } - - switch (bw) { - case 1: - r = io_readb_mmu(env, origaddr, addr, retaddr); - break; - case 2: - r = io_readw_mmu(env, origaddr, addr, retaddr); - break; - case 4: - r = io_readl_mmu(env, origaddr, addr, retaddr); - break; - case 8: - r = io_readq_mmu(env, origaddr, addr, retaddr); - break; - default: - abort(); - } - - ret = ConstantExpr::create(r, width); -end: - // TODO: trace mmio - state->setMemIoVaddr(nullptr); - return ret; -} - static ref handleForkAndConcretizeNative(Executor *executor, ExecutionState *state, klee::KInstruction *target, const ref &symbAddress) { ref constantAddress = dyn_cast(symbAddress); @@ -197,413 +73,193 @@ static ref handleForkAndConcretizeNative(Executor *executor, Execu return constantAddress; } -template -static ref handle_ldst_mmu(Executor *executor, ExecutionState *state, klee::KInstruction *target, const V &args, - bool isWrite, unsigned data_size, bool signExtend, bool zeroExtend) { - S2EExecutionState *s2estate = static_cast(state); - - ref envExpr = dyn_cast(args[0]); - assert(envExpr); - CPUArchState *env = (CPUArchState *) envExpr->getZExtValue(); - - const auto &symbAddress = args[1]; - ref constantAddress = handleForkAndConcretizeNative(executor, state, target, symbAddress); - - ref mmuIdxExpr = args[isWrite ? 3 : 2]; - unsigned mmu_idx = get_mmuidx(dyn_cast(mmuIdxExpr)->getZExtValue()); - - // XXX: determine this by looking at the instruction that called us - Expr::Width width = data_size * 8; - Expr::Width addressWidth = symbAddress->getWidth(); - - target_ulong addr = constantAddress->getZExtValue(); - target_ulong object_index, index; - ref value; - target_ulong tlb_addr, addr1, addr2; - target_phys_addr_t addend, ioaddr; - void *retaddr = nullptr; - - if (isWrite) { - value = args[2]; - assert(value->getWidth() == width); +static void traceAccess(Executor *executor, ExecutionState *state, klee::KInstruction *target, const ref &address, + const ref &value, unsigned size, unsigned flags) { + auto corePlugin = g_s2e->getCorePlugin(); + if (corePlugin->onAfterSymbolicDataMemoryAccess.empty() && corePlugin->onConcreteDataMemoryAccess.empty()) { + return; } - object_index = addr >> SE_RAM_OBJECT_BITS; - index = (object_index >> S2E_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); - -redo: - - const auto &tlbEntry = env_tlb(env)->f[mmu_idx].table[index]; + std::vector> traceArgs; + traceArgs.push_back(address); + traceArgs.push_back(value); + traceArgs.push_back(ConstantExpr::create(size, Expr::Int32)); + traceArgs.push_back(ConstantExpr::create(flags, Expr::Int64)); + traceArgs.push_back(ConstantExpr::create(0, Expr::Int64)); + handlerAfterMemoryAccess(executor, state, target, traceArgs); +} +/// Reads or writes a device register through the native softmmu. Devices +/// only take concrete values. +static ref accessMmio(S2EExecutionState *state, CPUArchState *env, target_ulong addr, const ref &value, + MemOpIdx oi, bool isWrite, unsigned size) { if (isWrite) { - tlb_addr = tlbEntry.addr_write & ~TLB_MEM_TRACE; - } else { - tlb_addr = tlbEntry.addr_read & ~TLB_MEM_TRACE; + uint64_t v = state->concretize(value, "mmio write", false); + switch (size) { + case 1: + cpu_stb_mmu(env, addr, v, oi, 0); + break; + case 2: + cpu_stw_mmu(env, addr, v, oi, 0); + break; + case 4: + cpu_stl_mmu(env, addr, v, oi, 0); + break; + case 8: + cpu_stq_mmu(env, addr, v, oi, 0); + break; + default: + abort(); + } + return ref(); } - if (likely((addr & TARGET_PAGE_MASK) == (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK)))) { - if (unlikely(tlb_addr & ~TARGET_PAGE_MASK)) { - /* IO access */ - if ((addr & (data_size - 1)) != 0) { - goto do_unaligned_access; - } - - ioaddr = env_tlb(env)->d[mmu_idx].iotlb[index]; - - if (!isWrite) { - value = io_read_chk(s2estate, tlbEntry, ioaddr, addr, retaddr, width); - } - - auto corePlugin = g_s2e->getCorePlugin(); - if (!corePlugin->onAfterSymbolicDataMemoryAccess.empty() || - !corePlugin->onConcreteDataMemoryAccess.empty()) { - // Trace the access - std::vector> traceArgs; - traceArgs.push_back(symbAddress); - traceArgs.push_back(value); - traceArgs.push_back(ConstantExpr::create(width / 8, Expr::Int32)); - unsigned flags = isWrite ? MEM_TRACE_FLAG_WRITE : 0; - traceArgs.push_back(ConstantExpr::create(flags | MEM_TRACE_FLAG_IO, Expr::Int64)); - traceArgs.push_back(ConstantExpr::create(0, Expr::Int64)); - handlerAfterMemoryAccess(executor, state, target, traceArgs); - } - - if (isWrite) { - io_write_chk(s2estate, env, ioaddr, value, addr, retaddr, width); - } + uint64_t v; + switch (size) { + case 1: + v = cpu_ldb_mmu(env, addr, oi, 0); + break; + case 2: + v = cpu_ldw_mmu(env, addr, oi, 0); + break; + case 4: + v = cpu_ldl_mmu(env, addr, oi, 0); + break; + case 8: + v = cpu_ldq_mmu(env, addr, oi, 0); + break; + default: + abort(); + } + return ConstantExpr::create(v, size * 8); +} - } else if (unlikely(((addr & ~SE_RAM_OBJECT_MASK) + data_size - 1) >= SE_RAM_OBJECT_SIZE)) { - /* slow unaligned access (it spans two pages or IO) */ - do_unaligned_access: +/// Performs one guest memory access. +/// +/// @param address the guest virtual address, possibly symbolic +/// @param value the value to store, size bytes wide; unused for loads +/// @return the value loaded, size bytes wide; null for stores +static ref accessMemory(Executor *executor, ExecutionState *state, klee::KInstruction *target, CPUArchState *env, + const ref &address, const ref &value, MemOpIdx oi, bool isWrite, + unsigned size) { + S2EExecutionState *s2estate = static_cast(state); + CPUState *cpu = env_cpu(env); + const unsigned mmu_idx = get_mmuidx(oi); + const MMUAccessType type = isWrite ? MMU_DATA_STORE : MMU_DATA_LOAD; + const Expr::Width width = size * 8; - if (isWrite) { - for (int i = data_size - 1; i >= 0; i--) { - HandlerArgs unalignedAccessArgs; -#ifdef TARGET_WORDS_BIGENDIAN - ref shiftCount = ConstantExpr::create((((data_size - 1) * 8) - (i * 8)), width); -#else - ref shiftCount = ConstantExpr::create(i * 8, width); -#endif - - ref shiftedValue = LShrExpr::create(value, shiftCount); - ref resizedValue = ExtractExpr::create(shiftedValue, 0, Expr::Int8); - unalignedAccessArgs.push_back(args[0]); - unalignedAccessArgs.push_back(ConstantExpr::create(addr + i, addressWidth)); - unalignedAccessArgs.push_back(resizedValue); - unalignedAccessArgs.push_back(mmuIdxExpr); - unalignedAccessArgs.push_back(args[3]); - handle_ldst_mmu(executor, state, target, unalignedAccessArgs, true, 1, false, false); - } - } else { - addr1 = addr & ~((target_ulong) data_size - 1); - addr2 = addr1 + (target_ulong) data_size; - - HandlerArgs unalignedAccessArgs; - unalignedAccessArgs.push_back(args[0]); - unalignedAccessArgs.push_back(ConstantExpr::create(addr1, addressWidth)); - unalignedAccessArgs.push_back(mmuIdxExpr); - unalignedAccessArgs.push_back(args[2]); - ref value1 = handle_ldst_mmu(executor, state, target, unalignedAccessArgs, isWrite, data_size, - signExtend, zeroExtend); - - unalignedAccessArgs[1] = ConstantExpr::create(addr2, addressWidth); - ref value2 = handle_ldst_mmu(executor, state, target, unalignedAccessArgs, isWrite, data_size, - signExtend, zeroExtend); - - ref shift = ConstantExpr::create((addr & (data_size - 1)) * 8, width); - ref shift2 = ConstantExpr::create((data_size * 8) - ((addr & (data_size - 1)) * 8), width); - -#ifdef TARGET_WORDS_BIGENDIAN - value = OrExpr::create(ShlExpr::create(value1, shift), LShrExpr::create(value2, shift2)); -#else - value = OrExpr::create(LShrExpr::create(value1, shift), ShlExpr::create(value2, shift2)); -#endif - - auto corePlugin = g_s2e->getCorePlugin(); - if (!corePlugin->onAfterSymbolicDataMemoryAccess.empty() || - !corePlugin->onConcreteDataMemoryAccess.empty()) { - // Trace the access - std::vector> traceArgs; - traceArgs.push_back(symbAddress); - traceArgs.push_back(value); - traceArgs.push_back(ConstantExpr::create(width / 8, Expr::Int32)); - unsigned flags = isWrite ? MEM_TRACE_FLAG_WRITE : 0; - traceArgs.push_back(ConstantExpr::create(flags, Expr::Int64)); - traceArgs.push_back(ConstantExpr::create(0, Expr::Int64)); - handlerAfterMemoryAccess(executor, state, target, traceArgs); - } - } - } else { -/* unaligned/aligned access in the same page */ -#ifdef ALIGNED_ONLY - if ((addr & (DATA_SIZE - 1)) != 0) { - do_unaligned_access(ENV_VAR addr, READ_ACCESS_TYPE, mmu_idx, retaddr); - } -#endif - addend = tlbEntry.addend; + ref constantAddress = handleForkAndConcretizeNative(executor, state, target, address); + target_ulong addr = constantAddress->getZExtValue(); + if (((addr & ~TARGET_PAGE_MASK) + size) > TARGET_PAGE_SIZE) { + // The access spans two pages: do it one byte at a time, in guest + // (little endian) byte order. + ref result; + for (unsigned i = 0; i < size; ++i) { + auto byteAddress = ConstantExpr::create((target_ulong) (addr + i), address->getWidth()); + MemOpIdx byteOi = make_memop_idx(MO_UB, mmu_idx); if (isWrite) { - s2estate->mem()->write(addr + addend, value, HostAddress); + auto byte = ExtractExpr::create(value, i * 8, Expr::Int8); + accessMemory(executor, state, target, env, byteAddress, byte, byteOi, true, 1); } else { - value = s2estate->mem()->read(addr + addend, width, HostAddress); - } - - auto corePlugin = g_s2e->getCorePlugin(); - if (!corePlugin->onAfterSymbolicDataMemoryAccess.empty() || - !corePlugin->onConcreteDataMemoryAccess.empty()) { - // Trace the access - std::vector> traceArgs; - traceArgs.push_back(symbAddress); - traceArgs.push_back(value); - traceArgs.push_back(ConstantExpr::create(width / 8, Expr::Int32)); - unsigned flags = isWrite ? MEM_TRACE_FLAG_WRITE : 0; - traceArgs.push_back(ConstantExpr::create(flags, Expr::Int64)); - traceArgs.push_back(ConstantExpr::create(0, Expr::Int64)); - handlerAfterMemoryAccess(executor, state, target, traceArgs); + auto byte = accessMemory(executor, state, target, env, byteAddress, ref(), byteOi, false, 1); + result = result ? ConcatExpr::create(byte, result) : byte; } } - } else { - /* the page is not in the TLB : fill it */ - tlb_fill(env, addr, object_index << SE_RAM_OBJECT_BITS, isWrite, mmu_idx, retaddr); - goto redo; - } - - if (!isWrite) { - if (zeroExtend) { - assert(data_size == 2); - value = ZExtExpr::create(value, Expr::Int32); - } - return value; - } else { - return ref(); + return result; } -} -static void handle_ldb_mmu(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 4); - ref value = handle_ldst_mmu(executor, state, target, args, false, 1, false, false); - assert(value->getWidth() == Expr::Int8); - state->llvm.bindLocal(target, value); -} - -static void handle_ldw_mmu(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 4); - ref value = handle_ldst_mmu(executor, state, target, args, false, 2, false, false); - assert(value->getWidth() == Expr::Int16); - state->llvm.bindLocal(target, value); -} - -static void handle_ldl_mmu(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 4); - ref value = handle_ldst_mmu(executor, state, target, args, false, 4, false, false); - assert(value->getWidth() == Expr::Int32); - state->llvm.bindLocal(target, value); -} - -static void handle_ldq_mmu(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 4); - ref value = handle_ldst_mmu(executor, state, target, args, false, 8, false, false); - assert(value->getWidth() == Expr::Int64); - state->llvm.bindLocal(target, value); -} - -static void handle_stb_mmu(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 5); - handle_ldst_mmu(executor, state, target, args, true, 1, false, false); -} - -static void handle_stw_mmu(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 5); - handle_ldst_mmu(executor, state, target, args, true, 2, false, false); -} + CPUTLBDescFast *fast = cpu_tlb_fast(cpu, mmu_idx); + const uintptr_t index = (addr >> TARGET_PAGE_BITS) & (fast->mask >> CPU_TLB_ENTRY_BITS); + const CPUTLBEntry *entry = &fast->table[index]; + uintptr_t tlb_addr = isWrite ? entry->addr_write : entry->addr_read; -static void handle_stl_mmu(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 5); - handle_ldst_mmu(executor, state, target, args, true, 4, false, false); -} - -static void handle_stq_mmu(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 5); - handle_ldst_mmu(executor, state, target, args, true, 8, false, false); -} - -static void handle_ldst_kernel(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args, bool isWrite, unsigned dataSize, bool signExtend, - bool zeroExtend) { - S2EExecutionState *s2estate = static_cast(state); - unsigned mmu_idx = CPU_MMU_INDEX; - - ref envExpr = dyn_cast(args[0]); - assert(envExpr); - CPUArchState *env = (CPUArchState *) envExpr->getZExtValue(); + if ((addr & TARGET_PAGE_MASK) != (tlb_addr & (TARGET_PAGE_MASK | TLB_INVALID_MASK))) { + // Not in the TLB. A guest fault leaves through the CPU loop and does + // not come back here. + x86_cpu_tlb_fill(cpu, addr, size, type, mmu_idx, false, 0); + tlb_addr = isWrite ? entry->addr_write : entry->addr_read; + } - const auto &symbAddress = args[1]; - ref constantAddress = handleForkAndConcretizeNative(executor, state, target, symbAddress); + CPUTLBEntryFull *full = &cpu->neg.tlb.d[mmu_idx].fulltlb[index]; + int flags = tlb_addr & (TLB_FLAGS_MASK & ~TLB_FORCE_SLOW); + flags |= full->slow_flags[type]; - Expr::Width width = dataSize * 8; - target_ulong addr = constantAddress->getZExtValue(); - target_ulong object_index, page_index, tlb_addr; - ref value; - uintptr_t physaddr; - - object_index = addr >> SE_RAM_OBJECT_BITS; - page_index = (object_index >> S2E_RAM_OBJECT_DIFF) & (CPU_TLB_SIZE - 1); + if (flags & TLB_WATCHPOINT) { + cpu_check_watchpoint(cpu, addr, size, full->attrs, isWrite ? BP_MEM_WRITE : BP_MEM_READ, 0); + } - ////////////////////////////////////////// - const auto &tlbEntry = env_tlb(env)->f[mmu_idx].table[page_index]; + ref result; - if (isWrite) { - value = args[2]; - if (value->getWidth() > width) { - value = ExtractExpr::create(value, 0, width); - } + if (flags & TLB_MMIO) { + result = accessMmio(s2estate, env, addr, value, oi, isWrite, size); + traceAccess(executor, state, target, address, isWrite ? value : result, size, + (isWrite ? MEM_TRACE_FLAG_WRITE : 0) | MEM_TRACE_FLAG_IO); + return result; + } - tlb_addr = tlbEntry.addr_write & ~TLB_MEM_TRACE; - } else { - tlb_addr = tlbEntry.addr_read & ~TLB_MEM_TRACE; + if (isWrite && (flags & TLB_NOTDIRTY)) { + notdirty_write(cpu, addr, size, full, 0); } - if (unlikely(tlb_addr != (addr & (TARGET_PAGE_MASK | (dataSize - 1))))) { - - HandlerArgs slowArgs; - - if (isWrite) { - slowArgs.push_back(envExpr); - slowArgs.push_back(constantAddress); - slowArgs.push_back(value); - slowArgs.push_back(ConstantExpr::create(mmu_idx, Expr::Int64)); - slowArgs.push_back(ConstantExpr::create(0, Expr::Int64)); - handle_ldst_mmu(executor, state, target, slowArgs, isWrite, dataSize, signExtend, zeroExtend); - } else { - slowArgs.push_back(envExpr); - slowArgs.push_back(constantAddress); - slowArgs.push_back(ConstantExpr::create(mmu_idx, Expr::Int64)); - slowArgs.push_back(ConstantExpr::create(0, Expr::Int64)); - value = handle_ldst_mmu(executor, state, target, slowArgs, isWrite, dataSize, signExtend, zeroExtend); - state->llvm.bindLocal(target, value); + // KLEE binds the page at its address in guest RAM (addend). se_addend + // points into the concrete buffer and is for natively executed code. + const uint64_t host = addr + entry->addend; + if (isWrite) { + if (!(flags & TLB_DISCARD_WRITE)) { + s2estate->mem()->write(host, value, HostAddress); } - return; - } else { - // When we get here, the address is aligned with the size of the access, - // which by definition means that it will fall inside the small page, without overflowing. - physaddr = addr + tlbEntry.addend; - - if (isWrite) { - s2estate->mem()->write(physaddr, value, HostAddress); - } else { - value = s2estate->mem()->read(physaddr, width, HostAddress); - } - - // Trace the access - // TODO: don't do this if there is no instrumentation - auto corePlugin = g_s2e->getCorePlugin(); - if (!corePlugin->onAfterSymbolicDataMemoryAccess.empty() || !corePlugin->onConcreteDataMemoryAccess.empty()) { - std::vector> traceArgs; - traceArgs.push_back(constantAddress); - traceArgs.push_back(value); - traceArgs.push_back(ConstantExpr::create(width / 8, Expr::Int32)); - unsigned flags = isWrite ? MEM_TRACE_FLAG_WRITE : 0; - traceArgs.push_back(ConstantExpr::create(flags, Expr::Int64)); - traceArgs.push_back(ConstantExpr::create(0, Expr::Int64)); - handlerAfterMemoryAccess(executor, state, target, traceArgs); - } - - if (!isWrite) { - if (zeroExtend) { - assert(dataSize < 4); - value = ZExtExpr::create(value, Expr::Int32); - } - state->llvm.bindLocal(target, value); - } + result = s2estate->mem()->read(host, width, HostAddress); } -} -static void handle_ldub_kernel(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 2); - handle_ldst_kernel(executor, state, target, args, false, 1, false, true); + traceAccess(executor, state, target, address, isWrite ? value : result, size, isWrite ? MEM_TRACE_FLAG_WRITE : 0); + return result; } -static void handle_lduw_kernel(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 2); - handle_ldst_kernel(executor, state, target, args, false, 2, false, true); -} - -// TODO: implement lds -static void handle_ldl_kernel(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 2); - handle_ldst_kernel(executor, state, target, args, false, 4, false, false); -} +/// Handles helper_ld{ub,uw,ul,q,sb,sw,sl}_mmu(env, addr, oi, retaddr). They +/// return a register-sized value, zero or sign extended. +template +static void handleLoad(Executor *executor, ExecutionState *state, klee::KInstruction *target, + std::vector> &args) { + assert(args.size() == 4); + auto env = (CPUArchState *) cast(args[0])->getZExtValue(); + MemOpIdx oi = cast(args[2])->getZExtValue(); -#ifdef TARGET_X86_64 -static void handle_ldq_kernel(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 2); - handle_ldst_kernel(executor, state, target, args, false, 8, false, false); -} -#endif + ref value = accessMemory(executor, state, target, env, args[1], ref(), oi, false, SIZE); -static void handle_stb_kernel(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 3); - handle_ldst_kernel(executor, state, target, args, true, 1, false, false); + const Expr::Width retWidth = sizeof(tcg_target_ulong) * 8; + if (value->getWidth() < retWidth) { + value = SIGNED ? SExtExpr::create(value, retWidth) : ZExtExpr::create(value, retWidth); + } + state->llvm.bindLocal(target, value); } -static void handle_stw_kernel(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 3); - handle_ldst_kernel(executor, state, target, args, true, 2, false, false); -} +/// Handles helper_st{b,w,l,q}_mmu(env, addr, val, oi, retaddr). The value +/// argument can be wider than the access. +template +static void handleStore(Executor *executor, ExecutionState *state, klee::KInstruction *target, + std::vector> &args) { + assert(args.size() == 5); + auto env = (CPUArchState *) cast(args[0])->getZExtValue(); + MemOpIdx oi = cast(args[3])->getZExtValue(); -static void handle_stl_kernel(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 3); - handle_ldst_kernel(executor, state, target, args, true, 4, false, false); -} + ref value = args[2]; + if (value->getWidth() > SIZE * 8) { + value = ExtractExpr::create(value, 0, SIZE * 8); + } -#ifdef TARGET_X86_64 -static void handle_stq_kernel(Executor *executor, ExecutionState *state, klee::KInstruction *target, - std::vector> &args) { - assert(args.size() == 3); - handle_ldst_kernel(executor, state, target, args, true, 8, false, false); + accessMemory(executor, state, target, env, args[1], value, oi, true, SIZE); } -#endif static Handler s_handlerInfo[] = { #define add(name, handler) {name, &handler, nullptr} - add("helper_ldb_mmu", handle_ldb_mmu), - add("helper_ldw_mmu", handle_ldw_mmu), - add("helper_ldl_mmu", handle_ldl_mmu), - add("helper_ldq_mmu", handle_ldq_mmu), - add("helper_stb_mmu", handle_stb_mmu), - add("helper_stw_mmu", handle_stw_mmu), - add("helper_stl_mmu", handle_stl_mmu), - add("helper_stq_mmu", handle_stq_mmu), - add("cpu_stb_kernel", handle_stb_kernel), - add("cpu_stw_kernel", handle_stw_kernel), - add("cpu_stl_kernel", handle_stl_kernel), - add("cpu_ldub_kernel", handle_ldub_kernel), - add("cpu_lduw_kernel", handle_lduw_kernel), - add("cpu_ldl_kernel", handle_ldl_kernel), - -#ifdef TARGET_X86_64 - add("helper_ldq_mmu", handle_ldq_mmu), - add("helper_stq_mmu", handle_stq_mmu), - add("cpu_ldq_kernel", handle_ldq_kernel), - add("cpu_stq_kernel", handle_stq_kernel) -#endif /* TARGET_X86_64 */ - + add("helper_ldub_mmu", (handleLoad<1, false>) ), add("helper_lduw_mmu", (handleLoad<2, false>) ), + add("helper_ldul_mmu", (handleLoad<4, false>) ), add("helper_ldq_mmu", (handleLoad<8, false>) ), + add("helper_ldsb_mmu", (handleLoad<1, true>) ), add("helper_ldsw_mmu", (handleLoad<2, true>) ), + add("helper_ldsl_mmu", (handleLoad<4, true>) ), add("helper_stb_mmu", handleStore<1>), + add("helper_stw_mmu", handleStore<2>), add("helper_stl_mmu", handleStore<4>), + add("helper_stq_mmu", handleStore<8>), #undef add }; diff --git a/libs2ecore/src/S2EExecutionState.cpp b/libs2ecore/src/S2EExecutionState.cpp index 0f2269b06..f99d147f7 100644 --- a/libs2ecore/src/S2EExecutionState.cpp +++ b/libs2ecore/src/S2EExecutionState.cpp @@ -841,6 +841,7 @@ void se_write_dirty_mask(uint64_t host_address, uint8_t val) { return g_s2e_state->mem()->writeDirtyMask(host_address, val); } +#if defined(CONFIG_SYMBEX_MP) || defined(SE_ENABLE_PHYSRAM_TLB) static inline CPUTLBRAMEntry *s2e_get_ram_tlb_entry(uint64_t host_address) { #if defined(SE_ENABLE_PHYSRAM_TLB) uintptr_t tlb_index = (host_address >> 12) & (CPU_TLB_SIZE - 1); @@ -850,6 +851,7 @@ static inline CPUTLBRAMEntry *s2e_get_ram_tlb_entry(uint64_t host_address) { return nullptr; #endif } +#endif #ifdef SE_ENABLE_PHYSRAM_TLB static inline void s2e_dma_rw(uint64_t hostAddress, uint8_t *buf, unsigned size, bool is_write) { @@ -903,12 +905,6 @@ void s2e_dma_write(uint64_t hostAddress, uint8_t *buf, unsigned size) { #endif } -void s2e_read_ram_concrete_check(uint64_t host_address, uint8_t *buf, uint64_t size) { - assert(g_s2e_state->isRunningConcrete()); - CPUTLBRAMEntry *re = s2e_get_ram_tlb_entry(host_address); - g_s2e_state->mem()->transferRam(re, host_address, buf, size, false, true); -} - void s2e_read_ram_concrete(uint64_t host_address, void *buf, uint64_t size) { #ifdef CONFIG_SYMBEX_MP CPUTLBRAMEntry *re = s2e_get_ram_tlb_entry(host_address); diff --git a/libs2ecore/src/S2EExecutionStateTlb.cpp b/libs2ecore/src/S2EExecutionStateTlb.cpp index 74881f66a..7a257002d 100644 --- a/libs2ecore/src/S2EExecutionStateTlb.cpp +++ b/libs2ecore/src/S2EExecutionStateTlb.cpp @@ -50,6 +50,24 @@ namespace s2e { using namespace klee; +namespace { +/// Number of entries of the main TLB of one MMU index. +inline unsigned tlbSize(CPUState *cpu, unsigned mmu_idx) { + return (cpu->neg.tlb.f[mmu_idx].mask >> CPU_TLB_ENTRY_BITS) + 1; +} + +/// The comparators, addend and se_addend of entry (mmu_idx, index). +inline CPUTLBEntry *fastEntry(CPUState *cpu, unsigned mmu_idx, unsigned index) { + return &cpu->neg.tlb.f[mmu_idx].table[index]; +} + +/// The KLEE object that backs the page of entry (mmu_idx, index). The +/// pointer is in the full entry, which generated code does not read. +inline void *&entryObject(CPUState *cpu, unsigned mmu_idx, unsigned index) { + return cpu->neg.tlb.d[mmu_idx].fulltlb[index].extra.object_state; +} +} // namespace + bool S2EExecutionStateTlb::addressSpaceChangeUpdateTlb(const klee::ObjectStateConstPtr &oldState, const klee::ObjectStatePtr &newState) { if (!(oldState && oldState->isMemoryPage())) { @@ -153,12 +171,12 @@ void S2EExecutionStateTlb::updateTlb(const klee::ObjectStateConstPtr &oldState, #ifdef S2E_DEBUG_TLBCACHE g_s2e->getDebugStream() << " mmu_idx=" << coords.first << " index=" << coords.second << "\n"; #endif - CPUTLBEntry *entry = &cpu->neg.tlb.f[coords.first].table[coords.second]; - assert(entry->objectState == (void *) oldState.get()); + CPUTLBEntry *entry = fastEntry(cpu, coords.first, coords.second); + assert(entryObject(cpu, coords.first, coords.second) == (void *) oldState.get()); assert(newState); // XXX: use proper refcounting - entry->objectState = newState.get(); + entryObject(cpu, coords.first, coords.second) = newState.get(); if (!newState->isSharedConcrete()) { // The addend does not change. @@ -215,9 +233,9 @@ void S2EExecutionStateTlb::flushTlbCachePage(const klee::ObjectStatePtr &objectS << "flushTlbCachePage: clearing cache entry for " << objectState << " (" << mmu_idx << "," << index << ")\n"; #endif - CPUTLBEntry *entry = &m_registers->getCpuCaches()->neg.tlb.f[mmu_idx].table[index]; - entry->objectState = 0; - entry->se_addend = 0; + CPUState *cpu = m_registers->getCpuCaches(); + entryObject(cpu, mmu_idx, index) = nullptr; + fastEntry(cpu, mmu_idx, index)->se_addend = 0; if (g_s2e_single_path_mode) { return; @@ -290,9 +308,9 @@ void S2EExecutionStateTlb::clearRamTlb() { void S2EExecutionStateTlb::clearTlbOwnership() { CPUState *cpu = m_registers->getCpuCaches(); - for (unsigned i = 0; i < CPU_TLB_SIZE; i++) { - for (unsigned mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - cpu->neg.tlb.f[mmu_idx].table[i].addr_write |= TLB_NOT_OURS; + for (unsigned mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { + for (unsigned i = 0; i < tlbSize(cpu, mmu_idx); i++) { + fastEntry(cpu, mmu_idx, i)->addr_write |= TLB_NOT_OURS; } } } @@ -301,10 +319,11 @@ void S2EExecutionStateTlb::updateTlbEntry(int mmu_idx, uint64_t virtAddr, uint64 assert((hostAddr & ~TARGET_PAGE_MASK) == 0); assert((virtAddr & ~TARGET_PAGE_MASK) == 0); - unsigned int index = (virtAddr >> SE_RAM_OBJECT_BITS) & (CPU_TLB_SIZE - 1); + CPUState *cpu = m_registers->getCpuCaches(); + unsigned int index = (virtAddr >> TARGET_PAGE_BITS) & (tlbSize(cpu, mmu_idx) - 1); - CPUTLBEntry *entry = &m_registers->getCpuCaches()->neg.tlb.f[mmu_idx].table[index]; - ObjectState *oldObjectState = static_cast(entry->objectState); + CPUTLBEntry *entry = fastEntry(cpu, mmu_idx, index); + ObjectState *oldObjectState = static_cast(entryObject(cpu, mmu_idx, index)); /* Retrieve the object state using the host address */ auto newObjectState = m_asCache->get(hostAddr); @@ -332,7 +351,7 @@ void S2EExecutionStateTlb::updateTlbEntry(int mmu_idx, uint64_t virtAddr, uint64 #endif /* Update the TLB entry */ - entry->objectState = const_cast(newObjectState.get()); + entryObject(cpu, mmu_idx, index) = const_cast(newObjectState.get()); if (newObjectState->isSharedConcrete()) { entry->se_addend = (hostAddr - virtAddr); @@ -362,26 +381,26 @@ bool S2EExecutionStateTlb::audit() { for (const auto &[os, refs] : m_tlbMap) { for (const auto &[mmu_idx, index] : refs) { - const CPUTLBEntry *entry = &cpu->neg.tlb.f[mmu_idx].table[index]; - if (entry->objectState != os.get()) { + void *object = entryObject(cpu, mmu_idx, index); + if (object != os.get()) { llvm::errs() << "TLB audit: map entry (" << mmu_idx << "," << index << ") refers to " - << hexval(os.get()) << " but the TLB holds " << hexval(entry->objectState) << "\n"; + << hexval(os.get()) << " but the TLB holds " << hexval(object) << "\n"; return false; } } } for (unsigned mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { - for (unsigned index = 0; index < CPU_TLB_SIZE; index++) { - const CPUTLBEntry *entry = &cpu->neg.tlb.f[mmu_idx].table[index]; - if (!entry->objectState) { + for (unsigned index = 0; index < tlbSize(cpu, mmu_idx); index++) { + void *object = entryObject(cpu, mmu_idx, index); + if (!object) { continue; } - auto it = m_tlbMap.find(static_cast(entry->objectState)); + auto it = m_tlbMap.find(static_cast(object)); if (it == m_tlbMap.end()) { - llvm::errs() << "TLB audit: TLB entry (" << mmu_idx << "," << index << ") refers to " - << hexval(entry->objectState) << " which is not in the map\n"; + llvm::errs() << "TLB audit: TLB entry (" << mmu_idx << "," << index << ") refers to " << hexval(object) + << " which is not in the map\n"; return false; } @@ -394,7 +413,7 @@ bool S2EExecutionStateTlb::audit() { if (foundCount != 1) { llvm::errs() << "TLB audit: TLB entry (" << mmu_idx << "," << index << ") is referenced " << foundCount - << " times by " << hexval(entry->objectState) << "\n"; + << " times by " << hexval(object) << "\n"; return false; } } diff --git a/libs2ecore/src/S2EExecutor.cpp b/libs2ecore/src/S2EExecutor.cpp index 4df06b435..1062da885 100644 --- a/libs2ecore/src/S2EExecutor.cpp +++ b/libs2ecore/src/S2EExecutor.cpp @@ -36,6 +36,8 @@ #include +#include + #include #include #include @@ -329,15 +331,12 @@ S2EExecutor::S2EExecutor(S2E *s2e, TCGLLVMTranslator *translator) __DEFINE_EXT_FUNCTION(tlb_flush_page) __DEFINE_EXT_FUNCTION(tlb_flush) - __DEFINE_EXT_FUNCTION(io_readb_mmu) - __DEFINE_EXT_FUNCTION(io_readw_mmu) - __DEFINE_EXT_FUNCTION(io_readl_mmu) - __DEFINE_EXT_FUNCTION(io_readq_mmu) - - __DEFINE_EXT_FUNCTION(io_writeb_mmu) - __DEFINE_EXT_FUNCTION(io_writew_mmu) - __DEFINE_EXT_FUNCTION(io_writel_mmu) - __DEFINE_EXT_FUNCTION(io_writeq_mmu) + // The native half of the softmmu, which its bitcode half calls + // (libcpu/src/accel/cputlb.c). + __DEFINE_EXT_FUNCTION(notdirty_write) + __DEFINE_EXT_FUNCTION(do_ld_mmio_beN) + __DEFINE_EXT_FUNCTION(do_st_mmio_leN) + __DEFINE_EXT_FUNCTION(cpu_check_watchpoint) __DEFINE_EXT_FUNCTION(se_ensure_symbolic) @@ -354,13 +353,6 @@ S2EExecutor::S2EExecutor(S2E *s2e, TCGLLVMTranslator *translator) __DEFINE_EXT_FUNCTION(s2e_on_privilege_change); __DEFINE_EXT_FUNCTION(s2e_on_page_fault); - __DEFINE_EXT_FUNCTION(se_notdirty_mem_write) - __DEFINE_EXT_FUNCTION(se_notdirty_mem_read) - - __DEFINE_EXT_FUNCTION(se_ismemfunc) - __DEFINE_EXT_FUNCTION(phys_get_ops) - __DEFINE_EXT_FUNCTION(is_notdirty_ops) - __DEFINE_EXT_FUNCTION(ldub_phys) __DEFINE_EXT_FUNCTION(stb_phys) @@ -851,7 +843,7 @@ void S2EExecutor::doStateSwitch(S2EExecutionStatePtr oldState, S2EExecutionState // Clears the TLB and the TB jump cache, and in multi-path mode // empties the active state's map, which is newState here. - tlb_flush(env, 1); + tlb_flush(env_cpu(env)); } // m_s2e->getCorePlugin()->onStateSwitch.emit(oldState, newState); @@ -995,7 +987,7 @@ bool S2EExecutor::finalizeTranslationBlockExec(S2EExecutionState *state) { * Memory topology may change on state switches. * Ensure that there are no bad mappings left. */ - tlb_flush(env, 1); + tlb_flush(env_cpu(env)); return ret; } diff --git a/libtcg/include/tcg/cpu.h b/libtcg/include/tcg/cpu.h deleted file mode 100644 index 1e297d5a8..000000000 --- a/libtcg/include/tcg/cpu.h +++ /dev/null @@ -1,33 +0,0 @@ -/// Copyright (C) 2003 Fabrice Bellard -/// Copyright (C) 2010 Dependable Systems Laboratory, EPFL -/// Copyright (C) 2016 Cyberhaven -/// Copyrights of all contributions belong to their respective owners. -/// -/// This library is free software; you can redistribute it and/or -/// modify it under the terms of the GNU Library General Public -/// License as published by the Free Software Foundation; either -/// version 2 of the License, or (at your option) any later version. -/// -/// This library is distributed in the hope that it will be useful, -/// but WITHOUT ANY WARRANTY; without even the implied warranty of -/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -/// Library General Public License for more details. -/// -/// You should have received a copy of the GNU Library General Public -/// License along with this library; if not, see . - -#ifndef __LIBTCG_CPU_H__ - -#define __LIBTCG_CPU_H__ - -/* same as PROT_xxx */ -#define PAGE_READ 0x0001 -#define PAGE_WRITE 0x0002 -#define PAGE_EXEC 0x0004 -#define PAGE_BITS (PAGE_READ | PAGE_WRITE | PAGE_EXEC) -#define PAGE_VALID 0x0008 -/* original state of the write flag (used when tracking self-modifying - code */ -#define PAGE_WRITE_ORG 0x0010 - -#endif \ No newline at end of file diff --git a/libtcg/include/tcg/tcg.h b/libtcg/include/tcg/tcg.h index d98de1cc8..c7378f7bd 100644 --- a/libtcg/include/tcg/tcg.h +++ b/libtcg/include/tcg/tcg.h @@ -60,11 +60,7 @@ extern "C" { #define TARGET_PAGE_SIZE (1 << TARGET_PAGE_BITS) #define TARGET_PAGE_MASK ~(TARGET_PAGE_SIZE - 1) -#include - -// XXX: Fix me -#define CPU_TLB_BITS 10 -#define CPU_TLB_SIZE (1 << CPU_TLB_BITS) +#include #define QEMU_NORETURN __attribute__((__noreturn__)) @@ -78,8 +74,6 @@ typedef uint32_t target_ulong __attribute__((aligned(TARGET_LONG_ALIGNMENT))); #define TARGET_FMT_ld "%d" #define TARGET_FMT_lu "%u" -#define CPU_TLB_DYN_MAX_BITS (32 - TARGET_PAGE_BITS) - #elif TARGET_LONG_SIZE == 8 #define TARGET_LONG_ALIGNMENT 8 typedef int64_t target_long __attribute__((aligned(TARGET_LONG_ALIGNMENT))); @@ -88,9 +82,6 @@ typedef uint64_t target_ulong __attribute__((aligned(TARGET_LONG_ALIGNMENT))); #define TARGET_FMT_ld "%" PRId64 #define TARGET_FMT_lu "%" PRIu64 -// XXX: fix this -#define CPU_TLB_DYN_MAX_BITS (32 - TARGET_PAGE_BITS) - #else #error TARGET_LONG_SIZE undefined #endif @@ -551,22 +542,6 @@ struct TCGContext { void *__caller_init; /* Everything below is set before initializing TCG */ - /* helper signature: helper_ret_ld_mmu(CPUState *env, target_ulong addr, - * int mmu_idx, uintptr_t ra) - */ - void *qemu_ld_helpers[(MO_SIZE | MO_BSWAP) + 1]; - - /* helper signature: helper_ret_st_mmu(CPUState *env, target_ulong addr, - * uintxx_t val, int mmu_idx, uintptr_t ra) - */ - void *qemu_st_helpers[(MO_SIZE | MO_BSWAP) + 1]; - -// XXX: remove these? -#if defined(CONFIG_SYMBEX) && defined(TCG_ENABLE_MEM_TRACING) - void *qemu_ld_trace_helpers[4]; - void *qemu_st_trace_helpers[4]; -#endif - // CPU state offset information uintptr_t env_ptr; unsigned env_offset_eip; diff --git a/libtcg/include/tcg/tlb.h b/libtcg/include/tcg/tlb.h deleted file mode 100644 index 84f145f1a..000000000 --- a/libtcg/include/tcg/tlb.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef TCG_TLB_H - -#define TCG_TLB_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef CONFIG_SYMBEX -#define CPU_TLB_ENTRY_BITS 6 -#else -#define CPU_TLB_ENTRY_BITS 5 -#endif - -typedef struct CPUTLBEntry { - /* bit TARGET_LONG_BITS to TARGET_PAGE_BITS : virtual address - bit TARGET_PAGE_BITS-1..4 : Nonzero for accesses that should not - go directly to ram. - bit 3 : indicates that the entry is invalid - bit 2..0 : zero - */ - uint64_t addr_read; - uint64_t addr_write; - uint64_t addr_code; - - /* Addend to virtual address to get host address. IO accesses - use the corresponding iotlb value. */ - uintptr_t addend; - -#ifdef CONFIG_SYMBEX - uintptr_t se_addend; - void *objectState; - - /* padding to get a power of two size */ - uint8_t dummy[(1 << CPU_TLB_ENTRY_BITS) - (sizeof(uint64_t) * 3 + 3 * sizeof(uintptr_t))]; -#else - uint8_t dummy[(1 << CPU_TLB_ENTRY_BITS) - (sizeof(uint64_t) * 3 + 1 * sizeof(uintptr_t))]; -#endif -} CPUTLBEntry; - -QEMU_BUILD_BUG_ON(sizeof(CPUTLBEntry) != (1 << CPU_TLB_ENTRY_BITS)); - -/* - * Data elements that are per MMU mode, accessed by the fast path. - * The structure is aligned to aid loading the pair with one insn. - */ -typedef struct CPUTLBDescFast { - /* Contains (n_entries - 1) << CPU_TLB_ENTRY_BITS */ - uintptr_t mask; - /* The array of tlb entries itself. */ - CPUTLBEntry *table; -} CPUTLBDescFast QEMU_ALIGNED(2 * sizeof(void *)); - -/* Flags stored in the low bits of the TLB virtual address. These are - * defined so that fast path ram access is all zeros. - * The flags all must be between TARGET_PAGE_BITS and - * maximum address alignment bit. - */ -/* Zero if TLB entry is valid. */ -#define TLB_INVALID_MASK (1 << (TARGET_PAGE_BITS - 1)) -/* Set if TLB entry references a clean RAM page. The iotlb entry will - contain the page physical address. */ -#define TLB_NOTDIRTY (1 << (TARGET_PAGE_BITS - 2)) -/* Set if TLB entry is an IO callback. */ -#define TLB_MMIO (1 << (TARGET_PAGE_BITS - 3)) -/* Set if TLB entry must have MMU lookup repeated for every access */ -#define TLB_RECHECK (1 << (TARGET_PAGE_BITS - 4)) - -#ifdef CONFIG_SYMBEX -/* Set if TLB entry points to a page that has symbolic data */ -#define TLB_SYMB (1 << (TARGET_PAGE_BITS - 5)) - -/* Set if TLB entry points to a page that does not belong to us (only for write) */ -#define TLB_NOT_OURS (1 << (TARGET_PAGE_BITS - 6)) - -#endif - -/* Indicates that accesses to the page must be traced */ -#define TLB_MEM_TRACE (1 << (TARGET_PAGE_BITS - 7)) - -/* Use this mask to check interception with an alignment mask - * in a TCG backend. - */ -#ifdef CONFIG_SYMBEX -#define TLB_FLAGS_MASK (TLB_INVALID_MASK | TLB_NOTDIRTY | TLB_MMIO | TLB_SYMB | TLB_RECHECK | TLB_NOT_OURS) -#else -#define TLB_FLAGS_MASK (TLB_INVALID_MASK | TLB_NOTDIRTY | TLB_MMIO | TLB_RECHECK) -#endif - -#ifdef __cplusplus -} -#endif - -#endif \ No newline at end of file diff --git a/libtcg/scripts/upgrade/mapping.tsv b/libtcg/scripts/upgrade/mapping.tsv index 952ce5f52..92d3bf76d 100644 --- a/libtcg/scripts/upgrade/mapping.tsv +++ b/libtcg/scripts/upgrade/mapping.tsv @@ -1,7 +1,7 @@ # libtcg path upstream QEMU path, as of the tag recorded in BASELINE. # # Only files that track upstream appear here. S2E-original files -# (tcg-s2e.c, tcg-llvm.cpp, tcg/tb.h, tcg/tlb.h, tcg/regs.h, tcg/cpu.h, +# (tcg-s2e.c, tcg-llvm.cpp, tcg/tb.h, tcg/regs.h, # tcg/helper.h, tcg/ops_sse_header.h, tcg/qemu-plugin.h) are deliberately # absent: they have no upstream counterpart to merge from. # @@ -61,8 +61,6 @@ include/tcg/exec/helper-proto-common.h include/exec/helper-proto-common.h include/tcg/exec/plugin-gen.h include/exec/plugin-gen.h src/tcg-rt/tcg-runtime.c accel/tcg/tcg-runtime.c src/tcg-rt/tcg-runtime-gvec.c accel/tcg/tcg-runtime-gvec.c -src/atomic_common.c.inc accel/tcg/atomic_common.c.inc -src/atomic_template.h accel/tcg/atomic_template.h # --- target-dependent utilities ----------------------------------------- # What is left of the old utils/ subset: everything platform-independent # moved to libutils. cpu-float.h needs the softfloat types, bswap.h is the diff --git a/libtcg/src/CMakeLists.txt b/libtcg/src/CMakeLists.txt index 9951d296a..aea26af75 100644 --- a/libtcg/src/CMakeLists.txt +++ b/libtcg/src/CMakeLists.txt @@ -24,7 +24,7 @@ list (APPEND TCG_SOURCES utils/log.c region.c tcg.c tcg-s2e.c tcg-op-ldst.c tcg-common.c tcg-op.c optimize.c tcg-op-gvec.c tcg-op-vec.c tcg-rt/tcg-runtime-gvec.c tcg-rt/tcg-runtime.c - atomic-helpers.c + fpu/softfloat.c) if (WITH_SYMBEX) diff --git a/libtcg/src/atomic-helpers.c b/libtcg/src/atomic-helpers.c deleted file mode 100644 index 12675149e..000000000 --- a/libtcg/src/atomic-helpers.c +++ /dev/null @@ -1,61 +0,0 @@ -/* - * User emulator execution - * - * Copyright (c) 2003-2005 Fabrice Bellard - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, see . - */ - -#include - -// clang-format off -#include -#include -#include -// clang-format on - -#define ATOMIC_NAME(X) glue(glue(glue(cpu_atomic_##X, SUFFIX), END), _mmu) - -#define ATOMIC_MMU_CLEANUP - -#include "atomic_common.c.inc" - -#define DATA_SIZE 1 -#include "atomic_template.h" - -#define DATA_SIZE 2 -#include "atomic_template.h" - -#define DATA_SIZE 4 -#include "atomic_template.h" - -#ifdef CONFIG_ATOMIC64 -#define DATA_SIZE 8 -#include "atomic_template.h" -#endif - -#if HAVE_CMPXCHG128 || HAVE_ATOMIC128 -#define DATA_SIZE 16 -#include "atomic_template.h" -#endif - -// TODO: FIXME -void helper_st_i128(CPUArchState *env, uint64_t addr, Int128 val, MemOpIdx oi) { - abort(); -} - -Int128 helper_ld_i128(CPUArchState *env, uint64_t addr, uint32_t oi) { - abort(); - return int128_make64(0); -} \ No newline at end of file diff --git a/libtcg/src/atomic_common.c.inc b/libtcg/src/atomic_common.c.inc deleted file mode 100644 index 93ebc2aa2..000000000 --- a/libtcg/src/atomic_common.c.inc +++ /dev/null @@ -1,51 +0,0 @@ -#define CMPXCHG_HELPER(OP, TYPE) \ - TYPE HELPER(atomic_##OP)(CPUArchState * env, uint64_t addr, TYPE oldv, TYPE newv, uint32_t oi) { \ - abort(); \ - } - -CMPXCHG_HELPER(cmpxchgb, uint32_t) -CMPXCHG_HELPER(cmpxchgw_be, uint32_t) -CMPXCHG_HELPER(cmpxchgw_le, uint32_t) -CMPXCHG_HELPER(cmpxchgl_be, uint32_t) -CMPXCHG_HELPER(cmpxchgl_le, uint32_t) -CMPXCHG_HELPER(cmpxchgq_be, uint64_t) -CMPXCHG_HELPER(cmpxchgq_le, uint64_t) - -#undef CMPXCHG_HELPER - -#define ATOMIC_HELPER(OP, TYPE) \ - TYPE HELPER(glue(atomic_, OP))(CPUArchState * env, uint64_t addr, TYPE val, uint32_t oi) { \ - abort(); \ - } - -#define GEN_ATOMIC_HELPERS(OP) \ - ATOMIC_HELPER(glue(OP, b), uint32_t) \ - ATOMIC_HELPER(glue(OP, w_be), uint32_t) \ - ATOMIC_HELPER(glue(OP, w_le), uint32_t) \ - ATOMIC_HELPER(glue(OP, l_be), uint32_t) \ - ATOMIC_HELPER(glue(OP, l_le), uint32_t) \ - ATOMIC_HELPER(glue(OP, q_be), uint64_t) \ - ATOMIC_HELPER(glue(OP, q_le), uint64_t) - -GEN_ATOMIC_HELPERS(fetch_add) -GEN_ATOMIC_HELPERS(fetch_and) -GEN_ATOMIC_HELPERS(fetch_or) -GEN_ATOMIC_HELPERS(fetch_xor) -GEN_ATOMIC_HELPERS(fetch_smin) -GEN_ATOMIC_HELPERS(fetch_umin) -GEN_ATOMIC_HELPERS(fetch_smax) -GEN_ATOMIC_HELPERS(fetch_umax) - -GEN_ATOMIC_HELPERS(add_fetch) -GEN_ATOMIC_HELPERS(and_fetch) -GEN_ATOMIC_HELPERS(or_fetch) -GEN_ATOMIC_HELPERS(xor_fetch) -GEN_ATOMIC_HELPERS(smin_fetch) -GEN_ATOMIC_HELPERS(umin_fetch) -GEN_ATOMIC_HELPERS(smax_fetch) -GEN_ATOMIC_HELPERS(umax_fetch) - -GEN_ATOMIC_HELPERS(xchg) - -#undef ATOMIC_HELPER -#undef GEN_ATOMIC_HELPERS diff --git a/libtcg/src/atomic_template.h b/libtcg/src/atomic_template.h deleted file mode 100644 index 263a3f340..000000000 --- a/libtcg/src/atomic_template.h +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Atomic helper templates - * Included from tcg-runtime.c and cputlb.c. - * - * Copyright (c) 2016 Red Hat, Inc - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, see . - */ - -#if DATA_SIZE == 16 -#define SUFFIX o -#define DATA_TYPE Int128 -#define BSWAP bswap128 -#define SHIFT 4 -#elif DATA_SIZE == 8 -#define SUFFIX q -#define DATA_TYPE uint64_t -#define SDATA_TYPE int64_t -#define BSWAP bswap64 -#define SHIFT 3 -#elif DATA_SIZE == 4 -#define SUFFIX l -#define DATA_TYPE uint32_t -#define SDATA_TYPE int32_t -#define BSWAP bswap32 -#define SHIFT 2 -#elif DATA_SIZE == 2 -#define SUFFIX w -#define DATA_TYPE uint16_t -#define SDATA_TYPE int16_t -#define BSWAP bswap16 -#define SHIFT 1 -#elif DATA_SIZE == 1 -#define SUFFIX b -#define DATA_TYPE uint8_t -#define SDATA_TYPE int8_t -#define BSWAP -#define SHIFT 0 -#else -#error unsupported data size -#endif - -#if DATA_SIZE >= 4 -#define ABI_TYPE DATA_TYPE -#else -#define ABI_TYPE uint32_t -#endif - -/* Define host-endian atomic operations. Note that END is used within - the ATOMIC_NAME macro, and redefined below. */ -#if DATA_SIZE == 1 -#define END -#elif HOST_BIG_ENDIAN -#define END _be -#else -#define END _le -#endif - -ABI_TYPE ATOMIC_NAME(cmpxchg)(CPUArchState *env, target_ulong addr, ABI_TYPE cmpv, ABI_TYPE newv, MemOpIdx oi, - uintptr_t retaddr) { - abort(); -} - -#if DATA_SIZE >= 16 -#if HAVE_ATOMIC128 -ABI_TYPE ATOMIC_NAME(ld)(CPUArchState *env, target_ulong addr, MemOpIdx oi, uintptr_t retaddr) { - abort(); -} - -void ATOMIC_NAME(st)(CPUArchState *env, target_ulong addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { - abort(); -} -#endif -#else -ABI_TYPE ATOMIC_NAME(xchg)(CPUArchState *env, target_ulong addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { - abort(); -} - -#define GEN_ATOMIC_HELPER(X) \ - ABI_TYPE ATOMIC_NAME(X)(CPUArchState * env, target_ulong addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { \ - abort(); \ - } - -GEN_ATOMIC_HELPER(fetch_add) -GEN_ATOMIC_HELPER(fetch_and) -GEN_ATOMIC_HELPER(fetch_or) -GEN_ATOMIC_HELPER(fetch_xor) -GEN_ATOMIC_HELPER(add_fetch) -GEN_ATOMIC_HELPER(and_fetch) -GEN_ATOMIC_HELPER(or_fetch) -GEN_ATOMIC_HELPER(xor_fetch) - -#undef GEN_ATOMIC_HELPER - -/* - * These helpers are, as a whole, full barriers. Within the helper, - * the leading barrier is explicit and the trailing barrier is within - * cmpxchg primitive. - * - * Trace this load + RMW loop as a single RMW op. This way, regardless - * of CF_PARALLEL's value, we'll trace just a read and a write. - */ -#define GEN_ATOMIC_HELPER_FN(X, FN, XDATA_TYPE, RET) \ - ABI_TYPE ATOMIC_NAME(X)(CPUArchState * env, target_ulong addr, ABI_TYPE xval, MemOpIdx oi, uintptr_t retaddr) { \ - abort(); \ - } - -GEN_ATOMIC_HELPER_FN(fetch_smin, MIN, SDATA_TYPE, old) -GEN_ATOMIC_HELPER_FN(fetch_umin, MIN, DATA_TYPE, old) -GEN_ATOMIC_HELPER_FN(fetch_smax, MAX, SDATA_TYPE, old) -GEN_ATOMIC_HELPER_FN(fetch_umax, MAX, DATA_TYPE, old) - -GEN_ATOMIC_HELPER_FN(smin_fetch, MIN, SDATA_TYPE, new) -GEN_ATOMIC_HELPER_FN(umin_fetch, MIN, DATA_TYPE, new) -GEN_ATOMIC_HELPER_FN(smax_fetch, MAX, SDATA_TYPE, new) -GEN_ATOMIC_HELPER_FN(umax_fetch, MAX, DATA_TYPE, new) - -#undef GEN_ATOMIC_HELPER_FN -#endif /* DATA SIZE >= 16 */ - -#undef END - -#if DATA_SIZE > 1 - -/* Define reverse-host-endian atomic operations. Note that END is used - within the ATOMIC_NAME macro. */ -#if HOST_BIG_ENDIAN -#define END _le -#else -#define END _be -#endif - -ABI_TYPE ATOMIC_NAME(cmpxchg)(CPUArchState *env, target_ulong addr, ABI_TYPE cmpv, ABI_TYPE newv, MemOpIdx oi, - uintptr_t retaddr) { - abort(); -} - -#if DATA_SIZE >= 16 -#if HAVE_ATOMIC128 -ABI_TYPE ATOMIC_NAME(ld)(CPUArchState *env, target_ulong addr, MemOpIdx oi, uintptr_t retaddr) { - abort(); -} - -void ATOMIC_NAME(st)(CPUArchState *env, target_ulong addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { - abort(); -} -#endif -#else -ABI_TYPE ATOMIC_NAME(xchg)(CPUArchState *env, target_ulong addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { - abort(); -} - -#define GEN_ATOMIC_HELPER(X) \ - ABI_TYPE ATOMIC_NAME(X)(CPUArchState * env, target_ulong addr, ABI_TYPE val, MemOpIdx oi, uintptr_t retaddr) { \ - abort(); \ - } - -GEN_ATOMIC_HELPER(fetch_and) -GEN_ATOMIC_HELPER(fetch_or) -GEN_ATOMIC_HELPER(fetch_xor) -GEN_ATOMIC_HELPER(and_fetch) -GEN_ATOMIC_HELPER(or_fetch) -GEN_ATOMIC_HELPER(xor_fetch) - -#undef GEN_ATOMIC_HELPER - -/* These helpers are, as a whole, full barriers. Within the helper, - * the leading barrier is explicit and the trailing barrier is within - * cmpxchg primitive. - * - * Trace this load + RMW loop as a single RMW op. This way, regardless - * of CF_PARALLEL's value, we'll trace just a read and a write. - */ -#define GEN_ATOMIC_HELPER_FN(X, FN, XDATA_TYPE, RET) \ - ABI_TYPE ATOMIC_NAME(X)(CPUArchState * env, target_ulong addr, ABI_TYPE xval, MemOpIdx oi, uintptr_t retaddr) { \ - abort(); \ - } - -GEN_ATOMIC_HELPER_FN(fetch_smin, MIN, SDATA_TYPE, old) -GEN_ATOMIC_HELPER_FN(fetch_umin, MIN, DATA_TYPE, old) -GEN_ATOMIC_HELPER_FN(fetch_smax, MAX, SDATA_TYPE, old) -GEN_ATOMIC_HELPER_FN(fetch_umax, MAX, DATA_TYPE, old) - -GEN_ATOMIC_HELPER_FN(smin_fetch, MIN, SDATA_TYPE, new) -GEN_ATOMIC_HELPER_FN(umin_fetch, MIN, DATA_TYPE, new) -GEN_ATOMIC_HELPER_FN(smax_fetch, MAX, SDATA_TYPE, new) -GEN_ATOMIC_HELPER_FN(umax_fetch, MAX, DATA_TYPE, new) - -/* Note that for addition, we need to use a separate cmpxchg loop instead - of bswaps for the reverse-host-endian helpers. */ -#define ADD(X, Y) (X + Y) -GEN_ATOMIC_HELPER_FN(fetch_add, ADD, DATA_TYPE, old) -GEN_ATOMIC_HELPER_FN(add_fetch, ADD, DATA_TYPE, new) -#undef ADD - -#undef GEN_ATOMIC_HELPER_FN -#endif /* DATA_SIZE >= 16 */ - -#undef END -#endif /* DATA_SIZE > 1 */ - -#undef BSWAP -#undef ABI_TYPE -#undef DATA_TYPE -#undef SDATA_TYPE -#undef SUFFIX -#undef DATA_SIZE -#undef SHIFT diff --git a/libtcg/src/region.c b/libtcg/src/region.c index c72e1f21d..66cdb856e 100644 --- a/libtcg/src/region.c +++ b/libtcg/src/region.c @@ -50,7 +50,6 @@ // clang-format off #include #include -#include // clang-format on #include diff --git a/libtcg/src/tcg-llvm.cpp b/libtcg/src/tcg-llvm.cpp index 5a1375c35..2185463a7 100644 --- a/libtcg/src/tcg-llvm.cpp +++ b/libtcg/src/tcg-llvm.cpp @@ -194,9 +194,9 @@ void TCGLLVMTranslator::initializeHelpers() { abort(); } - m_qemu_ld_helpers[0] = m_module->getFunction("helper_ldb_mmu"); - m_qemu_ld_helpers[1] = m_module->getFunction("helper_ldw_mmu"); - m_qemu_ld_helpers[2] = m_module->getFunction("helper_ldl_mmu"); + m_qemu_ld_helpers[0] = m_module->getFunction("helper_ldub_mmu"); + m_qemu_ld_helpers[1] = m_module->getFunction("helper_lduw_mmu"); + m_qemu_ld_helpers[2] = m_module->getFunction("helper_ldul_mmu"); m_qemu_ld_helpers[3] = m_module->getFunction("helper_ldq_mmu"); m_qemu_ld_helpers[4] = m_module->getFunction("helper_ldq_mmu"); @@ -515,15 +515,31 @@ Value *TCGLLVMTranslator::generateQemuMemOp(bool ld, Value *value, Value *addr, assert(TCG_TARGET_REG_BITS == 64); // XXX MemOp memop = get_memop(mem_index); unsigned helper_size = memop & MO_SIZE; + if (helper_size > MO_64) { + // The i386 frontend emits no 128-bit memory operations. + abort(); + } #ifdef CONFIG_SOFTMMU #if defined(CONFIG_SYMBEX) - auto retAddr = Constant::getNullValue(intPtrType(8)); + // The argument types come from the helper's prototype in the bitcode + // library: helper_ld*_mmu(env, addr, oi, retaddr) and + // helper_st*_mmu(env, addr, val, oi, retaddr). The address is 64 bits + // wide whatever the target is, and the return address is an integer. It + // is zero because the caller is not natively generated code. + Function *helper = ld ? m_qemu_ld_helpers[helper_size] : m_qemu_st_helpers[helper_size]; + FunctionType *helperType = helper->getFunctionType(); + unsigned oiIndex = ld ? 2 : 3; + + addr = m_builder.CreateZExt(addr, helperType->getParamType(1)); + auto oi = ConstantInt::get(helperType->getParamType(oiIndex), mem_index); + auto retAddr = Constant::getNullValue(helperType->getParamType(oiIndex + 1)); if (ld) { - Value *v = attachCurrentPc( - m_builder.CreateCall(m_qemu_ld_helpers[helper_size], - {m_cpuState, addr, ConstantInt::get(intType(8 * sizeof(int)), mem_index), retAddr})); + Value *v = attachCurrentPc(m_builder.CreateCall(helper, {m_cpuState, addr, oi, retAddr})); + + // The load helpers return a zero-extended register-sized value. + v = m_builder.CreateTrunc(v, intType((1 << helper_size) * 8)); if (memop & MO_SIGN) { v = m_builder.CreateSExt(v, intType(bits)); @@ -533,14 +549,15 @@ Value *TCGLLVMTranslator::generateQemuMemOp(bool ld, Value *value, Value *addr, return v; } else { + // The store helpers take the value in the type of their third + // parameter, which is wider than the access for the small sizes. auto new_bits = (1 << helper_size) * 8; if (new_bits < bits) { value = m_builder.CreateTrunc(value, intType(new_bits)); } + value = m_builder.CreateZExt(value, helperType->getParamType(2)); - attachCurrentPc(m_builder.CreateCall( - m_qemu_st_helpers[helper_size], - {m_cpuState, addr, value, ConstantInt::get(intType(8 * sizeof(int)), mem_index), retAddr})); + attachCurrentPc(m_builder.CreateCall(helper, {m_cpuState, addr, value, oi, retAddr})); return NULL; } #endif diff --git a/libtcg/src/x86_64/tcg-target.c.inc b/libtcg/src/x86_64/tcg-target.c.inc index 72e063448..22a313bae 100644 --- a/libtcg/src/x86_64/tcg-target.c.inc +++ b/libtcg/src/x86_64/tcg-target.c.inc @@ -1717,7 +1717,7 @@ static bool tcg_out_qemu_ld_slow_path(TCGContext *s, TCGLabelQemuLdst *l) { } tcg_out_ld_helper_args(s, l, &ldst_helper_param); - tcg_out_branch(s, 1, s->qemu_ld_helpers[opc & MO_SIZE]); + tcg_out_branch(s, 1, qemu_ld_helpers[opc & MO_SIZE]); tcg_out_ld_helper_ret(s, l, false, &ldst_helper_param); tcg_out_jmp(s, l->raddr); @@ -1738,7 +1738,7 @@ static bool tcg_out_qemu_st_slow_path(TCGContext *s, TCGLabelQemuLdst *l) { } tcg_out_st_helper_args(s, l, &ldst_helper_param); - tcg_out_branch(s, 1, s->qemu_st_helpers[opc & MO_SIZE]); + tcg_out_branch(s, 1, qemu_st_helpers[opc & MO_SIZE]); tcg_out_jmp(s, l->raddr); return true; From b1b71a88913b9b9745fe57f9d8acdcb7fb212cb4 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:46:54 +0200 Subject: [PATCH 42/52] libcpu,libs2ecore: removed mem_io_vaddr The upstream softmmu passes the address of the access to notdirty_write() and cpu_check_watchpoint() directly, so nothing reads the field or its symbolic copy in the execution state anymore. Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/se_libcpu.h | 2 -- libcpu/include/cpu/state.h | 1 - libcpu/src/exec.c | 1 - libs2e/src/s2e-libcpu-interface.cpp | 1 - libs2ecore/include/s2e/S2EExecutionState.h | 14 ------------- libs2ecore/include/s2e/s2e_libcpu.h | 3 --- libs2ecore/src/S2EExecutionState.cpp | 23 ---------------------- libs2ecore/src/S2EExecutor.cpp | 4 ---- 8 files changed, 49 deletions(-) diff --git a/libcpu/include/cpu/se_libcpu.h b/libcpu/include/cpu/se_libcpu.h index 607e613f1..2c4167551 100644 --- a/libcpu/include/cpu/se_libcpu.h +++ b/libcpu/include/cpu/se_libcpu.h @@ -119,7 +119,6 @@ struct se_libcpu_interface_t { void (*read_ram_concrete)(uint64_t host_address, void *buf, uint64_t size); void (*write_ram_concrete)(uint64_t host_address, const uint8_t *buf, uint64_t size); - uint64_t (*read_mem_io_vaddr)(int masked); int (*is_port_symbolic)(uint64_t port); int (*is_mmio_symbolic)(uint64_t phys_addr, unsigned size); int (*is_vmem_symbolic)(uint64_t vaddr, unsigned size); @@ -251,7 +250,6 @@ uint64_t tcg_llvm_trace_port_access(uint64_t port, uint64_t value, unsigned bits uint64_t tcg_llvm_trace_mmio_access(uint64_t physaddr, uint64_t value, unsigned bytes, int isWrite); -void tcg_llvm_write_mem_io_vaddr(uint64_t value, int reset); uint64_t tcg_llvm_get_value(uint64_t value, bool addConstraint); #endif diff --git a/libcpu/include/cpu/state.h b/libcpu/include/cpu/state.h index c4880fdab..1d0a02b26 100644 --- a/libcpu/include/cpu/state.h +++ b/libcpu/include/cpu/state.h @@ -260,7 +260,6 @@ typedef struct CPUState { access being handled, so that the MMIO and TB invalidation code can restore the CPU state without more arguments. */ uintptr_t mem_io_pc; - target_ulong mem_io_vaddr; /* Forces the translator to put a single instruction in the next TB. Reset before code execution (S2E). */ diff --git a/libcpu/src/exec.c b/libcpu/src/exec.c index ba964816b..eb4f94ba6 100644 --- a/libcpu/src/exec.c +++ b/libcpu/src/exec.c @@ -101,7 +101,6 @@ void cpu_common_reset(CPUState *cpu) { cpu->current_tb = NULL; cpu->se_current_tb = NULL; cpu->mem_io_pc = 0; - cpu->mem_io_vaddr = 0; cpu->translate_single_instruction = 0; cpu->halted = 0; cpu->interrupt_request = 0; diff --git a/libs2e/src/s2e-libcpu-interface.cpp b/libs2e/src/s2e-libcpu-interface.cpp index bc33fb9bb..a784f53c4 100644 --- a/libs2e/src/s2e-libcpu-interface.cpp +++ b/libs2e/src/s2e-libcpu-interface.cpp @@ -76,7 +76,6 @@ void init_s2e_libcpu_interface(struct se_libcpu_interface_t *sqi) { sqi->mem.dma_write = s2e_dma_write; sqi->mem.read_ram_concrete = s2e_read_ram_concrete; sqi->mem.write_ram_concrete = s2e_write_ram_concrete; - sqi->mem.read_mem_io_vaddr = s2e_read_mem_io_vaddr; sqi->mem.is_port_symbolic = s2e_is_port_symbolic; sqi->mem.is_mmio_symbolic = s2e_is_mmio_symbolic; sqi->mem.is_vmem_symbolic = se_is_vmem_symbolic; diff --git a/libs2ecore/include/s2e/S2EExecutionState.h b/libs2ecore/include/s2e/S2EExecutionState.h index b4910e595..88e5ea59a 100644 --- a/libs2ecore/include/s2e/S2EExecutionState.h +++ b/libs2ecore/include/s2e/S2EExecutionState.h @@ -147,9 +147,6 @@ class S2EExecutionState : public klee::ExecutionState, public klee::IConcretizer S2EExecutionStateTlb m_tlb; - /* Temp location to store a symbolic mem_io_vaddr */ - klee::ref m_memIoVaddr; - /** Set when execution enters doInterrupt, reset when it exits. */ bool m_runningExceptionEmulationCode; @@ -197,7 +194,6 @@ class S2EExecutionState : public klee::ExecutionState, public klee::IConcretizer m_forkAborted = state.m_forkAborted; m_nextSymbVarId = state.m_nextSymbVarId; - m_memIoVaddr = state.m_memIoVaddr; m_runningExceptionEmulationCode = state.m_runningExceptionEmulationCode; m_saveOnContextSwitch = state.m_saveOnContextSwitch; } @@ -212,10 +208,6 @@ class S2EExecutionState : public klee::ExecutionState, public klee::IConcretizer return m_guid; } - void setMemIoVaddr(const klee::ref &e) { - m_memIoVaddr = e; - } - /// /// \brief Assign a new state id. /// @@ -288,12 +280,6 @@ class S2EExecutionState : public klee::ExecutionState, public klee::IConcretizer return m_runningConcrete; } - // XXX: Move to S2EExecutionStateMemory.cpp - uint64_t readMemIoVaddr(bool masked); - void writeMemIoVaddr(klee::ref value) { - m_memIoVaddr = value; - } - bool getReturnAddress(uint64_t *retAddr); bool bypassFunction(unsigned paramCount); diff --git a/libs2ecore/include/s2e/s2e_libcpu.h b/libs2ecore/include/s2e/s2e_libcpu.h index cdac04260..c3a97b2be 100644 --- a/libs2ecore/include/s2e/s2e_libcpu.h +++ b/libs2ecore/include/s2e/s2e_libcpu.h @@ -205,12 +205,9 @@ uint64_t tcg_llvm_trace_port_access(uint64_t port, uint64_t value, unsigned bits uint64_t tcg_llvm_trace_mmio_access(uint64_t physaddr, uint64_t value, unsigned bytes, int isWrite); -void tcg_llvm_write_mem_io_vaddr(uint64_t value, int reset); void tcg_llvm_get_value(void *addr, unsigned nbytes, bool addConstraint); #endif -uint64_t s2e_read_mem_io_vaddr(int masked); - void s2e_kill_state(const char *message); /* Register target-specific helpers with LLVM */ diff --git a/libs2ecore/src/S2EExecutionState.cpp b/libs2ecore/src/S2EExecutionState.cpp index f99d147f7..1a83a1852 100644 --- a/libs2ecore/src/S2EExecutionState.cpp +++ b/libs2ecore/src/S2EExecutionState.cpp @@ -650,29 +650,6 @@ void S2EExecutionState::addressSpaceObjectSplit(const ObjectStateConstPtr &oldOb m_tlb.updateTlb(oldObject, baseObject); } -uint64_t S2EExecutionState::readMemIoVaddr(bool masked) { - klee::ref result; - - if (!m_memIoVaddr) { - return env_cpu(env)->mem_io_vaddr; - } - - if (masked) { - result = AndExpr::create(m_memIoVaddr, - klee::ConstantExpr::create((target_ulong) TARGET_PAGE_MASK, m_memIoVaddr->getWidth())); - // This assumes that the page is already fully constrained by the MMU - result = concolics()->evaluate(result); - assert(dyn_cast(result) && "Expression must be constant here"); - } else { - result = m_memIoVaddr; - result = this->toConstant(result, "Reading mem_io_vaddr"); - } - - ConstantExpr *ce = dyn_cast(result); - assert(ce && "Expression must be constant here"); - return ce->getZExtValue(); -} - bool S2EExecutionState::getStaticTarget(uint64_t *target) { if (llvm.stack.size() == 1) { return false; diff --git a/libs2ecore/src/S2EExecutor.cpp b/libs2ecore/src/S2EExecutor.cpp index 1062da885..1ecf98f24 100644 --- a/libs2ecore/src/S2EExecutor.cpp +++ b/libs2ecore/src/S2EExecutor.cpp @@ -1842,10 +1842,6 @@ void helper_register_symbol(const char *name, void *address) { llvm::sys::DynamicLibrary::AddSymbol(name, address); } -uint64_t s2e_read_mem_io_vaddr(int masked) { - return g_s2e_state->readMemIoVaddr(masked); -} - void s2e_kill_state(const char *message) { g_s2e->getExecutor()->terminateState(g_s2e_state, message); } From 50bacb72ea0cf6b2e5000e17356340a61d6de383 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 10 Oct 2026 23:48:16 +0200 Subject: [PATCH 43/52] libcpu: added the softmmu replacement plan Co-Authored-By: Claude Opus 5.5 --- libcpu/softmmu-update.md | 705 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 705 insertions(+) create mode 100644 libcpu/softmmu-update.md diff --git a/libcpu/softmmu-update.md b/libcpu/softmmu-update.md new file mode 100644 index 000000000..2f55e801d --- /dev/null +++ b/libcpu/softmmu-update.md @@ -0,0 +1,705 @@ +# Replacing the softmmu headers with QEMU 11.1's `cputlb.c` + +The softmmu is the code that turns a guest virtual address into a host access: +the TLB, its fill and flush functions, and the load and store helpers that +generated code and C helpers call when the inline fast path does not apply. +libcpu still has the QEMU 1.0 version, spread over four template headers and +`exec-tlb.c`. This document is the plan for replacing it with upstream's +`accel/tcg/cputlb.c` at `v11.1.0`. + +`PORTING.md` schedules this inside phase 2, together with the rest of +`accel/tcg`, and defers the symbolic half to phase 6. This plan changes that +order: the softmmu is ported alone, on the current tree, with symbolic execution +kept working throughout. The reasoning is the same as for `tlb-update.md`. The +softmmu is the part of `accel/tcg` most entangled with S2E, so it is easier to +validate on a tree that still boots than in the middle of the larger import. + +**Status: implemented, not validated.** Steps 1 to 4 are in the tree and all +six targets build. No guest has been booted on it yet, so the exit criteria of +step 3 are still open. The code differs from the plan below in the following +places. Where the two disagree, the code is the reference. + +- **Memory model (deviation 1).** `cputlb.c` keeps upstream's text for the + memory API. `cpu/memory.h` defines a small `MemoryRegion` and + `MemoryRegionSection` over `MemoryDesc`, and `src/s2e/cputlb-deps.h` + implements `address_space_translate_for_iotlb()` and the + `memory_region_*()` functions on top of them. `CPUTLBEntryFull` keeps its + `section` field. This replaces the plan's `mem_desc` field and + `mem-shim.h`, and removes deviation 1. + The MMIO functions of the shim convert between the byte order that the + softmmu asks for and the little-endian values of the device interface, as + upstream's memory API does: the softmmu reads devices in big-endian order. + They also split an 8-byte access into two 4-byte ones, which is the largest + size that libs2e's device interface takes. +- **One glue header.** `src/s2e/cputlb-deps.h` holds every stub and shim. + `internal-common.h` and `backend-ldst.h` are not imported: the first + mostly declares code that is not ported, and the second reduces to an + empty `cpu_req_mo()` for an x86 guest on an x86 host. +- **`cpu->cc->tcg_ops`.** `CPUState` has a `cc` pointer to a `CPUClass` that + only contains `tcg_ops`, so upstream's expression compiles unchanged. + `CPUState` also gained `created` and `ignore_memory_transaction_failures`, + and `neg` gained `can_do_io`, for the same reason. +- **Watchpoints (hazard 5.7).** `watchpoint.c` is not imported. + `cpu_watchpoint_address_matches()` and `cpu_check_watchpoint()` are + written in `exec-bp.c` over the QEMU 1.0 watchpoint list. +- **`*_all_cpus_synced` flushes.** They are not pruned. The work queue + functions they call run the work in place. +- **Victim TLB (deviation 3).** `victim_tlb_hit()` is not edited. The + eviction is skipped, so the victim table stays empty and the function + never finds anything. The bitcode build replaces it with `false`. +- **Memory tracing (deviation 6).** `do_{ld,st}{1,2,4,8}_mmu()` are not + edited. `src/s2e/cputlb-symbex-ldst.c.inc` wraps them and redirects their + callers with macros. The wrappers no longer set `MEM_TRACE_FLAG_IO`. +- **`se_mmu_resolve()` keeps no state and writes nothing.** The plan's + scratch buffer and its write of zeros before a store are gone. When + natively executed code cannot access a RAM page directly, + `se_mmu_resolve()` sets `TLB_MMIO` in the flags of the lookup result, which + is a local copy. The upstream load and store code then calls + `do_ld_mmio_beN()` or `do_st_mmio_leN()`, with the value for a store. Each + starts with a call to `se_ram_ld_beN()` or `se_ram_st_leN()`, which does + the one real access through libs2ecore when the page is RAM. + `se_mmu_resolve()` checks both pages for a reason to switch to symbolic + execution before it decides anything else. +- **No global variables in the S2E softmmu code.** The bitcode build has no + ops table: `SE_TCG_HAS_OP()` answers for it. The memory trace wrapper + reads the TLB flags again to decide whether to report an access to + symbolic hardware. +- **Hazard 5.3.** `required_atomicity()` is not redirected. `cputlb.c` only + reaches it through `load_atom_N()` and `store_atom_N()`, which are. The + 16-byte entry points stay in the bitcode build. +- **Bitcode build.** Five `#ifndef SYMBEX_LLVM_LIB` regions remove the + native-only code, and `SE_TCG_OPS()` / `SE_TCG_OP()` select the bitcode + copies of the target hooks. +- **TB invalidation.** `tb_invalidate_phys_page_fast()` only handles stores + that stay inside 8 aligned bytes. The old softmmu only called it for + aligned accesses. The shim splits a store where it crosses a multiple + of 8. +- **`flush_tlb_cache_mmuidx()`.** libcpu clears `object_state` of the full + entries itself, in `se_tlb_drop_mmuidx()`. The libs2ecore hook only drops + the map references. +- **Step 4.** The static translator code was dead and has been removed + (`tools/include/Translator/` and every `STATIC_TRANSLATOR` conditional). + The `ld*_raw_symb` accessors in `cpu-all.h` are still there, unused. + `PORTING.md` and `tlb-update.md` have not been updated yet. + + +## 1. The softmmu today + +| File | Lines | Role | +|---|---:|---| +| `src/softmmu_template.h` | 664 | Slow path: `helper_{ld,st}*`, `slow_{ld,st}*`, `io_{read,write}*` and their `_chk` wrappers | +| `src/softmmu_header.h` | 346 | Inline accessors with their own TLB lookup: `cpu_ld*_kernel`, `_user`, `_data`, `_code` | +| `src/softmmu_exec.h` | 152 | Instantiates the header per MMU mode; defines the `ldl(p)` shorthand macros | +| `include/cpu/softmmu_defs.h` | 125 | Prototypes for all of the above | +| `src/exec-tlb.{c,h}` | 381 | `tlb_flush`, `tlb_flush_page`, `tlb_set_page`, dirty tracking in the TLB | +| `src/exec.c` (part) | ~170 | The notdirty, DMA and watchpoint `MemoryDescOps`, and `get_page_addr_code()` | + +The template is instantiated in three places: + +- `target-i386/op_helper.c`, suffix `_mmu`: the data helpers. +- `target-i386/op_helper.c`, suffix `_mmu_symb`, in the native symbex build + only. Generated code calls this copy under `CONFIG_SYMBEX_MP` + (`translate-all.c` installs it in `TCGContext::qemu_ld_helpers`). +- `exec.c`, suffix `_cmmu`: code fetches. + +The same source runs in three different ways: + +**Native, from generated code.** libtcg's backend inlines the TLB lookup and, on +a hit, loads through `se_addend`. This field points into the concrete buffer of +the KLEE object that backs the page in the current state. A page that holds +symbolic data has `TLB_SYMB` set in its comparators, so the inline compare +fails and the helper runs. The helper treats any flag bit as "IO access" and +calls `io_read`, which checks whether the bytes being read are concrete +(`_se_check_concrete`). If they are, it loads through `se_addend`. If they are +not, it calls `g_sqi.exec.switch_to_symbolic(retaddr)`, which does not return: +the instruction is executed again by KLEE. + +**Native, from a C helper.** The accessor has no return address into generated +code, so it cannot switch to symbolic mode: a helper that has already modified +the CPU state cannot be rolled back. It reads through the `ld*_raw` accessors +instead, which concretize the data (`g_sqi.mem.read_ram_concrete`). + +**As LLVM bitcode, inside KLEE.** `op_helper.c` is also compiled with +`SYMBEX_LLVM_LIB` into `op_helper.bc`. In that build the template calls +`tcg_llvm_fork_and_concretize()` on the address. With +`fork-on-symbolic-address` disabled, only the page number is made concrete and +the offset inside the page stays symbolic. The TLB lookup then runs as bitcode +on the registered TLB object, and the final access at `addr + addend` goes +through the KLEE address space, which handles symbolic data and copy-on-write. +libs2ecore replaces some of the bitcode functions with native C++ handlers +(`MMUFunctionHandlers.cpp`): `helper_{ld,st}{b,w,l,q}_mmu` and +`cpu_{ld,st}*_kernel`. These handlers make the whole address concrete. + +Three S2E flags share the comparator with QEMU's: + +| Flag | Meaning | Effect | +|---|---|---| +| `TLB_SYMB` | The page holds symbolic data | Loads and stores leave the inline path | +| `TLB_NOT_OURS` | The KLEE object backing the page is shared with another state | Stores leave the inline path so that the object is copied first | +| `TLB_MEM_TRACE` | A plugin subscribed to memory access events | Every access reaches the helper, which reports it | + +Pages that contain symbolic MMIO or DMA ranges are marked through QEMU's own +flags: `tlb_set_page()` sets `TLB_NOTDIRTY` on the read comparator and +`TLB_MMIO` on the write comparator when `g_sqi.mem.is_mmio_symbolic()` is true. + + +## 2. Target shape + +### 2.1 Files, and which library owns them + +The libraries form a chain: libutils, then libtcg, then libcpu, then +libs2ecore. A library includes headers only from the ones before it. libtcg +includes no `cpu/` header today, and this work keeps it that way. + +The rule for a new file follows from the chain. A file belongs to libtcg only +if the code generator needs it to compile. Everything that implements a +memory access, or that needs `CPUState`, belongs to libcpu. Upstream's `tcg/` +directory follows the same line: of the TLB headers, it includes only +`exec/tlb-common.h`. + +**libtcg.** One new header. The other files that the code generator shares +with the softmmu are already there and already at `v11.1.0`. + +| File | From upstream | Note | +|---|---|---| +| `include/tcg/exec/tlb-common.h` | `include/exec/tlb-common.h` | New. `CPUTLBEntry` and `CPUTLBDescFast`, which the backend reads with `offsetof()`. Carries `se_addend` (2.2). Replaces the structure half of `tcg/tlb.h`. | +| `include/tcg/tcg-memopidx.h` | `include/exec/memopidx.h` | Present, updated in step 2 (hazard 5.8) | +| `include/tcg/tcg-memop.h`, `tcg-ldst.h` | `include/exec/memop.h`, `include/tcg/tcg-ldst.h` | Present. `tcg-ldst.h` declares `helper_{ld,st}*_mmu`. | +| `include/tcg/accel/tcg-runtime.h`, `getpc.h`, `exec/helper-proto-common.h` | same names | Present. `tcg-runtime.h` declares the atomic and 128-bit helpers. | + +**libcpu.** + +| File | From upstream | Note | +|---|---|---| +| `src/accel/cputlb.c` | `accel/tcg/cputlb.c` | The deviations of section 4 | +| `src/accel/ldst_common.c.inc` | `accel/tcg/ldst_common.c.inc` | `helper_*_mmu`, `cpu_*_mmu`, `helper_{ld,st}_i128` | +| `src/accel/ldst_atomicity.c.inc` | `accel/tcg/ldst_atomicity.c.inc` | See hazard 5.3 | +| `src/accel/atomic_common.c.inc`, `atomic_template.h` | same | Moved from `libtcg/src/`, together with their two `mapping.tsv` rows, and restored to upstream's text. Compiled, but not called before the phase 3 frontend. | +| `src/accel/tlb-bounds.h`, `backend-ldst.h`, `internal-common.h` | same | `tlb-bounds.h` carries the pinned size | +| `src/accel/watchpoint.c` | `accel/tcg/watchpoint.c` | Replaces the watchpoint half of `exec-bp.c` | +| `src/s2e/cputlb-symbex.c.inc` | none, S2E file | `se_mmu_resolve()` and the libs2ecore accessors (2.4); not in `mapping.tsv` | +| `include/cpu/accel/cpu-ldst.h`, `cpu-ldst-common.h`, `cpu-ops.h`, `cpu-mmu-index.h`, `probe.h` | `include/accel/tcg/` | The public accessor API and `TCGCPUOps` | +| `include/cpu/exec/cputlb.h`, `tlb-flags.h`, `vaddr.h`, `memattrs.h`, `mmu-access-type.h`, `page-protection.h` | `include/exec/` | `tlb-flags.h` replaces the flag half of `tcg/tlb.h`. libtcg uses none of the flags. | + +Each new row goes into the `mapping.tsv` of its library with `BASELINE` = +`v11.1.0`. + +`include/exec/target_page.h` is not imported. `TARGET_PAGE_BITS` and the two +macros derived from it are already defined in `tcg/tcg.h` and in libcpu, and +`cputlb.c` uses those. + +**Removed from libtcg.** These are softmmu definitions that libtcg carries +today and that the code generator does not use: + +- `include/tcg/tlb.h`, split as described above. +- `src/atomic-helpers.c`. It instantiates the atomic templates with bodies + that call `abort()` and defines stub `helper_{ld,st}_i128()`. `cputlb.c` now + defines all of these symbols, so keeping the file would define them twice. +- `include/tcg/cpu.h`, which only defines the `PAGE_*` protection bits. + `page-protection.h` replaces it. Of its three includers, only + `libcpu/src/cpu-all.h` uses the bits. +- `CPU_TLB_BITS`, `CPU_TLB_SIZE` and `CPU_TLB_DYN_MAX_BITS` in `tcg/tcg.h`. + `tlb-bounds.h` defines the bounds, and `translate-all.c` keeps passing the + maximum to the backend through `TCGContext::tlb_dyn_max_bits`. + +**Removed from libcpu.** The four `softmmu_*.h` files, `exec-tlb.{c,h}`, and +from `exec.c` the notdirty, DMA and watch `MemoryDescOps`, +`se_notdirty_mem_{read,write}`, `se_ismemfunc` and `get_page_addr_code()`. +`exec-phys.{c,h}` loses the notdirty and watch sections. + +**Symbols that libtcg declares and libcpu defines.** The include graph has no +cycle, but generated code calls helpers whose implementation needs the TLB, +so libtcg refers to a few symbols that only libcpu can define: + +| Symbol | Referenced from libtcg by | Defined in libcpu by | +|---|---|---| +| `helper_lookup_tb_ptr` | the helper table built from `tcg-runtime.h` | `cpu-exec.c` (already the case today) | +| `helper_atomic_*`, `helper_{ld,st}_i128` | the same table | `atomic_common.c.inc` and `ldst_common.c.inc`, through `cputlb.c` | +| `helper_{ld,st}*_mmu` | `qemu_{ld,st}_helpers[]` in `tcg.c` | `ldst_common.c.inc`, through `cputlb.c` | + +This is the only upward reference, it exists today for the first row, and it +is how upstream is organized. The alternative for the third row is to keep +the S2E tables in `TCGContext`, which libcpu fills at startup. It would not +remove the first two rows, so it is not worth the backend deviation. + +Two consequences follow. libs2e links `libcpu.a` before `libtcg.a`, and the +linker resolves libtcg's references only against objects it has already +taken from `libcpu.a`. `cputlb.o` is always taken, because libs2ecore and the +rest of libcpu call `tlb_flush()`, but the link line should wrap the two +archives in `--start-group` and `--end-group` so that this does not depend on +the order. A program that uses libtcg without libcpu must define the symbols +itself. + +### 2.2 Data structures + +`CPUTLBEntry` becomes upstream's union with one S2E field. It stays 64 bytes in +symbex builds and becomes 32 bytes otherwise: + +```c +typedef union CPUTLBEntry { + struct { + uintptr_t addr_read; + uintptr_t addr_write; + uintptr_t addr_code; + uintptr_t addend; +#ifdef CONFIG_SYMBEX + /* Host address of the page in the current state's KLEE object, minus + the guest address. The backend loads it on the inline path. */ + uintptr_t se_addend; +#endif + }; + uintptr_t addr_idx[(1 << CPU_TLB_ENTRY_BITS) / sizeof(uintptr_t)]; +} CPUTLBEntry; +``` + +`CPUTLBEntryFull` is upstream's, with two changes in `state.h`: + +- `MemoryRegionSection *section` becomes `const MemoryDesc *mem_desc`, which is + NULL for MMIO (`PORTING.md` decision 3.2). +- The target-specific `extra` union holds `void *object_state`, moved out of + the fast entry. Only the slow path and libs2ecore read it. Upstream's flush + functions do not touch `fulltlb[]`, so the libs2ecore flush hooks + (deviation 5) set the field to NULL. `audit()` and `updateTlbEntry()` treat + a non-NULL value as a live reference. + +The flags are allocated as follows in `tlb-flags.h`: + +| Flag | Where | Bit | Set by | +|---|---|---:|---| +| `TLB_SYMB` | comparator, in `TLB_FLAGS_MASK` | 9 | libs2ecore, on all three comparators | +| `TLB_NOT_OURS` | comparator, in `TLB_FLAGS_MASK` | 10 | libs2ecore, on `addr_write` | +| `TLB_MEM_TRACE` | comparator, in `TLB_FLAGS_MASK` | 11 | `tlb_set_page_full()`, on `addr_read` and `addr_write` | +| `TLB_SYMB_MMIO` | `slow_flags[]`, in `TLB_SLOW_FLAGS_MASK` | 5 | `tlb_set_page_full()`, on loads and stores (section 7) | + +`slow_flags[]` cannot hold the first three. `mmu_lookup1()` and +`probe_access_internal()` merge the comparator flags and the slow flags into +one `int`, where bit 6 is `TLB_INVALID_MASK`, bit 7 is `TLB_NOTDIRTY` and bit 8 +is `TLB_FORCE_SLOW`. Only bit 5 is free in that merged value. Bits 9 to 11 are +free in the comparator because `TARGET_PAGE_BITS` is 12 on x86; add a +build-time assertion that `TLB_FLAGS_MASK` stays below `TARGET_PAGE_SIZE`. + +Keeping the three dynamic flags in the comparator has two advantages. +libs2ecore sets and clears one bit, as it does today, and has no +`TLB_FORCE_SLOW` bit to keep consistent. `tlb_set_compare()`, `mmu_lookup1()` +and `probe_access_internal()` already propagate every bit of `TLB_FLAGS_MASK`, +so they need no edit. Any nonzero bit below the page mask makes the backend's +inline compare fail, so no backend change is needed either. + +`TLB_SYMB_MMIO` is set once, when the entry is filled. `tlb_set_compare()` +adds `TLB_FORCE_SLOW` for it like for any other slow flag. + +`CPUTLB` in `state.h` becomes upstream's (`CPUTLBCommon c`, `d[]`, `f[]`), with +the storage for `f[i].table` and `d[i].fulltlb` allocated statically inside +`CPUNegativeOffsetState`. The bitcode softmmu reads both arrays, so both must +lie inside the KLEE object that libs2ecore registers once over `neg`. This is +the pinned-size option of `tlb-update.md` section 5. The victim TLB is disabled +(`PORTING.md` 9.4). + +`NB_MMU_MODES` stays 2 and `cpu_mmu_index()` keeps its two values until the +phase 3 frontend arrives. `cputlb.c` does not depend on the number. + +### 2.3 Entry points + +| Caller | Today | After | +|---|---|---| +| Generated code | `tcg_helper_ld{b,w,l,q}_mmu[_symb]`, `helper_st*_mmu[_symb]`, taken from `TCGContext::qemu_{ld,st}_helpers` | `helper_ld{ub,uw,ul,q,sb,sw,sl}_mmu`, `helper_st{b,w,l,q}_mmu`, called directly by the backend as upstream does | +| C helpers | `cpu_ld*_{kernel,user,data}`, `ldl(p)` macros | `cpu_ld*_mmuidx_ra()` and `cpu_ld*_data_ra()`, inline wrappers around `cpu_{ld,st}{b,w,l,q}_mmu()` | +| Translator | `cpu_ld*_code` | `cpu_ld{b,w,l,q}_code_mmu()` | +| Code generated by `tcg-llvm.cpp` | `helper_ld{b,w,l,q}_mmu(env, addr, mmu_idx, retaddr)` | `helper_ld*_mmu(env, addr, oi, retaddr)`; loads return `tcg_target_ulong` and must be truncated | + +The arguments change from `(env, addr, mmu_idx, retaddr)` to +`(env, addr, oi, retaddr)`, where `oi` (a `MemOpIdx`) packs the access size, +alignment and MMU index. libtcg already passes `oi`; the old helpers only work +because they extract the MMU index from it (hazard 5.8). The S2E override tables in `TCGContext` +and `translate-all.c` are deleted, and `tcg_out_qemu_{ld,st}_slow_path()` in +the backend returns to upstream's text. + +`op_helper.c` and the old `translate.c` are replaced in phase 3, so their ~250 +call sites are not edited. A compatibility header, `src/softmmu-compat.h`, maps +the old names onto the new API: + +```c +#define cpu_ldl_kernel(env, p) cpu_ldl_mmuidx_ra(env, p, 0 /* kernel mode */, 0) +#define ldl(p) cpu_ldl_data_ra(env, p, 0) +#define cpu_ldub_code(env, p) cpu_ldb_code_mmu(env, p, make_memop_idx(MO_UB, cpu_mmu_index(env)), 0) +``` + +A return address of 0 matches the `NULL` that the old inline accessors pass. +The header is deleted with `op_helper.c`. + +### 2.4 Native and bitcode builds of the same file + +`cputlb.c` is compiled twice, as `op_helper.c` is today: natively into +`libcpu.a`, and with `-DSYMBEX_LLVM_LIB` into bitcode that is linked into +`op_helper.bc`. Symbolic addresses keep working because the lookup and the +final access run as bitcode. + +The bitcode build keeps the access path and turns everything else into calls to +the native copy: + +| Runs as bitcode | Stays native, called from bitcode | +|---|---| +| `helper_{ld,st}*_mmu`, `cpu_{ld,st}*_mmu`, `cpu_ld*_code_mmu` | `tlb_set_page*()`, reached through `cpu_x86_handle_mmu_fault()` | +| `do_ld{1,2,4,8}_mmu`, `do_st{1,2,4,8}_mmu` | `notdirty_write()` | +| `mmu_lookup()`, `mmu_lookup1()`, `mmu_watch_or_dirty()` | `do_ld_mmio_beN()`, `do_st_mmio_leN()` | +| `do_ld_{1,2,4,8}`, `do_st_{1,2,4,8}`, the `beN` / `leN` cross-page loops | `cpu_check_watchpoint()` | +| `tlb_fill_align()` and the x86 `TCGCPUOps` hooks | all flush functions, `probe_access*()` | + +`tlb_fill_align()` and `x86_cpu_tlb_fill()` run as bitcode because the fault +address can have a symbolic offset. The old `tlb_fill()` handles this by +passing the concrete page address to `cpu_x86_handle_mmu_fault()` and then +writing the full address to CR2 (or to the VMCB) and to the `on_page_fault` +event. `x86_cpu_tlb_fill()` does the same: it masks the address before the +native call and restores the full fault address afterwards. A native hook +would either receive only the page address, and report a page-aligned CR2, or +receive the symbolic address, and fork on its value (hazard 5.4). + +The native-only functions are `static` upstream. A macro, `SE_NATIVE`, replaces +`static` on the definitions of `notdirty_write()`, `do_ld_mmio_beN()` and +`do_st_mmio_leN()`. It expands to `static` when `CONFIG_SYMBEX` is off and to +nothing in symbex builds, which exports the function. Their bodies sit inside +`#ifndef SYMBEX_LLVM_LIB`, so the bitcode build sees only the prototypes. +libs2ecore lists these functions with `__DEFINE_EXT_FUNCTION`, as it lists +`io_readb_mmu` and `se_notdirty_mem_write` today. The flush functions, +`tlb_set_page*()` and `probe_access*()` are already public; the bitcode build +leaves their bodies out the same way. + +The S2E cases are resolved in one place, so that `do_ld_*` and `do_st_*` keep +upstream's text. `mmu_lookup()` calls `se_mmu_resolve()` for each page after +`mmu_watch_or_dirty()`, when the page carries one of the S2E flags or +`TLB_MMIO`. The function lives in an S2E file, `src/s2e/cputlb-symbex.c.inc`, +which `cputlb.c` includes after `ldst_atomicity.c.inc` (hazard 5.3). When it +returns, each page is either accessed directly at `haddr` or routed to the +MMIO functions, which do the access through libs2ecore. A watchpoint hit or a fault leaves `mmu_lookup()` +before `se_mmu_resolve()` runs, so the function never acts on an access that +does not happen. + +How each case is handled in the two builds: + +| Case | Native build | Bitcode build | +|---|---|---| +| Address | Always concrete | `mmu_lookup()` calls `tcg_llvm_before_memory_access()`, then `tcg_llvm_fork_and_concretize()` on the address when `fork-on-symbolic-address` is set. `tlb_index()` concretizes the page number and computes the index from the result (hazard 5.5). | +| Host address | `mmu_lookup1()` computes `addr + se_addend` under `CONFIG_SYMBEX_MP`, else `addr + addend` | `addr + addend`; the access resolves through the KLEE address space | +| `TLB_SYMB`, loads | `se_mmu_resolve()` checks the accessed bytes with `_se_check_concrete()`. If they are symbolic and `ra` is in generated code, it calls `switch_to_symbolic(ra)`. Otherwise it routes the load to `do_ld_mmio_beN()`, which reads the concretized bytes with `g_sqi.mem.read_ram_concrete()`. | Ignored | +| `TLB_SYMB` or `TLB_NOT_OURS`, stores | If the object is shared or the accessed bytes are symbolic, `se_mmu_resolve()` routes the store to `do_st_mmio_leN()`, which writes the value with `g_sqi.mem.write_ram_concrete()`. This copies the object, makes the bytes concrete and updates the TLB entry. | Ignored; KLEE copies the object | +| `TLB_MEM_TRACE` | `g_sqi.events.after_memory_access()` in `do_{ld,st}{1,2,4,8}_mmu`, except for code fetches | `tcg_llvm_after_memory_access()` at the same sites | +| `TLB_NOTDIRTY` (stores) | `notdirty_write()` | Calls the native `notdirty_write()`, then stores | +| `TLB_MMIO` and `TLB_SYMB_MMIO` | `se_mmu_resolve()` calls `switch_to_symbolic(ra)` if `g_sqi.mem.is_mmio_symbolic()` is true and `ra` is in generated code, as `io_read` does today. Otherwise `do_{ld,st}_mmio_*()` dispatch through `MemoryDescOps` for `TLB_MMIO`, and a `TLB_SYMB_MMIO` page is accessed as RAM. | `TLB_MMIO` calls the native function. Both flags then call `tcg_llvm_trace_mmio_access()` next to the memory trace call. | +| TLB miss | `tlb_fill_align()` | `tlb_fill_align()` as bitcode, calling the bitcode `x86_cpu_tlb_fill()` by name | + +The S2E code works with three addresses, and they must not be mixed up. +`haddr` is based on `se_addend` and is only valid for a direct access. +`g_sqi.mem.read_ram_concrete()` and `write_ram_concrete()` take the host RAM +address, `addr + entry->addend`, which is the address KLEE binds the object +at. `g_sqi.mem.is_mmio_symbolic()` takes the guest physical address, +`full->phys_addr` plus the page offset. The old `io_read` passes it the +virtual address. + +The native handlers in `MMUFunctionHandlers.cpp` stay for the +`helper_{ld,st}*_mmu` entry points, which is where code translated by +`tcg-llvm.cpp` enters. They are rewritten against the new TLB layout and the +new arguments. The `cpu_{ld,st}*_kernel` handlers are removed: upstream has no +per-mode accessor functions, so kernel-mode accesses from helpers run through +the bitcode `cpu_*_mmu` functions like all others. + + +## 3. What `cputlb.c` needs from code that is not ported yet + +| Dependency | Upstream provider | Bridge | +|---|---|---| +| `cpu->cc->tcg_ops->{tlb_fill, mmu_index, pointer_wrap, do_unaligned_access}` | `target/i386/tcg/tcg-cpu.c` | `cpu->tcg_ops` (already in `state.h`). The four hooks are written in `target-i386/op_helper.c`, which is compiled both natively and as bitcode (2.4), over the old `cpu_x86_handle_mmu_fault()` and `raise_exception_err_ra()`. The old `tlb_fill()`, including its `on_tlb_miss` and `on_page_fault` events and its CR2 handling, becomes `x86_cpu_tlb_fill()`. | +| `MemoryRegionSection`, `address_space_translate_for_iotlb()`, `memory_region_dispatch_{read,write}()` | `system/memory.c` | `src/s2e/mem-shim.h` over `mem_desc_find()` and `MemoryDescOps` (`PORTING.md` 3.2). About eight sites in `cputlb.c`. | +| `physical_memory_is_clean()`, `_get_dirty_flag()`, `_set_dirty_range()`, `_test_and_clear_dirty()`, `qemu_ram_addr_from_host_nofail()` | `system/physmem.c` | Same shim, over the byte-per-page mask of `exec-ram.h`. `_test_and_clear_dirty()` must call `tlb_reset_dirty()` with the host address range, as upstream's does. `tlb_protect_code()` relies on that call to set `TLB_NOTDIRTY` on the entries that map the page. | +| `tb_invalidate_phys_range_fast()` | `tb-maint.c` | Wrapper around the old `tb_invalidate_phys_page_fast()` in `exec-tb.c` | +| `tb_jmp_cache_clear_page()` uses `CPUJumpCache` | `tb-jmp-cache.h` | Temporary deviation: call the old `tlb_flush_jmp_cache()` over `neg.tb_jmp_cache[]`. Removed when `cpu-exec.c` is imported. | +| `tcg_flush_jmp_cache()`, called by the full and range flushes | `translate-all.c` | Stub header: clear `neg.tb_jmp_cache[]`, as the old `tlb_flush()` does | +| `cpu_in_serial_context()` in `ldst_atomicity.c.inc` | `internal-common.h` | Stub header: always true. There is one vCPU, so `required_atomicity()` never asks for more than byte atomicity. | +| `get_page_addr_code_hostp()` returns -1 for MMIO | `cputlb.c` itself | The two old callers (`cpu-exec.c`, `exec-tb.c`) call `cpu_abort()` on -1, as `get_page_addr_code()` does today. Deviation 10 keeps a RAM page that carries S2E flags from being reported as MMIO. | +| `cpu_watchpoint_address_matches()`, `cpu_check_watchpoint()` | `accel/tcg/watchpoint.c` | Imported in this work. The breakpoint half of `exec-bp.c` stays. | +| `bql_lock()`, `cpu_io_recompile()`, `can_do_io`, plugin memory callbacks, trace points, `assert_cpu_is_self()` | various | Stub headers: no-ops, with `can_do_io` always true | +| `async_safe_run_on_cpu()` in the `*_all_cpus_synced` flushes | `cpu-common.c` | Pruned; there is one vCPU and x86 does not call them | + + +## 4. S2E deviations in the imported files + +Each one gets a comment that states why, so that the next merge can keep it. + +1. **Memory model.** `tlb_set_page_full()`, `io_prepare()`, `io_failed()`, + `int_ld_mmio_beN()` and `int_st_mmio_leN()` use `MemoryDesc`. +2. **Pinned size.** `tlb_mmu_init()` points `fast->table` and `desc->fulltlb` + at the static storage in `neg`. `tlb-bounds.h` sets the minimum, default + and maximum sizes equal, so `tlb_mmu_resize_locked()` always returns on its + existing `new_size == old_size` branch. `tlb_destroy()` frees nothing. +3. **No victim TLB.** `victim_tlb_hit()` returns false, and + `tlb_set_page_full()` skips the eviction. +4. **`se_addend`.** `mmu_lookup1()` computes `haddr` from it in native + `CONFIG_SYMBEX_MP` builds. `tlb_set_page_full()` builds the new entry in a + local variable and copies it over the live one, so it must set + `tn.se_addend` to 0. +5. **libs2ecore hooks.** Four sites, each placed where upstream has the MMU + index and the entry index at hand: + - `tlb_set_page_full()`, before `desc->fulltlb[index] = *full`: + `flush_tlb_cache_page(old object_state, mmu_idx, index)`. The hook must + run before the overwrite, because `updateTlbEntry()` finds the reference + to drop from `m_tlbMap` through the old `object_state`. Today the field + survives a refill, and upstream overwrites both the fast entry and the + full entry. + - `tlb_set_page_full()`, after the new entry is copied in: + `update_tlb_entry()` for RAM pages. + - `tlb_flush_one_mmuidx_locked()`: a new hook, + `flush_tlb_cache_mmuidx(mmu_idx)`, which drops the references of that + index and sets their `object_state` to NULL. The existing + `flush_tlb_cache()` clears the whole map and cannot be used here. + Upstream tracks large pages per MMU index, and `tlb_flush_page_locked()` + flushes a single index when the page lies in that index's large-page + region. Clearing the whole map at that point would leave the other + index with live entries that `updateTlb()` no longer finds, and their + `se_addend` would go stale at the next copy-on-write. + - `tlb_flush_page_locked()` and `tlb_flush_range_locked()`, before each + call to `tlb_flush_entry_locked()` that hits: + `flush_tlb_cache_page()`. `tlb_flush_entry_mask_locked()` itself only + receives the entry pointer. + + The `g_se_disable_tlb_flush` guard goes at the top of the three functions + that every public flush reaches: `tlb_flush_by_mmuidx_async_work()`, + `tlb_flush_page_by_mmuidx_async_0()` and + `tlb_flush_range_by_mmuidx_async_0()`. +6. **`se_mmu_resolve()`** called from `mmu_lookup()`, and the memory trace + calls in `do_{ld,st}{1,2,4,8}_mmu`, per the table in 2.4. `do_ld_*` and + `do_st_*` are not edited. +7. **`TLB_MEM_TRACE` and `TLB_SYMB_MMIO` at fill time.** `tlb_set_page_full()` + adds the first to `read_flags` and `write_flags` when a memory access + signal has subscribers, as `tlb_set_page()` does today, and the second + when `g_sqi.mem.is_mmio_symbolic()` is true for the page. Both are added + after the `MMU_INST_FETCH` comparator is set. +8. **Bitcode build.** `SE_NATIVE` (2.4), the entry code in `mmu_lookup()`, + the concretization in `tlb_index()` (hazard 5.5), and the three hook calls + by name (hazard 5.4). +9. **Jump cache**, temporary (section 3). +10. **Code fetches ignore the S2E flags.** In `probe_access_internal()`, the + S2E flags are masked out when `access_type` is `MMU_INST_FETCH`. + libs2ecore sets `TLB_SYMB` on `addr_code` so that `cpu_ld*_code_mmu()` + concretizes symbolic code bytes instead of reading stale ones through + `se_addend`. Without the mask, `probe_access_internal()` would report + the page as MMIO, `get_page_addr_code_hostp()` would return -1, and the + callers would abort on any code page that holds symbolic data. The old + `get_page_addr_code()` ignores the flags in the same way. + +For data accesses, `probe_access_internal()` needs no deviation. It reports +any flag it does not know as `TLB_MMIO` with a NULL host pointer, so a caller +that probes a page carrying `TLB_SYMB` or `TLB_NOT_OURS` falls back to the +`cpu_*_mmu` functions and never receives a host pointer that bypasses the +checks. The old helpers do not probe; this matters for the phase 3 helpers. + + +## 5. Hazards + +**5.1 Codegen and C must agree on the entry layout.** The backend hard-codes +`offsetof(CPUTLBEntry, addr_read)`, `addr_write`, `se_addend` and +`CPU_TLB_ENTRY_BITS`. `tlb-common.h` is the single definition for both +components. A build-time assertion on `sizeof(CPUTLBEntry)` exists upstream; add +one on `offsetof(CPUTLBEntry, se_addend)`. + +**5.2 The `f[]` index convention.** Upstream's `cpu_tlb_fast()` inverts the +index (`NB_MMU_MODES - 1 - mmu_idx`); libtcg's `tlb_mask_table_ofs()` and +`state.h` do not. `cputlb.c` reaches `f[]` only through `cpu_tlb_fast()`, which +lives in the hand-written `state.h`, so the non-inverted convention stays and +costs no deviation. Check after the import that no `&tlb->f[i]` remains outside +the init and flush loops, where the order does not matter. + +**5.3 `ldst_atomicity.c.inc` cannot be used as is in symbex builds.** Three +problems, two of them in the bitcode build and one in the native build: + +- The file reaches inline assembly (`vmovdqa`) through the x86-64 host header + `atomic128-ldst.h`, and KLEE cannot execute inline assembly. +- `load_atom_N()` and `required_atomicity()` branch on the alignment of the + host pointer. KLEE forks on that branch when the in-page offset is + symbolic, although both sides compute the same value. +- An unaligned `load_atom_{2,4,8}()` reads the 16 aligned bytes around the + address and relies on the host page offset of the pointer to stay inside + the page. In native `CONFIG_SYMBEX_MP` builds `haddr` points into a KLEE + concrete buffer, which is a 4096-byte heap block with no page alignment, + so the load can read up to 8 bytes past its end. + +In every `CONFIG_SYMBEX` build, native and bitcode, `cputlb-symbex.c.inc` +therefore redirects `load_atom_N()` and `store_atom_N()` to plain +`ldN_he_p()` / `stN_he_p()` and `required_atomicity()` to `MO_8`, with +`#define`s placed after the `#include "ldst_atomicity.c.inc"` line. The +imported file is not edited, and its own functions become unused statics. +Atomicity adds nothing in these builds: there is one vCPU, and KLEE runs one +state at a time. The plain build keeps upstream's behavior. The 16-byte entry +points (`helper_ld16_mmu`, `cpu_ld16_mmu`) are left out of the bitcode build +until the phase 3 frontend emits 128-bit accesses. + +**5.4 Calls through `tcg_ops` from bitcode reach the native hooks.** +`cpu->tcg_ops` holds native function pointers. KLEE can call them: it +registers the target address as an external function. A native call forks +once per possible value of each symbolic argument, though, and three hooks +receive the access address: `tlb_fill()` in `tlb_fill_align()`, +`pointer_wrap()` in `mmu_lookup()` and `do_unaligned_access()` in +`cpu_unaligned_access()`. In the bitcode build these three sites call the x86 +functions by name, which selects their bitcode copies in `op_helper.bc`. + +**5.5 The lookup must not index the TLB with a symbolic value.** If the index +depends on the symbolic address, KLEE treats the table access as a symbolic +pointer into the TLB object. `mmu_lookup1()` computes the index for both pages +of an access, and `mmu_lookup()` computes it again after a possible resize. +All of these go through `tlb_index()`, so the bitcode build concretizes the +page number there, in one place, and `tlb_entry()` inherits it. + +**5.6 Return address conventions.** `se_mmu_resolve()` decides between +`switch_to_symbolic()` and concretization with `tcg_is_dyngen_addr(ra)`. The +compatibility macros pass 0, which selects concretization, as today. The +`helper_*_mmu` functions receive the address from the backend's slow path. +Check that the value still satisfies `tcg_is_dyngen_addr()` once the backend +calls the helpers directly. The phase 3 helpers pass `GETPC()`, which is an +address in generated code, so the test will then select +`switch_to_symbolic()` for helpers too. Phase 3 has to decide whether its +helpers can be restarted at that point, or pass the distinction another way. + +**5.7 Watchpoints change mechanism.** The old code routes watched pages +through an IO section (`phys_section_watch`) and `mem_io_vaddr`. Upstream sets +`TLB_WATCHPOINT` and calls `cpu_check_watchpoint()` with the address. +`watchpoint.c` reaches `tb-maint.c` and `cpu-exec.c` functions +(`tb_check_watchpoint()`, `cpu_loop_exit_restore()`, `cflags_next_tb`) that +have old equivalents with different shapes. This is the least-scoped item of +the plan; size it before starting step 3. + +**5.8 `MemOpIdx` width.** libtcg's `tcg/tcg-memopidx.h` keeps the MMU index in +the low 4 bits of `oi`; upstream's `include/exec/memopidx.h` uses 5 since +v10.2.0. libtcg's `mapping.tsv` lists the header as tracking upstream's, but +the file still has its 8.1.2 content. Step 2 brings it to `v11.1.0`. The +backend and `cputlb.c` must use one definition, so `cputlb.c` includes +libtcg's header and upstream's is not imported into libcpu a second time. + +**5.9 `TLB_NOTDIRTY` stays set while an S2E flag is set.** Upstream's +`tlb_set_dirty1_locked()` clears the flag only when the write comparator +equals `addr | TLB_NOTDIRTY` exactly. The old `tlb_set_dirty1()` masks +`TLB_SYMB` out of that comparison. With upstream's text, a page that carries +`TLB_SYMB`, `TLB_NOT_OURS` or `TLB_MEM_TRACE` keeps `TLB_NOTDIRTY`, and every +store to it calls `notdirty_write()` again. The result is correct, and these +stores already take the slow path, so this is left without a deviation. +`notdirty_write()` tries again on each store and succeeds once the S2E flags +are gone. + + +## 6. Steps + +Each step ends with all six targets building. Steps 1 and 2 change no +behavior. + +### Step 1: Tooling + +Create `libcpu/scripts/upgrade/{BASELINE,mapping.tsv}` with an +`# upstream-dirs:` header (`PORTING.md` phase 0). Check that +`normalize.sh` emits `accel/tcg/cputlb.c` into `src/accel/cputlb.c`. + +### Step 2: Preparation, with the old softmmu still in place + +- Update libtcg's `tcg/tcg-memopidx.h` to upstream's `v11.1.0` text, as its own + commit (hazard 5.8). Three sites extract the MMU index with a hard-coded + `& 0xf` and must call `get_mmuidx()` first: two in `softmmu_template.h` and + one in `MMUFunctionHandlers.cpp`. All other users go through the accessors. + The header keeps two deviations: the `(MemOp)` cast in `get_memop()`, which + `tcg-llvm.cpp` needs to compile the header as C++, and the include of + `tcg-memop.h` in place of `exec/memop.h`. The assertions under + `CONFIG_DEBUG_TCG` use `clz32()`, so `host-utils.h` must be visible there. +- Write `src/s2e/mem-shim.h` and its dirty-tracking half. +- Add the stub headers and import the plain headers of 2.1 that do not conflict + with existing definitions (`cpu-ops.h`, `vaddr.h`, `memattrs.h`, + `mmu-access-type.h`, `page-protection.h`). `page-protection.h` replaces + libtcg's `tcg/cpu.h`, which is deleted here. +- Write the four `TCGCPUOps` hooks in `op_helper.c` and set `cpu->tcg_ops`. + Nothing calls them yet. +- Add `softmmu-compat.h`, initially mapping the old names onto themselves, and + include it where `softmmu_exec.h` is included. This fixes the include graph + before the switch. +- Split the watchpoint code out of `exec-bp.c` so that step 3 replaces one + file. + +**Exit:** the tree builds and boots unchanged. + +### Step 3: The switch + +The TLB layout is shared by `cputlb.c`, libtcg's backend and libs2ecore, so +this lands as one change. Bring the targets up in this order on the branch: + +1. **`{i386,x86_64}-softmmu`.** Import the files of 2.1 with deviations 1, 2, 3 + and 9. Replace `CPUTLB`, `CPUTLBDesc` and `CPUTLBEntry`. Apply the libtcg + removals of 2.1 in the same change: split `tcg/tlb.h`, drop the TLB size + macros from `tcg/tcg.h`, delete `atomic-helpers.c` and move the two atomic + template rows to libcpu's `mapping.tsv`. The atomic files cannot move + earlier, because the upstream template bodies call `atomic_mmu_lookup()`, + which `cputlb.c` defines. Delete the helper override tables, restore the + backend slow path, and put `libcpu.a` and `libtcg.a` in one linker group. + Point the compatibility header at the new API. Convert the + `tlb_flush(env, 1)` and `tlb_flush_page(env, addr)` callers to the + `CPUState *` signatures, and the one `tlb_set_page()` caller. Delete the + old files. +2. **`-s2e_sp-softmmu`** (single path). Add deviations 5, 7 and 10 with the + new `flush_tlb_cache_mmuidx()` hook, the redirections of hazard 5.3, the + memory trace calls of deviation 6, the bitcode build of `cputlb.c` with + deviation 8, and the `tcg-llvm.cpp` change. Rewrite + `MMUFunctionHandlers.cpp`. Update the `__DEFINE_EXT_FUNCTION` list. +3. **`-s2e-softmmu`.** Add deviation 4 and `se_mmu_resolve()`. Port + `S2EExecutionStateTlb` to the new layout: `object_state` in + `CPUTLBEntryFull` and the flags at their new comparator bits. The `CPU_TLB_SIZE` sites that index the + main TLB switch to `tlb_index()`-style mask reads; the `se_ram_tlb` sites + keep their own constant. + +**Exit:** a guest boots on all six targets. With the TLB audit enabled +(`ba81a679`), a symbolic run reports no inconsistency. The testsuite passes, +including these cases: + +- a symbolic in-page offset with `fork-on-symbolic-address` disabled; +- code executed from a page that also holds symbolic data (deviation 10); +- a page fault taken in KLEE at an address that is not page-aligned, checking + the CR2 value that the guest reads (2.4); +- a guest that maps the same region with a large page and flushes one page of + it while other entries are live (deviation 5). + +### Step 4: Cleanup + +- Delete `mem_io_vaddr`, `S2EExecutionState::setMemIoVaddr()`, + `g_sqi.mem.read_mem_io_vaddr` and `tcg_llvm_write_mem_io_vaddr`. Upstream + passes the address to `notdirty_write()` and `cpu_check_watchpoint()` + directly. +- Delete `se_tlb_current`. `do_ld_*` and `do_st_*` receive the + `CPUTLBEntryFull` they need. +- Delete the `ld*_raw_symb` accessors and the `_kernel_symb` instantiation. +- Update `PORTING.md` (phases 1, 2, 6, and section 9.6, which still describes + editing `softmmu_header.h`) and `tlb-update.md` section 6. + + +## 7. Symbolic MMIO pages get their own flag + +Today RAM pages that contain symbolic MMIO or DMA ranges are marked by reusing +`TLB_NOTDIRTY` on reads and `TLB_MMIO` on writes. Upstream gives +`TLB_NOTDIRTY` a write-only meaning and reads `TLB_MMIO` as "no host memory", +so the reuse does not carry over. + +These pages are marked with `TLB_SYMB_MMIO`, the one slow flag bit that +upstream leaves free (2.2). The flag is known when the entry is filled and +never changes afterwards, so `tlb_set_compare()` handles it without help from +libs2ecore. + +Reusing `TLB_SYMB` for these pages was considered and rejected. The bitcode +build ignores `TLB_SYMB`, so it would stop calling +`tcg_llvm_trace_mmio_access()` for them, and libs2ecore clears `TLB_SYMB` +whenever the page becomes fully concrete. + + +## 8. What this leaves alone + +- The rest of `accel/tcg`: `cpu-exec.c`, `tb-maint.c`, `translate-all.c`, + `translator.c`. The TB hash, the jump cache structure and `precise-pc.c` do + not change. +- The i386 frontend and helpers, `NB_MMU_MODES`, and the MMU index values. +- The RAM TLB (`se_ram_tlb`) and `S2EExecutionStateTlb`'s ownership model. +- Dynamic TLB sizing and the victim TLB. Both need the TLB to move or reorder + entries under libs2ecore, which the bitcode softmmu and `m_tlbMap` do not + support (`tlb-update.md` section 5, `PORTING.md` 9.4). +- The atomic helpers (`cpu_atomic_*_mmu`). They are compiled natively but have + no caller and no symbolic path until phases 3 and 6. `atomic_mmu_lookup()` + returns a host pointer, so it will need the same treatment as + `probe_access()` when a caller appears. From c291f5842cc18bf213b48e77f562bf3a4d8453e2 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 17 Oct 2026 23:45:01 +0200 Subject: [PATCH 44/52] libtcg: optimize the llvm code of translation blocks KLEE interprets every instruction of a translation block, but the blocks were not optimized. Run sroa, early-cse, instsimplify, simplifycfg and adce on each block. On coreutils-echo, this removes 22% of the instructions of the blocks and every alloca. The pipeline keeps the shape of the code that S2E depends on: simplifycfg does not speculate or simplify conditional branches, which create selects and freeze instructions, instcombine is not used because it creates intrinsics that KLEE does not lower in translation blocks, and there is no dead store elimination. splitCommonReturn() undoes the merging of the returns, which GetStaticBranchTarget() needs. The translator also removes the memory effects that the compiler inferred for the helpers, such as memory(none) on helper_lzcnt(). KLEE can fork inside a helper, and early-cse could otherwise remove a store to the CPU state that a later store overwrites after the call. Co-Authored-By: Claude Opus 5.5 --- libtcg/include/tcg/tcg-llvm.h | 17 +++++ libtcg/src/tcg-llvm.cpp | 132 +++++++++++++++++++++++++++++++++- 2 files changed, 147 insertions(+), 2 deletions(-) diff --git a/libtcg/include/tcg/tcg-llvm.h b/libtcg/include/tcg/tcg-llvm.h index 48be81846..ca0dd9ad2 100644 --- a/libtcg/include/tcg/tcg-llvm.h +++ b/libtcg/include/tcg/tcg-llvm.h @@ -68,7 +68,9 @@ void *tcg_llvm_gen_code(void *llvmTranslator, struct TCGContext *s, struct Trans #include #include #include +#include #include +#include #include #include #include @@ -87,6 +89,19 @@ class TCGLLVMTranslator { llvm::IRBuilder<> m_builder; + /* + * Pipeline that optimizes each translation block (see optimizeTbFunction()). + * The analysis managers reference each other and must be destroyed in the + * reverse order of these declarations. The analyses that they create on + * demand reference the pass builder, which must outlive them. + */ + llvm::PassBuilder m_passBuilder; + llvm::LoopAnalysisManager m_lam; + llvm::FunctionAnalysisManager m_fam; + llvm::CGSCCAnalysisManager m_cgam; + llvm::ModuleAnalysisManager m_mam; + llvm::FunctionPassManager m_fpm; + #ifdef CONFIG_SYMBEX /* Declaration of a wrapper function for helpers */ llvm::Function *m_helperForkAndConcretize; @@ -233,6 +248,8 @@ class TCGLLVMTranslator { llvm::Function *createTbFunction(const std::string &name); llvm::Function *generateCode(TCGContext *s, TranslationBlock *tb); void removeInterruptExit(); + void optimizeTbFunction(); + void splitCommonReturn(); static bool GetStaticBranchTarget(const llvm::BasicBlock *bb, uint64_t *target); }; diff --git a/libtcg/src/tcg-llvm.cpp b/libtcg/src/tcg-llvm.cpp index 2185463a7..58e412461 100644 --- a/libtcg/src/tcg-llvm.cpp +++ b/libtcg/src/tcg-llvm.cpp @@ -51,8 +51,15 @@ extern "C" { #include #include #include +#include +#include #include +#include +#include +#include #include +#include +#include #include #include @@ -85,6 +92,22 @@ using namespace llvm; uint64_t TCGLLVMTranslator::m_eip_byte_offset = 0; +/* + * Removes the memory effects that the compiler inferred for the functions of + * the helper library, such as memory(none) on helper_lzcnt(). Without them, + * the optimizer of the translation blocks treats every helper call as a + * possible read and write of the CPU state. KLEE can fork inside a helper that + * branches on a symbolic argument, and the plugins then read the CPU state, + * so the stores before the call must not be removed or moved past it. + */ +static void dropHelperMemoryEffects(Module &module) { + for (Function &f : module) { + if (!f.isDeclaration()) { + f.removeFnAttr(Attribute::Memory); + } + } +} + TCGLLVMTranslator::TCGLLVMTranslator(const std::string &bitcodeLibraryPath, std::unique_ptr module) : m_bitcodeLibraryPath(bitcodeLibraryPath), m_module(std::move(module)), m_builder(m_module->getContext()), m_tbCount(0), m_tcgContext(NULL), m_tbFunction(NULL), m_tbType(NULL) { @@ -96,6 +119,60 @@ TCGLLVMTranslator::TCGLLVMTranslator(const std::string &bitcodeLibraryPath, std: m_eip = NULL; m_ccop = NULL; + m_passBuilder.registerModuleAnalyses(m_mam); + m_passBuilder.registerCGSCCAnalyses(m_cgam); + m_passBuilder.registerFunctionAnalyses(m_fam); + m_passBuilder.registerLoopAnalyses(m_lam); + m_passBuilder.crossRegisterProxies(m_lam, m_fam, m_cgam, m_mam); + + /* + * KLEE interprets every instruction of a translation block, so each one + * removed saves time on every execution of the block. SROA turns the TCG + * local temps from allocas into registers, which also saves the memory + * object that KLEE allocates for each alloca. EarlyCSE removes repeated + * loads of the CPU state. Only a helper call can set se_tb_abort, so the + * check of a guest instruction becomes a constant when no call ran since + * the previous check. SimplifyCFG then removes the branches whose + * condition became constant, and merges the blocks. + * + * The pipeline must keep the shape of the code that KLEE and S2E depend on: + * - SimplifyCFG does not speculate blocks and does not simplify + * conditional branches. Both turn branches into selects or merge the + * conditions of several branches into one. KLEE forks the state on a + * branch with a symbolic condition, while a select merges both paths + * into one symbolic value, which can be the guest PC. The branch + * simplifications also merge conditional stores into a store of a + * select, and turn chains of comparisons into a switch preceded by a + * freeze instruction, which the KLEE executor does not implement. + * SimplifyCFG still folds the branches whose condition is a constant. + * EarlyCSE already replaces a condition with a constant in a block whose + * only predecessor branches on the same condition, which covers the + * repeated se_tb_abort checks. + * - InstSimplify replaces InstCombine. InstCombine can create intrinsics, + * such as llvm.ctpop or llvm.usub.sat, that the KLEE executor does not + * implement. KLEE lowers them when it loads the bitcode library. The + * translation blocks only go through the KFunction constructor, which + * lowers bswap and nothing else. + * - There is no dead store elimination pass. KLEE reads the CPU state where + * LLVM sees no read: when KLEE forks the state, on a branch of the block + * or inside a helper that the block calls, plugins read the guest PC and + * registers. Such a pass could remove a store before the branch if all + * paths after it overwrite the same location. EarlyCSE only removes a + * store that a later store in the same block overwrites with nothing in + * between that may read memory. A branch ends its block, and every helper + * call may read memory because dropHelperMemoryEffects() removes the + * memory effects of the helpers. + * SimplifyCFG also merges all returns into one block, which + * splitCommonReturn() undoes. + */ + m_fpm.addPass(llvm::SROAPass(llvm::SROAOptions::PreserveCFG)); + m_fpm.addPass(llvm::EarlyCSEPass(/* UseMemorySSA */ true)); + m_fpm.addPass(llvm::InstSimplifyPass()); + m_fpm.addPass( + llvm::SimplifyCFGPass(llvm::SimplifyCFGOptions().speculateBlocks(false).setSimplifyCondBranch(false))); + m_fpm.addPass(llvm::ADCEPass()); + + dropHelperMemoryEffects(*m_module); initializeNativeCpuState(); initializeHelpers(); } @@ -1133,6 +1210,58 @@ void TCGLLVMTranslator::removeInterruptExit() { BranchInst::Create(target, &bb); } +/// @brief Runs the pass pipeline that the constructor sets up on the current +/// translation block. +void TCGLLVMTranslator::optimizeTbFunction() { + m_fpm.run(*m_tbFunction, m_fam); + + // The analysis manager caches results by function address. splitCommonReturn() + // changes the function, and the function is erased when its translation block + // is flushed, after which a new one may get the same address. + m_fam.clear(*m_tbFunction, m_tbFunction->getName()); + + splitCommonReturn(); +} + +/// +/// @brief Gives each exit of the translation block its own return instruction. +/// +/// SimplifyCFG merges all return instructions into one block, and the exits +/// branch to it after storing their constant PC. GetStaticBranchTarget() +/// expects the store and the return in the same block, and +/// S2EExecutionState::getStaticBranchTargets() expects both successors of the +/// forking branch to be such blocks. This copies the return into each block +/// that ends in an unconditional branch to it. The blocks that reach the return +/// through a conditional branch, such as the se_tb_abort checks, keep using it. +/// +void TCGLLVMTranslator::splitCommonReturn() { + SmallVector rets; + for (auto &bb : *m_tbFunction) { + if (auto ret = dyn_cast(bb.getTerminator())) { + rets.push_back(ret); + } + } + + for (auto ret : rets) { + auto bb = ret->getParent(); + SmallVector preds(predecessors(bb)); + for (auto pred : preds) { + auto br = dyn_cast(pred->getTerminator()); + if (br && br->isUnconditional()) { + FoldReturnIntoUncondBranch(ret, bb, pred); + } + } + + if (pred_empty(bb) && bb != &m_tbFunction->getEntryBlock()) { + bb->eraseFromParent(); + } else { + // Folds the phi of the returned value when the remaining predecessors + // all return the same constant. + SimplifyInstructionsInBlock(bb); + } + } +} + Function *TCGLLVMTranslator::generateCode(TCGContext *s, TranslationBlock *tb) { m_tcgContext = s; m_tb = tb; @@ -1258,8 +1387,7 @@ Function *TCGLLVMTranslator::generateCode(TCGContext *s, TranslationBlock *tb) { abort(); } - // KLEE will optimize the function later - // m_functionPassManager->run(*m_tbFunction); + optimizeTbFunction(); if (libcpu_loglevel_mask(CPU_LOG_LLVM_IR)) { std::string fcnString; From 154de528af24d88af247649b77b693b4ecbc2f26 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sat, 17 Oct 2026 23:46:17 +0200 Subject: [PATCH 45/52] libcpu,libtcg,libs2ecore: reduced the interpreted work of the bitcode access path KLEE interpreted about 185 instructions for each guest memory access in the bitcode of cputlb.c, against 45 before the softmmu replacement. - Inline the access path in the bitcode build, so that MMULookupLocals stays in registers and the call frames disappear. - Add a TLB hit fast path to the bitcode wrappers (se_tlb_hit_haddr()), which accesses the host address directly when the page has no flags. - With fork-on-symbolic-address, make the address concrete once per access in the wrappers, before the TLB lookup, instead of again in mmu_lookup(). - Report symbolic hardware accesses from the device path (se_hw_ld_beN(), se_hw_st_leN()) instead of doing a second TLB lookup after every access. The host address comes from the lookup result. The reports carry the physical address, a load returns the value that the symbolic hardware plugins give back, and a store that TLB_DISCARD_WRITE drops is not reported. Code fetches from device pages are not reported. handlerTraceMmioAccess() takes the bytes of a load in the order of do_ld_mmio_beN() and converts them to guest byte order only when the access hits symbolic hardware, so that other symbolic bytes are returned unchanged. It now returns the value instead of the address when no symbolic hardware hook is registered. - Compute the TLB index once per lookup in mmu_lookup1(). - Compile the bitcode library with -Oz and the inline threshold of -Os, and force tlb_index() and tlb_entry() inline. This removes 25% of the instructions of op_helper.bc and keeps the TLB hit path at 47 to 51 instructions. Co-Authored-By: Claude Opus 5.5 --- libcpu/include/cpu/se_libcpu.h | 5 + libcpu/softmmu-update.md | 2 +- libcpu/src/CMakeLists.txt | 9 +- libcpu/src/accel/cputlb.c | 20 ++- libcpu/src/s2e/cputlb-deps.h | 9 ++ libcpu/src/s2e/cputlb-symbex-ldst.c.inc | 157 ++++++++++++++++++------ libcpu/src/s2e/cputlb-symbex.c.inc | 142 ++++++++++++++++++++- libs2ecore/include/s2e/s2e_libcpu.h | 5 + libs2ecore/src/FunctionHandlers.cpp | 33 ++++- libtcg/src/CMakeLists.txt | 4 +- 10 files changed, 324 insertions(+), 62 deletions(-) diff --git a/libcpu/include/cpu/se_libcpu.h b/libcpu/include/cpu/se_libcpu.h index 2c4167551..ac1ca996e 100644 --- a/libcpu/include/cpu/se_libcpu.h +++ b/libcpu/include/cpu/se_libcpu.h @@ -248,6 +248,11 @@ void tcg_llvm_after_memory_access(target_ulong vaddr, uint64_t value, unsigned s // XXX: change bits to bytes uint64_t tcg_llvm_trace_port_access(uint64_t port, uint64_t value, unsigned bits, int isWrite); +/* Reports an access to symbolic hardware. For a load, the low bytes of value + hold the bytes that were read, most significant first, and the function + returns value with them replaced by the bytes that the plugins return. For + a store, the low bytes hold the bytes that were written, least significant + first. See handlerTraceMmioAccess() in libs2ecore. */ uint64_t tcg_llvm_trace_mmio_access(uint64_t physaddr, uint64_t value, unsigned bytes, int isWrite); uint64_t tcg_llvm_get_value(uint64_t value, bool addConstraint); diff --git a/libcpu/softmmu-update.md b/libcpu/softmmu-update.md index 2f55e801d..90d029129 100644 --- a/libcpu/softmmu-update.md +++ b/libcpu/softmmu-update.md @@ -378,7 +378,7 @@ How each case is handled in the two builds: | Case | Native build | Bitcode build | |---|---|---| -| Address | Always concrete | `mmu_lookup()` calls `tcg_llvm_before_memory_access()`, then `tcg_llvm_fork_and_concretize()` on the address when `fork-on-symbolic-address` is set. `tlb_index()` concretizes the page number and computes the index from the result (hazard 5.5). | +| Address | Always concrete | The wrappers of `do_{ld,st}{1,2,4,8}_mmu` in `cputlb-symbex-ldst.c.inc` call `tcg_llvm_before_memory_access()`. These wrappers and those of `do_{ld,st}16_mmu` call `tcg_llvm_fork_and_concretize()` on the address when `fork-on-symbolic-address` is set, once per access and before the TLB lookup. `mmu_lookup()` gets the concrete address. `tlb_index()` concretizes the page number and computes the index from the result (hazard 5.5). | | Host address | `mmu_lookup1()` computes `addr + se_addend` under `CONFIG_SYMBEX_MP`, else `addr + addend` | `addr + addend`; the access resolves through the KLEE address space | | `TLB_SYMB`, loads | `se_mmu_resolve()` checks the accessed bytes with `_se_check_concrete()`. If they are symbolic and `ra` is in generated code, it calls `switch_to_symbolic(ra)`. Otherwise it routes the load to `do_ld_mmio_beN()`, which reads the concretized bytes with `g_sqi.mem.read_ram_concrete()`. | Ignored | | `TLB_SYMB` or `TLB_NOT_OURS`, stores | If the object is shared or the accessed bytes are symbolic, `se_mmu_resolve()` routes the store to `do_st_mmio_leN()`, which writes the value with `g_sqi.mem.write_ram_concrete()`. This copies the object, makes the bytes concrete and updates the TLB entry. | Ignored; KLEE copies the object | diff --git a/libcpu/src/CMakeLists.txt b/libcpu/src/CMakeLists.txt index a58c8e99e..ba472db9c 100644 --- a/libcpu/src/CMakeLists.txt +++ b/libcpu/src/CMakeLists.txt @@ -43,7 +43,14 @@ separate_arguments(BC_INC_DIRS) # The bitcode library that KLEE interprets: the helpers, the softmmu access # path (accel/cputlb.c) and softfloat. -set(BC_FLAGS ${CARGS_LIST} -Wno-unused-function -O3 -DSYMBEX_LLVM_LIB -march=x86-64 -emit-llvm ${BC_INC_DIRS} -fno-slp-vectorize -fno-tree-vectorize) +# +# The bitcode is optimized for size because KLEE interprets every instruction +# of it. -Oz alone does not inline functions of a few instructions, such as +# extract64(). KLEE pushes a stack frame for each call, which costs more than +# such a body, so the inline threshold is raised to that of -Os. +# libtcg/src/CMakeLists.txt compiles softfloat.bc with the same options. +set(BC_OPT_FLAGS -Oz -mllvm -inline-threshold=50) +set(BC_FLAGS ${CARGS_LIST} -Wno-unused-function ${BC_OPT_FLAGS} -DSYMBEX_LLVM_LIB -march=x86-64 -emit-llvm ${BC_INC_DIRS} -fno-slp-vectorize -fno-tree-vectorize) add_custom_target( op_helper_bc ALL diff --git a/libcpu/src/accel/cputlb.c b/libcpu/src/accel/cputlb.c index 5467a897e..5b3e9f9d5 100644 --- a/libcpu/src/accel/cputlb.c +++ b/libcpu/src/accel/cputlb.c @@ -88,7 +88,8 @@ static inline uint64_t tlb_addr_write(const CPUTLBEntry *entry) { } /* Find the TLB index corresponding to the mmu_idx + address pair. */ -static inline uintptr_t tlb_index(CPUState *cpu, uintptr_t mmu_idx, vaddr addr) { +/* S2E: SE_ALWAYS_INLINE here and on tlb_entry(), see cputlb-deps.h. */ +static inline SE_ALWAYS_INLINE uintptr_t tlb_index(CPUState *cpu, uintptr_t mmu_idx, vaddr addr) { uintptr_t size_mask = cpu_tlb_fast(cpu, mmu_idx)->mask >> CPU_TLB_ENTRY_BITS; /* S2E: the bitcode build forks on the page number, see cputlb-deps.h. */ @@ -96,7 +97,7 @@ static inline uintptr_t tlb_index(CPUState *cpu, uintptr_t mmu_idx, vaddr addr) } /* Find the TLB entry corresponding to the mmu_idx + address pair. */ -static inline CPUTLBEntry *tlb_entry(CPUState *cpu, uintptr_t mmu_idx, vaddr addr) { +static inline SE_ALWAYS_INLINE CPUTLBEntry *tlb_entry(CPUState *cpu, uintptr_t mmu_idx, vaddr addr) { return &cpu_tlb_fast(cpu, mmu_idx)->table[tlb_index(cpu, mmu_idx, addr)]; } @@ -1495,7 +1496,10 @@ static bool mmu_lookup1(CPUState *cpu, MMULookupPageData *data, MemOp memop, int uintptr_t ra) { vaddr addr = data->addr; uintptr_t index = tlb_index(cpu, mmu_idx, addr); - CPUTLBEntry *entry = tlb_entry(cpu, mmu_idx, addr); + /* S2E: the entry is taken from index rather than from tlb_entry(), which + would compute the index again. In bitcode, each computation is a call + to tcg_llvm_fork_and_concretize() that the compiler cannot merge. */ + CPUTLBEntry *entry = &cpu_tlb_fast(cpu, mmu_idx)->table[index]; uint64_t tlb_addr = tlb_read_idx(entry, access_type); bool maybe_resized = false; CPUTLBEntryFull *full; @@ -1507,7 +1511,7 @@ static bool mmu_lookup1(CPUState *cpu, MMULookupPageData *data, MemOp memop, int tlb_fill_align(cpu, addr, access_type, mmu_idx, memop, data->size, false, ra); maybe_resized = true; index = tlb_index(cpu, mmu_idx, addr); - entry = tlb_entry(cpu, mmu_idx, addr); + entry = &cpu_tlb_fast(cpu, mmu_idx)->table[index]; /* S2E, see above */ } tlb_addr = tlb_read_idx(entry, access_type) & ~TLB_INVALID_MASK; } @@ -1591,14 +1595,6 @@ static bool mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMU tcg_debug_assert(l->mmu_idx < NB_MMU_MODES); -#if defined(SYMBEX_LLVM_LIB) - /* S2E: with fork-on-symbolic-address, a symbolic address is replaced by - one of its values and the state forks on the others. */ - if (*g_sqi.mode.fork_on_symbolic_address) { - addr = tcg_llvm_fork_and_concretize(addr, 0, (target_ulong) -1, 0); - } -#endif - l->page[0].addr = addr; l->page[0].size = memop_size(l->memop); l->page[1].addr = 0; diff --git a/libcpu/src/s2e/cputlb-deps.h b/libcpu/src/s2e/cputlb-deps.h index 71a8aa34c..88e82415d 100644 --- a/libcpu/src/s2e/cputlb-deps.h +++ b/libcpu/src/s2e/cputlb-deps.h @@ -475,6 +475,14 @@ static inline void se_tlb_fill_flags(hwaddr paddr_page, unsigned *read_flags, un #define SE_CONCRETE_PAGE(page) tcg_llvm_fork_and_concretize(page, 0, ((target_ulong) - 1) >> TARGET_PAGE_BITS, 0) +/* + * The bitcode is optimized for size, which inlines less. tlb_index() and + * tlb_entry() are on the TLB hit path of every access, and KLEE pushes a stack + * frame for each call. They are defined before the always_inline region that + * cputlb-symbex.c.inc starts, so they carry the attribute themselves. + */ +#define SE_ALWAYS_INLINE __attribute__((always_inline)) + /* The victim TLB is disabled and always empty (tlb_set_page_full()). */ #define victim_tlb_hit(cpu, mmu_idx, index, access_type, page) false @@ -483,6 +491,7 @@ static inline void se_tlb_fill_flags(hwaddr paddr_page, unsigned *read_flags, un #define SE_TCG_HAS_OP(ops, op) ((ops)->op != NULL) #define SE_TCG_OP(cpu, op) ((cpu)->cc->tcg_ops->op) #define SE_CONCRETE_PAGE(page) (page) +#define SE_ALWAYS_INLINE #endif diff --git a/libcpu/src/s2e/cputlb-symbex-ldst.c.inc b/libcpu/src/s2e/cputlb-symbex-ldst.c.inc index 9e9870dbc..d107b9e0d 100644 --- a/libcpu/src/s2e/cputlb-symbex-ldst.c.inc +++ b/libcpu/src/s2e/cputlb-symbex-ldst.c.inc @@ -18,10 +18,11 @@ /// Reports guest memory accesses to the S2E plugins. /// /// accel/cputlb.c includes this file after the definitions of -/// do_{ld,st}{1,2,4,8}_mmu() and before the entry points that call them -/// (ldst_common.c.inc and the code fetch functions). Each function below -/// wraps one of them and reports the access, and the macros at the end make -/// the entry points call the wrappers. The upstream functions are not edited. +/// do_{ld,st}{1,2,4,8,16}_mmu() and before the entry points that call them +/// (ldst_common.c.inc and the code fetch functions). The functions below wrap +/// them, and the macros at the end make the entry points call the wrappers. +/// The wrappers of the accesses of 1 to 8 bytes report the access. The +/// upstream functions are not edited. /// /// The slow path only runs for the accesses that plugins want to see: when a /// plugin subscribes to memory accesses, tlb_set_page_full() marks every page @@ -29,7 +30,17 @@ /// /// Natively executed code reports an access after it happened, with its /// value. Bitcode also reports it before, while the address can still be -/// symbolic, and reports accesses to symbolic hardware. +/// symbolic. Bitcode reports accesses to symbolic hardware from the device +/// path instead (se_hw_ld_beN() and se_hw_st_leN() in cputlb-symbex.c.inc), +/// where the flags of the page are known. +/// +/// In the bitcode build, the wrappers also do the accesses that hit the TLB +/// themselves (se_tlb_hit_haddr()), so that KLEE only interprets the upstream +/// access path for misses and flagged pages. With fork-on-symbolic-address, +/// the wrappers also make the address concrete, once per access and before +/// the TLB lookup, and pass the concrete address to the upstream path. The +/// wrappers of do_ld16_mmu() and do_st16_mmu() only do this. mmu_lookup() +/// therefore always gets a concrete address and does not concretize it. #if defined(CONFIG_SYMBEX) @@ -41,38 +52,84 @@ static inline void se_trace_before(vaddr addr, uint64_t value, unsigned size, un } } -/* Returns true if the first page of an access is a device or holds - symbolic MMIO or DMA ranges. The access has just completed, so the page - is in the TLB. */ -static inline bool se_page_is_hw(CPUState *cpu, vaddr addr, MemOpIdx oi, MMUAccessType type) { - int mmu_idx = get_mmuidx(oi); - uintptr_t index = tlb_index(cpu, mmu_idx, addr); +static inline void se_trace_after(vaddr addr, uint64_t value, unsigned size, unsigned flags) { + if (*g_sqi.events.after_memory_access_signals_count) { + tcg_llvm_after_memory_access(addr, value, size, flags, 0); + } +} - if (!tlb_hit(tlb_read_idx(tlb_entry(cpu, mmu_idx, addr), type), addr)) { - return false; +/* With fork-on-symbolic-address, replaces a symbolic address by one of its + values and forks the state on the others. */ +static inline vaddr se_concrete_addr(vaddr addr) { + if (*g_sqi.mode.fork_on_symbolic_address) { + addr = tcg_llvm_fork_and_concretize(addr, 0, (target_ulong) -1, 0); } - return (cpu->neg.tlb.d[mmu_idx].fulltlb[index].slow_flags[type] & (TLB_MMIO | TLB_SYMB_MMIO)) != 0; + return addr; } -static inline void se_trace_after(CPUState *cpu, vaddr addr, MemOpIdx oi, uint64_t value, unsigned size, - unsigned flags) { - bool is_write = (flags & MEM_TRACE_FLAG_WRITE) != 0; +/* + * The TLB hit fast path of the bitcode build. + * + * In natively executed code, the TCG backend inlines the TLB hit check into + * the generated code, and only a miss or a flagged page calls the helpers. + * The LLVM translator calls the helpers for every access, so without this + * function KLEE would interpret the whole upstream access path every time. + * + * The function handles the accesses that need nothing but the host address: + * no byte swap, no alignment requirement, no page crossing, and a TLB entry + * for the page with none of the upstream comparator flags. Device pages, + * watchpoints, read-only pages and pages with symbolic hardware have flags in + * slow_flags, which always set TLB_FORCE_SLOW in the comparator + * (tlb_set_compare()). The S2E comparator flags are ignored, as in the + * upstream path of the bitcode: KLEE handles symbolic data and shared + * objects itself, and the wrappers below report the access. + * + * The caller makes the address concrete first (se_concrete_addr()). + * + * @return true if the caller can access the bytes at *haddr + */ +static inline bool se_tlb_hit_haddr(CPUState *cpu, vaddr addr, MemOpIdx oi, MMUAccessType type, void **haddr) { + MemOp memop = get_memop(oi); + int mmu_idx = get_mmuidx(oi); + CPUTLBEntry *entry; + uint64_t tlb_addr; - if (*g_sqi.events.after_memory_access_signals_count) { - tcg_llvm_after_memory_access(addr, value, size, flags, 0); + if (memop & (MO_BSWAP | MO_AMASK)) { + return false; + } + + if ((addr & ~TARGET_PAGE_MASK) + memop_size(memop) > TARGET_PAGE_SIZE) { + return false; } - if (se_page_is_hw(cpu, addr, oi, is_write ? MMU_DATA_STORE : MMU_DATA_LOAD)) { - tcg_llvm_trace_mmio_access(addr, value, size, is_write); + entry = tlb_entry(cpu, mmu_idx, addr); + tlb_addr = tlb_read_idx(entry, type); + if ((tlb_addr & (TARGET_PAGE_MASK | (TLB_FLAGS_MASK & ~TLB_SE_FLAGS_MASK))) != (addr & TARGET_PAGE_MASK)) { + return false; } + + *haddr = (void *) ((uintptr_t) addr + entry->addend); + return true; +} + +/* 16-byte accesses are not reported and always take the upstream path. */ +static Int128 se_do_ld16_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra) { + return do_ld16_mmu(cpu, se_concrete_addr(addr), oi, ra); +} + +static void se_do_st16_mmu(CPUState *cpu, vaddr addr, Int128 val, MemOpIdx oi, uintptr_t ra) { + do_st16_mmu(cpu, se_concrete_addr(addr), val, oi, ra); } +#define do_ld16_mmu se_do_ld16_mmu +#define do_st16_mmu se_do_st16_mmu + #else #define se_trace_before(addr, value, size, flags) ((void) 0) +#define se_concrete_addr(addr) (addr) -static inline void se_trace_after(CPUState *cpu, vaddr addr, MemOpIdx oi, uint64_t value, unsigned size, - unsigned flags) { +static inline void se_trace_after(vaddr addr, uint64_t value, unsigned size, unsigned flags) { #if defined(SE_ENABLE_MEM_TRACING) if (unlikely(*g_sqi.events.after_memory_access_signals_count)) { g_sqi.events.after_memory_access(addr, value, size, flags, 0); @@ -80,37 +137,54 @@ static inline void se_trace_after(CPUState *cpu, vaddr addr, MemOpIdx oi, uint64 #endif } +/* Natively executed code reaches the helpers only after the inline fast path + of the generated code has failed. */ +#define se_tlb_hit_haddr(cpu, addr, oi, type, haddr) false + #endif -/* Code fetches are not reported. */ -#define SE_GEN_LD(n, type) \ +/* Code fetches are not reported. ld_he and st_he access the host bytes in + host byte order, which is the order of the accesses of the fast path. */ +#define SE_GEN_LD(n, type, ld_he) \ static type se_do_ld##n##_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi, uintptr_t ra, MMUAccessType access) { \ type ret; \ + void *haddr; \ if (access == MMU_INST_FETCH) { \ - return do_ld##n##_mmu(cpu, addr, oi, ra, access); \ + return do_ld##n##_mmu(cpu, se_concrete_addr(addr), oi, ra, access); \ } \ se_trace_before(addr, 0, n, 0); \ - ret = do_ld##n##_mmu(cpu, addr, oi, ra, access); \ - se_trace_after(cpu, addr, oi, ret, n, 0); \ + addr = se_concrete_addr(addr); \ + if (se_tlb_hit_haddr(cpu, addr, oi, access, &haddr)) { \ + ret = ld_he(haddr); \ + } else { \ + ret = do_ld##n##_mmu(cpu, addr, oi, ra, access); \ + } \ + se_trace_after(addr, ret, n, 0); \ return ret; \ } -#define SE_GEN_ST(n, type) \ +#define SE_GEN_ST(n, type, st_he) \ static void se_do_st##n##_mmu(CPUState *cpu, vaddr addr, type val, MemOpIdx oi, uintptr_t ra) { \ + void *haddr; \ se_trace_before(addr, val, n, MEM_TRACE_FLAG_WRITE); \ - do_st##n##_mmu(cpu, addr, val, oi, ra); \ - se_trace_after(cpu, addr, oi, val, n, MEM_TRACE_FLAG_WRITE); \ + addr = se_concrete_addr(addr); \ + if (se_tlb_hit_haddr(cpu, addr, oi, MMU_DATA_STORE, &haddr)) { \ + st_he(haddr, val); \ + } else { \ + do_st##n##_mmu(cpu, addr, val, oi, ra); \ + } \ + se_trace_after(addr, val, n, MEM_TRACE_FLAG_WRITE); \ } -SE_GEN_LD(1, uint8_t) -SE_GEN_LD(2, uint16_t) -SE_GEN_LD(4, uint32_t) -SE_GEN_LD(8, uint64_t) +SE_GEN_LD(1, uint8_t, ldub_p) +SE_GEN_LD(2, uint16_t, lduw_he_p) +SE_GEN_LD(4, uint32_t, ldl_he_p) +SE_GEN_LD(8, uint64_t, ldq_he_p) -SE_GEN_ST(1, uint8_t) -SE_GEN_ST(2, uint16_t) -SE_GEN_ST(4, uint32_t) -SE_GEN_ST(8, uint64_t) +SE_GEN_ST(1, uint8_t, stb_p) +SE_GEN_ST(2, uint16_t, stw_he_p) +SE_GEN_ST(4, uint32_t, stl_he_p) +SE_GEN_ST(8, uint64_t, stq_he_p) #undef SE_GEN_LD #undef SE_GEN_ST @@ -126,3 +200,8 @@ SE_GEN_ST(8, uint64_t) #define do_st8_mmu se_do_st8_mmu #endif + +#if defined(SYMBEX_LLVM_LIB) +/* Ends the region of inlined functions that cputlb-symbex.c.inc starts. */ +#pragma clang attribute pop +#endif diff --git a/libcpu/src/s2e/cputlb-symbex.c.inc b/libcpu/src/s2e/cputlb-symbex.c.inc index 24f52fd7c..15c5ed743 100644 --- a/libcpu/src/s2e/cputlb-symbex.c.inc +++ b/libcpu/src/s2e/cputlb-symbex.c.inc @@ -41,10 +41,13 @@ /// two functions call se_ram_ld_beN() and se_ram_st_leN() below, which do /// the access through libs2ecore when the page is RAM. The upstream load and /// store functions therefore need no S2E change, and no state is kept -/// between the lookup and the access. +/// between the lookup and the access. In the bitcode build, se_mmu_resolve() +/// only routes the accesses to symbolic hardware, which are reported to the +/// plugins. /// /// The file also replaces the atomic load and store primitives of -/// ldst_atomicity.c.inc in builds with symbolic execution. +/// ldst_atomicity.c.inc in builds with symbolic execution, and makes the +/// bitcode build inline the load and store path (see the end of the file). #if defined(CONFIG_SYMBEX) @@ -213,10 +216,128 @@ static inline bool se_ram_st_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t return true; } +#elif defined(CONFIG_SYMBEX) && defined(SYMBEX_LLVM_LIB) + +/* + * The bitcode build. KLEE handles symbolic data and copies shared objects + * itself, so the only S2E case left is symbolic hardware: the accesses to a + * device page (TLB_MMIO) or to a RAM page with symbolic MMIO or DMA ranges + * (TLB_SYMB_MMIO) are reported to libs2ecore with + * tcg_llvm_trace_mmio_access(), which passes them to the symbolic hardware + * plugins. + * + * se_mmu_resolve() sends the accesses to RAM pages with TLB_SYMB_MMIO down + * the device path, like the native build does for the pages it cannot access + * directly. se_hw_ld_beN() and se_hw_st_leN() replace do_ld_mmio_beN() and + * do_st_mmio_leN() on that path. They do the access and report it. The flags + * of the page are known there, so the other accesses pay nothing for the + * check. + * + * An access that crosses a page boundary is reported once per page that has + * symbolic hardware, with the physical address and the size of the part in + * that page. The two pages need not be contiguous in physical memory, and + * the native device path splits such an access in the same way. + */ + +static inline void se_mmu_route_hw_page(MMULookupPageData *p) { + if (p->size && (p->flags & TLB_SYMB_MMIO)) { + p->flags |= TLB_MMIO; + } +} + +static inline void se_mmu_resolve(CPUState *cpu, MMULookupLocals *l, MMUAccessType type, uintptr_t ra) { + /* Code fetches are not reported. Accesses of 16 bytes to RAM pages are not + reported either: do_ld16_mmio_beN() and do_st16_mmio_leN() have no + replacement, and the native ones would concretize the symbolic bytes of + a RAM page. A device page already has TLB_MMIO. Its accesses reach + se_hw_ld_beN() and se_hw_st_leN() unless they are 16 bytes long and fit + in the page, in which case the native 16-byte functions handle them. */ + if (type == MMU_INST_FETCH || memop_size(l->memop) > 8) { + return; + } + + se_mmu_route_hw_page(&l->page[0]); + se_mmu_route_hw_page(&l->page[1]); +} + +/* + * Replaces do_ld_mmio_beN() in bitcode. A device page is read through the + * native function. A RAM page is read here, so that KLEE returns its symbolic + * bytes as they are. The symbolic hardware plugins may replace the bytes that + * were read, and the guest gets the bytes they return. Code fetches from a + * device page are not reported. + * + * @param ret_be the bytes are appended to it, most significant first + * @param haddr the host address of the bytes, which mmu_lookup1() computed; + * only valid for a RAM page + * @return ret_be with the size bytes of the access appended + */ +static uint64_t se_hw_ld_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t ret_be, vaddr addr, int size, int mmu_idx, + MMUAccessType type, uintptr_t ra, const uint8_t *haddr) { + if (full->slow_flags[type] & TLB_MMIO) { + ret_be = do_ld_mmio_beN(cpu, full, ret_be, addr, size, mmu_idx, type, ra); + if (type == MMU_INST_FETCH) { + return ret_be; + } + } else { + for (int i = 0; i < size; i++) { + ret_be = (ret_be << 8) | haddr[i]; + } + } + + /* The handler converts the bytes to the guest byte order that the plugins + use, and only when a plugin takes the access. Doing it here would put + the symbolic bytes of every other access through a byte swap and back. */ + return tcg_llvm_trace_mmio_access(full->phys_addr | (addr & ~TARGET_PAGE_MASK), ret_be, size, 0); +} + +/* + * Replaces do_st_mmio_leN() in bitcode. A device page is written through the + * native function. A RAM page is written here, so that KLEE stores symbolic + * bytes as they are and copies the object first if it is shared. A store to + * a read-only RAM page (TLB_DISCARD_WRITE) leaves memory unchanged and is not + * reported. + * + * @param val_le the bytes are taken from it, least significant first + * @param haddr the host address of the bytes, which mmu_lookup1() computed; + * only valid for a RAM page + * @return val_le shifted right by the size bytes of the access + */ +static uint64_t se_hw_st_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t val_le, vaddr addr, int size, int mmu_idx, + uintptr_t ra, uint8_t *haddr) { + uint64_t value_le = size == 8 ? val_le : val_le & ((1ull << (size * 8)) - 1); + int flags = full->slow_flags[MMU_DATA_STORE]; + + if (flags & TLB_MMIO) { + val_le = do_st_mmio_leN(cpu, full, val_le, addr, size, mmu_idx, ra); + } else if (flags & TLB_DISCARD_WRITE) { + return size == 8 ? 0 : val_le >> (size * 8); + } else { + for (int i = 0; i < size; i++) { + haddr[i] = val_le; + val_le >>= 8; + } + } + + tcg_llvm_trace_mmio_access(full->phys_addr | (addr & ~TARGET_PAGE_MASK), value_le, size, 1); + return val_le; +} + +/* Every caller of do_ld_mmio_beN() and do_st_mmio_leN() in cputlb.c passes + p->full and p->addr, where p is the MMULookupPageData of the page. The + macros take the host address from the same p. In bitcode, it is the addend + of the TLB entry, not se_addend, so KLEE resolves it to the object of the + page in the current state. Computing it again from the TLB would cost + another tcg_llvm_fork_and_concretize() call. */ +#define do_ld_mmio_beN(cpu, full, ret_be, addr, size, mmu_idx, type, ra) \ + se_hw_ld_beN(cpu, full, ret_be, addr, size, mmu_idx, type, ra, (const uint8_t *) p->haddr) +#define do_st_mmio_leN(cpu, full, val_le, addr, size, mmu_idx, ra) \ + se_hw_st_leN(cpu, full, val_le, addr, size, mmu_idx, ra, (uint8_t *) p->haddr) + #else -/* KLEE handles symbolic data and copies shared objects itself, and the other - builds have neither. */ +/* Builds without multi-path symbolic execution have no symbolic data and no + shared KLEE objects. */ #define se_mmu_resolve(cpu, l, type, ra) ((void) 0) static inline bool se_ram_ld_beN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t *ret_be, vaddr addr, int size, @@ -230,3 +351,16 @@ static inline bool se_ram_st_leN(CPUState *cpu, CPUTLBEntryFull *full, uint64_t } #endif + +#if defined(SYMBEX_LLVM_LIB) +/* + * KLEE executes a call by pushing a stack frame, and a local variable whose + * address is taken, such as the MMULookupLocals of every access, by + * allocating a memory object and mapping it in the address space of the + * state. Inlining the access path into its entry points lets the compiler + * keep these locals in registers and fold the work that depends on constants. + * The attribute applies to every function that cputlb.c defines from here to + * the end of cputlb-symbex-ldst.c.inc, which ends the region. + */ +#pragma clang attribute push(__attribute__((always_inline)), apply_to = function) +#endif diff --git a/libs2ecore/include/s2e/s2e_libcpu.h b/libs2ecore/include/s2e/s2e_libcpu.h index c3a97b2be..fc7bfd54a 100644 --- a/libs2ecore/include/s2e/s2e_libcpu.h +++ b/libs2ecore/include/s2e/s2e_libcpu.h @@ -203,6 +203,11 @@ void tcg_llvm_after_memory_access(target_ulong vaddr, uint64_t value, unsigned s uint64_t tcg_llvm_trace_port_access(uint64_t port, uint64_t value, unsigned bits, int isWrite); +/* Reports an access to symbolic hardware. For a load, the low bytes of value + hold the bytes that were read, most significant first, and the function + returns value with them replaced by the bytes that the plugins return. For + a store, the low bytes hold the bytes that were written, least significant + first. See handlerTraceMmioAccess() in libs2ecore. */ uint64_t tcg_llvm_trace_mmio_access(uint64_t physaddr, uint64_t value, unsigned bytes, int isWrite); void tcg_llvm_get_value(void *addr, unsigned nbytes, bool addConstraint); diff --git a/libs2ecore/src/FunctionHandlers.cpp b/libs2ecore/src/FunctionHandlers.cpp index d1c9cbddf..1c4e00de4 100644 --- a/libs2ecore/src/FunctionHandlers.cpp +++ b/libs2ecore/src/FunctionHandlers.cpp @@ -223,19 +223,40 @@ static void handlerOnTlbMiss(Executor *executor, ExecutionState *state, klee::KI } #endif +/// Reverses the order of the bytes of an expression whose width is a multiple +/// of 8. Extracts and concatenations keep the expression simple: swapping twice +/// gives back the original expression. +static klee::ref swapBytes(const klee::ref &value) { + unsigned size = value->getWidth() / 8; + klee::ref ret = klee::ExtractExpr::create(value, 0, 8); + for (unsigned i = 1; i < size; ++i) { + ret = klee::ConcatExpr::create(ret, klee::ExtractExpr::create(value, i * 8, 8)); + } + return ret; +} + +/// Passes an access to symbolic hardware to the plugins. +/// +/// The arguments are those of tcg_llvm_trace_mmio_access(). For a load, the +/// low size bytes of the value hold the bytes that were read, most significant +/// first, and the handler returns the value with these bytes replaced by the +/// ones that the plugins return. The other bytes are kept. For a store, the low +/// size bytes hold the bytes that were written, least significant first. When +/// the access does not hit symbolic hardware, the handler returns the value +/// unchanged, so that symbolic bytes do not go through any computation. static void handlerTraceMmioAccess(Executor *executor, ExecutionState *state, klee::KInstruction *target, std::vector> &args) { assert(args.size() == 4); auto symbolicPhysAddress = args[0]; + klee::ref value = args[1]; if (!g_symbolicMemoryHook.hasHook()) { // Avoid forced concretizations if symbolic hardware is not enabled - state->llvm.bindLocal(target, symbolicPhysAddress); + state->llvm.bindLocal(target, value); return; } uint64_t physAddress = state->toConstant(symbolicPhysAddress, "MMIO address")->getZExtValue(); - klee::ref value = args[1]; unsigned size = cast(args[2])->getZExtValue(); if (!g_symbolicMemoryHook.symbolic(nullptr, physAddress, size)) { @@ -250,9 +271,13 @@ static void handlerTraceMmioAccess(Executor *executor, ExecutionState *state, kl g_symbolicMemoryHook.write(nullptr, physAddress, resizedValue, SYMB_MMIO); state->llvm.bindLocal(target, value); } else { - klee::ref ret = g_symbolicMemoryHook.read(nullptr, physAddress, resizedValue, SYMB_MMIO); + // The plugins take and return the value in guest byte order. + klee::ref ret = g_symbolicMemoryHook.read(nullptr, physAddress, swapBytes(resizedValue), SYMB_MMIO); assert(ret->getWidth() == resizedValue->getWidth()); - ret = klee::ZExtExpr::create(ret, klee::Expr::Int64); + ret = swapBytes(ret); + if (size < 8) { + ret = klee::ConcatExpr::create(klee::ExtractExpr::create(value, size * 8, 64 - size * 8), ret); + } state->llvm.bindLocal(target, ret); } } diff --git a/libtcg/src/CMakeLists.txt b/libtcg/src/CMakeLists.txt index aea26af75..19e95d049 100644 --- a/libtcg/src/CMakeLists.txt +++ b/libtcg/src/CMakeLists.txt @@ -74,9 +74,11 @@ foreach(dir ${dirs}) endforeach() separate_arguments(BC_INC_DIRS) +# Optimized for size, as the rest of the bitcode library (see BC_OPT_FLAGS in +# libcpu/src/CMakeLists.txt). add_custom_target( softfloat_bc ALL - clang-19 ${CMAKE_CURRENT_SOURCE_DIR}/fpu/softfloat.c -c ${CARGS_LIST} -I${LIBTCG_INCLUDE_DIR} ${BC_INC_DIRS} -Wno-unused-function -O3 -DSYMBEX_LLVM_LIB -march=x86-64 -emit-llvm -o ${CMAKE_CURRENT_BINARY_DIR}/softfloat.bc ${BC_INC_DIRS} -fno-slp-vectorize -fno-tree-vectorize + clang-19 ${CMAKE_CURRENT_SOURCE_DIR}/fpu/softfloat.c -c ${CARGS_LIST} -I${LIBTCG_INCLUDE_DIR} ${BC_INC_DIRS} -Wno-unused-function -Oz -mllvm -inline-threshold=50 -DSYMBEX_LLVM_LIB -march=x86-64 -emit-llvm -o ${CMAKE_CURRENT_BINARY_DIR}/softfloat.bc ${BC_INC_DIRS} -fno-slp-vectorize -fno-tree-vectorize DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/fpu/softfloat.c ) endif (WITH_SYMBEX) \ No newline at end of file From cdc1da9e0017117fc85ed2e592515a63cb7ab3a4 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sun, 18 Oct 2026 13:12:32 +0200 Subject: [PATCH 46/52] libtcg,libutils: disabled inline assembly in the softfloat bitcode shl_double(), shr_double() and udiv_qrnnd() used x86 inline assembly because the bitcode is compiled with -march=x86-64. KLEE cannot interpret inline assembly and terminated any state that ran an FPU helper in symbolic mode. The bitcode build now uses the portable C versions. Co-Authored-By: Claude Opus 5.5 --- libtcg/include/fpu/softfloat-macros.h | 6 ++++-- libutils/include/utils/host-utils.h | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/libtcg/include/fpu/softfloat-macros.h b/libtcg/include/fpu/softfloat-macros.h index 973706076..28d51bb27 100644 --- a/libtcg/include/fpu/softfloat-macros.h +++ b/libtcg/include/fpu/softfloat-macros.h @@ -93,7 +93,8 @@ extern "C" { * Shift @l left by @c bits, shifting in bits from @r. */ static inline uint64_t shl_double(uint64_t l, uint64_t r, int c) { -#if defined(__x86_64__) +/* S2E: KLEE cannot interpret inline assembly, so the bitcode uses the C version. */ +#if defined(__x86_64__) && !defined(SYMBEX_LLVM_LIB) asm("shld %b2, %1, %0" : "+r"(l) : "r"(r), "ci"(c)); return l; #else @@ -110,7 +111,8 @@ static inline uint64_t shl_double(uint64_t l, uint64_t r, int c) { * Shift @r right by @c bits, shifting in bits from @l. */ static inline uint64_t shr_double(uint64_t l, uint64_t r, int c) { -#if defined(__x86_64__) +/* S2E: KLEE cannot interpret inline assembly, so the bitcode uses the C version. */ +#if defined(__x86_64__) && !defined(SYMBEX_LLVM_LIB) asm("shrd %b2, %1, %0" : "+r"(r) : "r"(l), "ci"(c)); return r; #else diff --git a/libutils/include/utils/host-utils.h b/libutils/include/utils/host-utils.h index 11105f758..240824cf4 100644 --- a/libutils/include/utils/host-utils.h +++ b/libutils/include/utils/host-utils.h @@ -760,7 +760,12 @@ void ulshift(uint64_t *plow, uint64_t *phigh, int32_t shift, bool *overflow); * Licensed under the GPLv2/LGPLv3 */ static inline uint64_t udiv_qrnnd(uint64_t *r, uint64_t n1, uint64_t n0, uint64_t d) { -#if defined(__x86_64__) +/* + * S2E: KLEE cannot interpret inline assembly, so the bitcode uses the generic + * version. A 128-bit division would not work either, because clang lowers it + * to a call to __udivti3, which the bitcode does not define. + */ +#if defined(__x86_64__) && !defined(SYMBEX_LLVM_LIB) uint64_t q; asm("divq %4" : "=a"(q), "=d"(*r) : "0"(n0), "1"(n1), "rm"(d)); return q; From 52fb17cea39041076949e029a9ba1b5a474a98df Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sun, 18 Oct 2026 13:12:32 +0200 Subject: [PATCH 47/52] libcpu: fail the build if the helper bitcode contains inline assembly Co-Authored-By: Claude Opus 5.5 --- libcpu/src/CMakeLists.txt | 1 + libcpu/src/check-no-inline-asm.cmake | 31 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 libcpu/src/check-no-inline-asm.cmake diff --git a/libcpu/src/CMakeLists.txt b/libcpu/src/CMakeLists.txt index ba472db9c..b4e371ffe 100644 --- a/libcpu/src/CMakeLists.txt +++ b/libcpu/src/CMakeLists.txt @@ -57,6 +57,7 @@ add_custom_target( clang-19 ${CMAKE_CURRENT_SOURCE_DIR}/target-i386/op_helper.c -c ${BC_FLAGS} -o ${CMAKE_CURRENT_BINARY_DIR}/op_helper-org.bc COMMAND clang-19 ${CMAKE_CURRENT_SOURCE_DIR}/accel/cputlb.c -c ${BC_FLAGS} -o ${CMAKE_CURRENT_BINARY_DIR}/cputlb.bc COMMAND llvm-link-19 ${CMAKE_CURRENT_BINARY_DIR}/op_helper-org.bc ${CMAKE_CURRENT_BINARY_DIR}/cputlb.bc ${LIBTCG_DIR}/src/softfloat.bc -o ${CMAKE_CURRENT_BINARY_DIR}/op_helper.bc + COMMAND ${CMAKE_COMMAND} -DLLVM_DIS=llvm-dis-19 -DBITCODE=${CMAKE_CURRENT_BINARY_DIR}/op_helper.bc -P ${CMAKE_CURRENT_SOURCE_DIR}/check-no-inline-asm.cmake DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/target-i386/op_helper.c ${CMAKE_CURRENT_SOURCE_DIR}/accel/cputlb.c ) diff --git a/libcpu/src/check-no-inline-asm.cmake b/libcpu/src/check-no-inline-asm.cmake new file mode 100644 index 000000000..2c7c8a95d --- /dev/null +++ b/libcpu/src/check-no-inline-asm.cmake @@ -0,0 +1,31 @@ +# Fails the build if the bitcode library contains inline assembly. +# +# KLEE cannot interpret inline assembly and terminates any state that reaches +# it. Host headers often have x86 inline-asm fast paths, which the bitcode +# build must disable with SYMBEX_LLVM_LIB. +# +# Usage: cmake -DLLVM_DIS= -DBITCODE= -P check-no-inline-asm.cmake + +execute_process( + COMMAND ${LLVM_DIS} ${BITCODE} -o - + OUTPUT_VARIABLE IR + RESULT_VARIABLE RES +) + +if (NOT RES EQUAL 0) + message(FATAL_ERROR "${LLVM_DIS} failed on ${BITCODE}") +endif () + +# Inline assembly appears as "call asm [sideeffect] ..." (or invoke and +# callbr) in function bodies, and as "module asm ..." at the top level. The +# text between the call keyword and "asm" may not contain "@" or a quote, so +# that a callee or a string constant that contains " asm " does not match. +string(REGEX MATCHALL "\n[^\n\"@]*(call|invoke|callbr) [^\n\"@]*asm [^\n]*" ASM_CALLS "${IR}") +string(REGEX MATCHALL "\nmodule asm [^\n]*" ASM_MODULE "${IR}") +set(ASM_LINES ${ASM_CALLS} ${ASM_MODULE}) + +if (ASM_LINES) + list(LENGTH ASM_LINES COUNT) + string(REPLACE ";" "" ASM_TEXT "${ASM_LINES}") + message(FATAL_ERROR "${BITCODE} contains ${COUNT} inline assembly statements:${ASM_TEXT}") +endif () From 0193c4122893e362ecbeafc704836b7081b0b6af Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sun, 18 Oct 2026 13:12:32 +0200 Subject: [PATCH 48/52] klee: print the asm string and function on unsupported inline assembly Co-Authored-By: Claude Opus 5.5 --- klee/lib/Core/Executor.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/klee/lib/Core/Executor.cpp b/klee/lib/Core/Executor.cpp index 4c2d7f1ae..cffbb872b 100644 --- a/klee/lib/Core/Executor.cpp +++ b/klee/lib/Core/Executor.cpp @@ -42,6 +42,7 @@ #include "llvm/IR/DataLayout.h" #include "llvm/IR/Function.h" #include "llvm/IR/GetElementPtrTypeIterator.h" +#include "llvm/IR/InlineAsm.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" @@ -795,7 +796,9 @@ void Executor::executeInstruction(ExecutionState &state, KInstruction *ki) { i++; } } else if (isa(fp)) { - throw LLVMExecutorException("inline assembly is unsupported"); + throw LLVMExecutorException("inline assembly is unsupported: \"" + + cast(fp)->getAsmString() + "\" in function " + + i->getFunction()->getName().str()); break; } } From 3adb4fa9644e49ae193b6e24fc882184e2af17d9 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sun, 18 Oct 2026 13:36:28 +0200 Subject: [PATCH 49/52] libs2e: pass the interrupt window request to the cpu on every kvm_run The request was only copied when the cpu coroutine started a new cpu_x86_exec. When the client requested a window on the KVM_RUN that completes an I/O exit, the coroutine resumed in the middle of cpu_x86_exec and the request was ignored. An interrupt raised by an I/O handler while the guest had interrupts disabled then stayed pending until an unrelated exit. SeaBIOS failed to boot from a floppy because the controller's reset interrupt never arrived in time. This was masked until 4223c7d7, whose cpu exit signal handler set the window request on every kick. Co-Authored-By: Claude Opus 5.5 --- libs2e/src/s2e-kvm-vcpu.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/libs2e/src/s2e-kvm-vcpu.cpp b/libs2e/src/s2e-kvm-vcpu.cpp index 0fc3edb2f..be9357718 100644 --- a/libs2e/src/s2e-kvm-vcpu.cpp +++ b/libs2e/src/s2e-kvm-vcpu.cpp @@ -318,7 +318,6 @@ int VCPU::setSignalMask(kvm_signal_mask *mask) { void VCPU::coroutineFcn(void *opaque) { VCPU *vcpu = reinterpret_cast(opaque); CPUX86State *env = vcpu->m_env; - auto buffer = vcpu->m_cpuBuffer; while (1) { if (!vcpu->m_task_runner.run_on_thread()) { @@ -329,8 +328,6 @@ void VCPU::coroutineFcn(void *opaque) { assert(env_cpu(env)->current_tb == NULL); - env->kvm_request_interrupt_window |= buffer->request_interrupt_window; - vcpu->m_cpuStateIsPrecise = false; cpu_x86_exec(env); vcpu->m_cpuStateIsPrecise = true; @@ -431,6 +428,14 @@ int VCPU::run(int vcpu_fd) { m_handlingKvmCallback = false; m_handlingDeviceState = false; + // The client may request an interrupt window on any KVM_RUN, including the one + // that completes an I/O exit. In that case, the coroutine resumes in the middle + // of cpu_x86_exec, so the request must reach the cpu here rather than when the + // coroutine starts a new cpu_x86_exec. Otherwise, an interrupt raised by an I/O + // handler (e.g., the floppy controller's reset interrupt) stays pending until an + // unrelated exit occurs. + m_env->kvm_request_interrupt_window |= m_cpuBuffer->request_interrupt_window; + coroutine_enter(m_coroutine, this); if (m_kvm->exiting()) { From 35f1c4a0ea9c2514f1111f69ae3350e671c38a31 Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sun, 18 Oct 2026 16:11:21 +0200 Subject: [PATCH 50/52] libs2ecore: gave print_stacktrace c linkage s2e_log.h declares print_stacktrace() inside extern "C", but Utils.cpp did not include the header and defined the function with C++ linkage. Co-Authored-By: Claude Opus 5.5 --- libs2ecore/src/Utils.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libs2ecore/src/Utils.cpp b/libs2ecore/src/Utils.cpp index 2580c6480..22d5bc992 100644 --- a/libs2ecore/src/Utils.cpp +++ b/libs2ecore/src/Utils.cpp @@ -30,10 +30,13 @@ #include #include +#include // stacktrace.h (c) 2008, Timo Bingmann from http://idlebox.net/ // published under the WTFPL v2.0 +extern "C" { + /** Print a demangled stack backtrace of the caller function to FILE* out. */ void print_stacktrace(void (*print_func)(const char *fmt, ...), const char *reason) { // storage array for stack trace address data @@ -103,6 +106,7 @@ void print_stacktrace(void (*print_func)(const char *fmt, ...), const char *reas free(funcname); free(symbollist); } +} namespace s2e { From 9993bd6cd0f139429273295e04faa25b439313da Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sun, 18 Oct 2026 17:23:57 +0200 Subject: [PATCH 51/52] tools: updated the gdb tlb commands to the new tlb layout The TLB is no longer in CPUX86State. virt_to_host_tlb and s2e-cpu-print-tlb now find it in the CPUState that precedes env in ArchCPU, and take the table size from its mask. The print command shows every MMU index. Co-Authored-By: Claude Opus 5.5 --- tools/tools/scripts/gdb.py | 46 +++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/tools/tools/scripts/gdb.py b/tools/tools/scripts/gdb.py index 9f939435c..efd21f5ad 100644 --- a/tools/tools/scripts/gdb.py +++ b/tools/tools/scripts/gdb.py @@ -31,7 +31,8 @@ g_cpu_env = 'g_cpu_env' -CPU_TLB_SIZE = 256 +CPU_TLB_ENTRY_BITS = 6 +NB_MMU_MODES = 2 TARGET_PAGE_BITS = 12 TARGET_PAGE_SIZE = 1 << TARGET_PAGE_BITS TARGET_PAGE_MASK = ~(TARGET_PAGE_SIZE - 1) @@ -191,11 +192,19 @@ def get_linear_address(self, seg, addr): base = self.segs[seg]['base'] return int(base + addr) + def get_tlb_fast(self, mmu_idx): + # The TLB is in the CPUState that precedes env in ArchCPU. + cpu = gdb.parse_and_eval('(ArchCPU *) ((char *) %s - (unsigned long) &((ArchCPU *) 0)->env)' % g_cpu_env) + fast = cpu['parent_obj']['neg']['tlb']['f'][mmu_idx] + size = (int(fast['mask']) >> CPU_TLB_ENTRY_BITS) + 1 + return fast['table'], size + def virt_to_host_tlb(self, addr): mmu_idx = 0 - index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1) - tlb_entry = self.env['tlb_table'][mmu_idx][index] - if tlb_entry['addend'] == -1: + table, size = self.get_tlb_fast(mmu_idx) + index = (addr >> TARGET_PAGE_BITS) & (size - 1) + tlb_entry = table[index] + if int(tlb_entry['addr_read']) & TARGET_PAGE_MASK != addr & TARGET_PAGE_MASK: raise Exception('Address %x is not mapped' % addr) # TODO: check if we run in S2E mode or not @@ -212,20 +221,21 @@ def read_memory(self, vaddr, count): return read_virt_memory(cr0, cr3, vaddr, count) def dump_tlb(self): - tlb_table = self._env['tlb_table'] - for i in range(0, CPU_TLB_SIZE): - tlb_entry = tlb_table[0][i] - if tlb_entry['addend'] == -1: - continue - - line = '0x{0:02x} read=0x{1:08x} write=0x{2:08x} code=0x{3:08x} addend=0x{4:x}'.format( - i, int(tlb_entry['addr_read']), - int(tlb_entry['addr_write']), - int(tlb_entry['addr_code']), - int(tlb_entry['addend']) - ) - - print(line) + for mmu_idx in range(0, NB_MMU_MODES): + table, size = self.get_tlb_fast(mmu_idx) + for i in range(0, size): + tlb_entry = table[i] + if tlb_entry['addend'] == -1: + continue + + line = '{0} 0x{1:03x} read=0x{2:08x} write=0x{3:08x} code=0x{4:08x} addend=0x{5:x}'.format( + mmu_idx, i, int(tlb_entry['addr_read']), + int(tlb_entry['addr_write']), + int(tlb_entry['addr_code']), + int(tlb_entry['addend']) + ) + + print(line) def dump_regs(self): print('eip=%#010x (%#010x)' % (self.pc, self.pc_linear)) From 13db525775417208d277603ca84372b39a53199f Mon Sep 17 00:00:00 2001 From: Vitaly Chipounov Date: Sun, 18 Oct 2026 17:23:57 +0200 Subject: [PATCH 52/52] libcpu: updated the porting plans for the landed softmmu softmmu-update.md is marked as landed and records the remaining deviations from the plan. PORTING.md marks the softmmu work of phases 1, 2, 4 and 6 as done and describes the flag allocation that was used. tlb-update.md notes that the cputlb.c import has landed. Co-Authored-By: Claude Opus 5.5 --- libcpu/PORTING.md | 112 +++++++++++++++++++++------------------ libcpu/softmmu-update.md | 26 ++++++--- libcpu/tlb-update.md | 5 ++ 3 files changed, 85 insertions(+), 58 deletions(-) diff --git a/libcpu/PORTING.md b/libcpu/PORTING.md index d2327faf3..9b4eccade 100644 --- a/libcpu/PORTING.md +++ b/libcpu/PORTING.md @@ -7,9 +7,10 @@ KVM-shim architecture and leaving symbolic execution to land on top afterwards. Measured against `~/softs/qemu` at `v11.1.0` and this tree at `9982579d`. Work that has landed since is marked **Done** in the phase it belongs to; the state -management half of the TLB work (`tlb-update.md`) and the move of the -execution fields out of `CPUX86State` are in, so phases 1, 2 and 4 are -lighter than the estimates below. +management half of the TLB work (`tlb-update.md`), the move of the +execution fields out of `CPUX86State`, and the replacement of the softmmu with +upstream's `cputlb.c` (`softmmu-update.md`) are in, so phases 1, 2, 4 and 6 +are lighter than the estimates below. | | | |---|---| @@ -401,8 +402,12 @@ codebase. - Write the memory shim: upstream's `iotlb_to_section`, `memory_region_dispatch_*`, `qemu_ram_addr_from_host*` and the dirty-tracking predicates, expressed over `MemoryDesc` and `exec-ram.h`. + Done for what `cputlb.c` needs: `cpu/memory.h` defines `MemoryRegion` and + `MemoryRegionSection` over `MemoryDesc`, and `src/s2e/cputlb-deps.h` + implements the memory API and dirty tracking on top of them. - Write the stub headers: BQL, icount, replay, plugins, `tcg_enabled()`, - target-info. + target-info. Done for `cputlb.c`, in `src/s2e/cputlb-deps.h`. The other + imported files will need more of them. **Exit:** the substrate compiles standalone against libtcg. A small unit test drives qht insert/lookup/remove/resize. @@ -416,18 +421,23 @@ drives qht insert/lookup/remove/resize. `ldst_common.c.inc`, `ldst_atomicity.c.inc`, and the atomic helpers `atomic_common.c.inc` / `atomic_template.h` that `cputlb.c` pulls in (`tcg-runtime*` already lives in libtcg). + Done for the softmmu (`softmmu-update.md`): `cputlb.c`, `tlb-bounds.h`, + `ldst_common.c.inc`, `ldst_atomicity.c.inc`, `atomic_common.c.inc` and + `atomic_template.h` are imported. `internal-common.h` and `backend-ldst.h` + are not: `src/s2e/cputlb-deps.h` provides the little that `cputlb.c` uses + from them. `watchpoint.c` is not imported either, and `exec-bp.c` implements + the two functions `cputlb.c` calls. - Rewrite the eight `MemoryRegion` touch points in `cputlb.c` against the phase 1 - shim. -- Apply the TLB decisions from section 9: disable the victim TLB, move S2E's flag - bits into `slow_flags[]`, and move `objectState` into `CPUTLBEntryFull`. - `tlb-update.md` has landed, so the ownership half of this is done and - `cputlb.c` imports without S2E-side surprises. Bring - `libtcg/include/tcg/tlb.h` forward to the 11.1 flag scheme at the same time. It - is an S2E-original that was never upgraded and still describes the pre-11.1 - bit allocation. -- Delete `cpu-exec.c`, `exec.c`, `exec-tb.c`, `exec-tlb.c`, `exec-phystb.c`, - `exec-bp.c`, `translate-all.c`, `softmmu_*.h`, `cpu-all.h`, `cpu-defs.h`, - `exec-all.h`. + shim. Done differently: `cputlb.c` keeps upstream's text, and the shim + provides the memory API it calls. +- Apply the TLB decisions from section 9: disable the victim TLB, give S2E's + flags their own bits, and move `objectState` into `CPUTLBEntryFull`. Done. + The flags went into the comparator rather than into `slow_flags[]` (see 9.6). + `libtcg/include/tcg/tlb.h` is gone: `tlb-common.h` and `tlb-flags.h` + replace it. +- Delete `cpu-exec.c`, `exec.c`, `exec-tb.c`, `exec-phystb.c`, `exec-bp.c`, + `translate-all.c`, `cpu-all.h`, `cpu-defs.h`, `exec-all.h`. `exec-tlb.c` and + `softmmu_*.h` are already gone. - Reconcile `libtcg/include/tcg/tb.h` with upstream's `TranslationBlock`: the S2E copy has drifted (it still carries `phys_hash_next` and `page_next` from the pre-qht era, alongside 11.1's `jmp_*` fields). @@ -483,15 +493,16 @@ off, in both release and debug trees. restore because it belongs to the host call stack doing the switch. What remains here is renaming the S2E-only fields upstream does not have (`current_tb`, `se_current_tb`, `translate_single_instruction`, - `se_tb_abort`, `generate_llvm`, `mem_io_vaddr`) onto their 11.1 - equivalents where one exists (`cflags_next_tb`, `tcg_tb_lookup()`). + `se_tb_abort`, `generate_llvm`) onto their 11.1 equivalents where one + exists (`cflags_next_tb`, `tcg_tb_lookup()`). `mem_io_vaddr` is already + gone: upstream's softmmu passes the address directly. - Map libcpu's exit reasons onto `kvm_run` as before; `cpu_x86_exec()` keeps its shape, `cpu_exec()` gains upstream's `cpu_exec_setjmp` structure. - Re-derive `cpu_get_pic_interrupt()`, `do_cpu_init()`, `cpu_state_reset()` against the new state layout, including `cpu_init_fp_statuses()`, which must run after every reset memset. -- Done: the TLB, `se_ram_tlb`, `se_tlb_current` and `tb_jmp_cache` are out of - the snapshotted region and flushed in `doStateSwitch()` after the new state +- Done: the TLB, `se_ram_tlb` and `tb_jmp_cache` are out of the snapshotted + region and flushed in `doStateSwitch()` after the new state is activated and `g_se_disable_tlb_flush` is cleared. Still open: collapsing the per-state `S2EExecutionStateTlb` into executor-owned data; today the class stays per state and asserts that an inactive state's map is empty. @@ -534,12 +545,15 @@ against a recorded trace from the pre-port build. `env->field` access inside a helper translation unit. - Re-add the symbolic softmmu: the `TLB_SYMB` / `TLB_NOT_OURS` / `TLB_MEM_TRACE` paths, `objectState` plumbing, and `g_sqi.mem.*` hooks, now inside upstream's - `do_ld_mmu` / `do_st_mmu` rather than `softmmu_template.h`. + `do_ld_mmu` / `do_st_mmu` rather than `softmmu_template.h`. Done, on the + current tree, ahead of the other phases (`softmmu-update.md`). - Rebuild the bitcode target. `op_helper.c` was one translation unit compiled to `op_helper.bc`; upstream's helpers are twelve files, so either `llvm-link` them - all or add a unity `.c` that includes them. Note the ld/st helper names - changed upstream (the 32-bit load is `helper_ldul_mmu`); the KLEE-side - handlers and handler tables must follow. + all or add a unity `.c` that includes them. The ld/st helpers already have + upstream's names, and `cputlb.c` is already compiled to bitcode and linked + into `op_helper.bc`. The phase 3 helpers pass `GETPC()` to the softmmu, so + `se_mmu_resolve()` will select `switch_to_symbolic()` for them + (`softmmu-update.md` hazard 5.6). - Check `tcg-llvm.cpp`'s opcode switch against 11.1's `tcg-opc.h`, and re-verify the `se_addend` / `fast_concrete_invocation` invariants end to end. Keep in mind `se_addend` is a native-execution concern only: the bitcode softmmu path @@ -882,31 +896,27 @@ rather than an allocator hook. The same argument then carried the rest of ### 9.6 What still has to be pinned or checked -Nothing about the TLB size remains open. What remains from the earlier -analysis: - -- **S2E's flags go in `CPUTLBEntryFull.slow_flags[]`** (bits 5, 6, 7 are free, - exactly the three S2E needs; `TLB_MMIO` moved into the slow set at bit 4, - which is why only three remain), driven by `TLB_FORCE_SLOW`. No new fast-path - bit, no change to `TLB_FLAGS_MASK`, no codegen change. `softmmu_header.h` and - the KLEE-side handlers change from testing `tlb_entry->addr_read & TLB_SYMB` - to `full->slow_flags[MMU_DATA_LOAD] & TLB_SYMB`. -- **`se_addend` stays in `CPUTLBEntry`** (the backend loads it inline on the hit - path); **`objectState` moves to `CPUTLBEntryFull`** (only the helpers read it). - `CPUTLBEntry` becomes upstream's union, including `addr_idx[]`, whose layout - `tlb_read_idx()` asserts. -- **`NB_MMU_MODES`**: x86 uses 8 against S2E's 2. This no longer costs snapshot - bytes, but it still multiplies `tlb_init()` allocations and the - `clearTlbOwnership` / `audit` sweeps. Declare it as x86's 8 rather than - inheriting upstream's 22-mode maximum. -- **The `CPUTLBDescFast` index convention** must match between libtcg's - `tlb_mask_table_ofs()` and upstream's `mmuidx_to_fast_index()`. See section 8. -- **`se_tlb_current`** is a cached `CPUTLBEntry *`, written by the softmmu IO - path and read from bitcode. It now sits next to the TLB in - `CPUNegativeOffsetState`, so it lives and dies with the tables; under the - arena option it would still have to be rebased or demoted to an index when - the in-use sub-range changes. -- **`libtcg/include/tcg/tlb.h`** is an S2E-original that was never brought - forward and still describes the pre-11.1 flag scheme (including `TLB_RECHECK`, - removed upstream in 4.1, and a `TLB_FLAGS_MASK` that omits `TLB_MEM_TRACE`). - It has to be fixed regardless of anything else here. +The softmmu replacement (`softmmu-update.md`) settled most of this section: + +- **S2E's flags.** `TLB_SYMB`, `TLB_NOT_OURS` and `TLB_MEM_TRACE` are bits 9 to + 11 of the comparator, inside `TLB_FLAGS_MASK`. They cannot go in + `slow_flags[]`: the lookup merges the slow flags with the comparator flags + (bits 6 to 8) into one value, which leaves only bit 5 free. That bit holds + `TLB_SYMB_MMIO`, which is known when the entry is filled. Any nonzero bit + below the page mask fails the inline compare, so the backend is unchanged. +- **`se_addend` stays in `CPUTLBEntry`**, and **`objectState` is in + `CPUTLBEntryFull`**. `CPUTLBEntry` is upstream's union, 64 bytes in symbex + builds. +- **The `CPUTLBDescFast` index convention** is not inverted: `cputlb.c` + reaches `f[]` only through `cpu_tlb_fast()` in `state.h`, which agrees with + libtcg's `tlb_mask_table_ofs()`. +- **`se_tlb_current`** and **`libtcg/include/tcg/tlb.h`** are gone. + +What remains: + +- **`NB_MMU_MODES`**: x86 uses 8 against S2E's 2. It is still 2, and + `cputlb.c` does not depend on the number, so it changes with the phase 3 + frontend. This no longer costs snapshot bytes, but it multiplies the static + tables in `CPUNegativeOffsetState` and the `clearTlbOwnership` / `audit` + sweeps. Declare it as x86's 8 rather than inheriting upstream's 22-mode + maximum. diff --git a/libcpu/softmmu-update.md b/libcpu/softmmu-update.md index 90d029129..24dc0a92a 100644 --- a/libcpu/softmmu-update.md +++ b/libcpu/softmmu-update.md @@ -14,10 +14,10 @@ kept working throughout. The reasoning is the same as for `tlb-update.md`. The softmmu is the part of `accel/tcg` most entangled with S2E, so it is easier to validate on a tree that still boots than in the middle of the larger import. -**Status: implemented, not validated.** Steps 1 to 4 are in the tree and all -six targets build. No guest has been booted on it yet, so the exit criteria of -step 3 are still open. The code differs from the plan below in the following -places. Where the two disagree, the code is the reference. +**Status: landed.** Steps 1 to 4 are in the tree, all six targets build, and +guests boot and pass the testsuite on them. The code differs from the plan +below in the following places. Where the two disagree, the code is the +reference. - **Memory model (deviation 1).** `cputlb.c` keeps upstream's text for the memory API. `cpu/memory.h` defines a small `MemoryRegion` and @@ -66,7 +66,19 @@ places. Where the two disagree, the code is the reference. symbolic hardware. - **Hazard 5.3.** `required_atomicity()` is not redirected. `cputlb.c` only reaches it through `load_atom_N()` and `store_atom_N()`, which are. The - 16-byte entry points stay in the bitcode build. + 16-byte entry points stay in the bitcode build. A 16-byte access to a RAM + page runs in bitcode. One to a device page calls the native + `do_ld16_mmio_beN()` or `do_st16_mmio_leN()`. They are not registered with + KLEE, which cannot pass their `Int128` to native code, so KLEE stops with an + error if a guest reaches them. `tcg-llvm.cpp` aborts on a 128-bit memory + operation. +- **Hazard 5.1.** The existing assertion on `sizeof(CPUTLBEntry)` also + catches `se_addend` not fitting in the entry. Every user of the field goes + through its name or `offsetof()`, so there is no separate assertion. +- **Probes.** `x86_cpu_tlb_fill()` calls `cpu_abort()` when a probe faults. + `cpu_x86_handle_mmu_fault()` records the fault in CR2 (or the VMCB) before + it returns, which a probe must not do. Nothing probes yet. The phase 3 + frontend replaces the page walk. - **Bitcode build.** Five `#ifndef SYMBEX_LLVM_LIB` regions remove the native-only code, and `SE_TCG_OPS()` / `SE_TCG_OP()` select the bitcode copies of the target hooks. @@ -79,8 +91,8 @@ places. Where the two disagree, the code is the reference. the map references. - **Step 4.** The static translator code was dead and has been removed (`tools/include/Translator/` and every `STATIC_TRANSLATOR` conditional). - The `ld*_raw_symb` accessors in `cpu-all.h` are still there, unused. - `PORTING.md` and `tlb-update.md` have not been updated yet. + Removing the `ld*_raw_symb` accessors also removed their only use of + `g_sqi.mem.read_ram_concrete_check`, which is gone from the interface. ## 1. The softmmu today diff --git a/libcpu/tlb-update.md b/libcpu/tlb-update.md index d7468761a..8dc8567a4 100644 --- a/libcpu/tlb-update.md +++ b/libcpu/tlb-update.md @@ -393,3 +393,8 @@ otherwise have to be debugged simultaneously with a 43k-line import. After this lands, `PORTING.md` phase 2's TLB work reduces to importing `cputlb.c` and mapping `CPUTLBEntryFull` onto `MemoryDesc`, with the state management already in the shape the imported code expects. + +That import has landed (`softmmu-update.md`). It brought upstream's +`CPUTLBEntryFull`, flag allocation and dynamic sizing code, with the size +pinned to `CPU_TLB_SIZE` entries and the victim TLB disabled. `NB_MMU_MODES` +is still 2.