diff --git a/.github/workflows/catkin_2.yml b/.github/workflows/catkin_2.yml index 8ad5adba..1b6f59b3 100644 --- a/.github/workflows/catkin_2.yml +++ b/.github/workflows/catkin_2.yml @@ -10,7 +10,8 @@ jobs: container: ros:noetic-ros-base-focal runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + - run: rm -Rf ariles2_ros2param_catkin - run: | source /opt/ros/noetic/setup.bash make catkin_test_old ROS_DISTRO=noetic UBUNTU_DISTRO=focal @@ -19,7 +20,7 @@ jobs: container: ros:noetic-ros-base-focal runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: | source /opt/ros/noetic/setup.bash make catkin_test_new ROS_DISTRO=noetic UBUNTU_DISTRO=focal @@ -27,9 +28,23 @@ jobs: prerelease: runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 + - run: rm -Rf ariles2_ros2param_catkin - run: make ros_prerelease ROS_DISTRO=noetic UBUNTU_DISTRO=focal BRANCH=`git branch --show-current` env: CCACHE_DIR: ${GITHUB_WORKSPACE}/.ccache + + jammy_ccws: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + with: + repository: asherikov/ccws + - uses: actions/checkout@v4 + with: + path: src/ariles_catkin + - run: make bp_install_build BUILD_PROFILE=reldebug + - run: make dep_install PKG=ariles2_ros2param_catkin + - run: make ariles2_ros2param_catkin diff --git a/.make/ariles.mk b/.make/ariles.mk index 7c599e0f..86784a2d 100644 --- a/.make/ariles.mk +++ b/.make/ariles.mk @@ -5,7 +5,7 @@ VERSION?="XXX__version_not_set__XXX" REPO=https://github.com/asherikov/ariles.git DEPENDENCY_PATH=./demo -DEBIAN_SYSTEM_DEPENDENCIES=libeigen3-dev octave libyaml-cpp-dev rapidjson-dev libpugixml-dev +DEBIAN_SYSTEM_DEPENDENCIES=libeigen3-dev octave libyaml-cpp-dev rapidjson-dev libpugixml-dev libboost-all-dev update: diff --git a/.make/ros.mk b/.make/ros.mk index cbad44ed..c6532535 100644 --- a/.make/ros.mk +++ b/.make/ros.mk @@ -143,6 +143,7 @@ catkin_test_new: ros_install_deps ros_prerelease_deps: sudo ${MAKE} ros_add_repos UBUNTU_DISTRO=${UBUNTU_DISTRO} + ${PIP_INSTALL} empy==3.3.4 ${PIP_INSTALL} ros_buildfarm ros_prerelease: ros_prerelease_deps diff --git a/README.md b/README.md index 73fd8aef..812258aa 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,11 @@ This is a proxy catkin package for Ariles serialization/configuration library, see https://github.com/asherikov/ariles for more information. -Enabled data formats: +Available data formats: - yaml - json - ROS parameter server +- ROS2 parameters - Octave script (output) - array (flattened key-value pairs) diff --git a/ariles/.travis.yml.disable b/ariles/.travis.yml.disable deleted file mode 100644 index dc070c66..00000000 --- a/ariles/.travis.yml.disable +++ /dev/null @@ -1,251 +0,0 @@ -language: cpp - -notifications: - email: - recipients: - - asherikov@yandex.com - on_success: always - on_failure: always - -services: - - docker -os: linux - - -jobs: - include: - -# special cases - - name: "test_cmake" - dist: xenial - compiler: gcc - before_install: - - sudo apt update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y octave libpugixml-dev libyaml-cpp-dev - script: - - sudo make install-jsonnet - - make test-cmake - - - - name: "deb_packages" - dist: xenial - compiler: gcc - - env: - - ROS_DISTRO=kinetic - - CI_SOURCE_PATH=$(pwd) - - ROS_CI_DESKTOP=${TRAVIS_DIST} - - ROSINSTALL_FILE=$CI_SOURCE_PATH/dependencies.rosinstall - - CATKIN_OPTIONS=$CI_SOURCE_PATH/catkin.options - # Set the python path manually to include /usr/-/python2.7/dist-packages - # as this is where apt-get installs python packages. - - PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages - - # Install system dependencies, namely a very barebones ROS setup. - before_install: - - sudo make install-ros ROS_DISTRO=$ROS_DISTRO UBUNTU_DISTRO=$ROS_CI_DESKTOP - - source /opt/ros/${ROS_DISTRO}/setup.bash - - rosdep update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y devscripts build-essential octave libpugixml-dev libyaml-cpp-dev fakeroot rapidjson-dev - - sudo apt install -y libprotobuf-dev protobuf-compiler - - script: - - sudo make install-jsonnet - - make deb-build DEB_TARGET=${TRAVIS_DIST} - - make deb-install DEB_TARGET=${TRAVIS_DIST} - - make cmake_dependency - - - name: "bionic_deb_packages" - dist: bionic - compiler: gcc - - env: - - ROS_DISTRO=melodic - - CI_SOURCE_PATH=$(pwd) - - ROS_CI_DESKTOP=${TRAVIS_DIST} - - ROSINSTALL_FILE=$CI_SOURCE_PATH/dependencies.rosinstall - - CATKIN_OPTIONS=$CI_SOURCE_PATH/catkin.options - # Set the python path manually to include /usr/-/python2.7/dist-packages - # as this is where apt-get installs python packages. - - PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages - - # Install system dependencies, namely a very barebones ROS setup. - before_install: - - sudo make install-ros ROS_DISTRO=$ROS_DISTRO UBUNTU_DISTRO=$ROS_CI_DESKTOP - - source /opt/ros/${ROS_DISTRO}/setup.bash - - rosdep update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y devscripts build-essential octave libpugixml-dev libyaml-cpp-dev fakeroot rapidjson-dev libmsgpack-dev - - sudo apt install -y libprotobuf-dev protobuf-compiler - - script: - - sudo make install-jsonnet - - make deb-build DEB_TARGET=${TRAVIS_DIST} - - make deb-install DEB_TARGET=${TRAVIS_DIST} - - make cmake_dependency - - - - name: "gcc_cpp11_noros" - dist: xenial - compiler: gcc - before_install: - - sudo apt update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y octave libpugixml-dev libyaml-cpp-dev graphviz - - sudo apt install -y libprotobuf-dev protobuf-compiler - script: - - sudo make install-jsonnet - - make build-tests TYPE=Debug OPTIONS=cpp11_on_noros_${TRAVIS_DIST} TARGETS="all" ARGS=-V - - - name: "clang_cpp11_noros" - dist: xenial - compiler: clang - before_install: - - sudo apt update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y octave libpugixml-dev libyaml-cpp-dev graphviz - - sudo apt install -y libprotobuf-dev protobuf-compiler - script: - - sudo make install-jsonnet - - make build-tests TYPE=Debug OPTIONS=cpp11_on_noros_${TRAVIS_DIST} TARGETS="all" ARGS=-V - - - name: "bionic_gcc_cpp11_noros" - dist: bionic - compiler: gcc - before_install: - - sudo apt update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y octave libpugixml-dev libyaml-cpp-dev rapidjson-dev libmsgpack-dev graphviz - - sudo apt install -y libprotobuf-dev protobuf-compiler - - script: - - sudo make install-jsonnet - - make build-tests TYPE=Debug OPTIONS=cpp11_on_noros_${TRAVIS_DIST} TARGETS="all" ARGS=-V - - - # based on https://github.com/felixduvallet/ros-travis-integration/blob/master/.travis.yml - - name: "gcc_cpp11_ros" - dist: xenial - compiler: gcc - - env: - - ROS_DISTRO=kinetic - - CI_SOURCE_PATH=$(pwd) - - ROS_CI_DESKTOP=${TRAVIS_DIST} - - ROSINSTALL_FILE=$CI_SOURCE_PATH/dependencies.rosinstall - - CATKIN_OPTIONS=$CI_SOURCE_PATH/catkin.options - # Set the python path manually to include /usr/-/python2.7/dist-packages - # as this is where apt-get installs python packages. - - PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages - - # Install system dependencies, namely a very barebones ROS setup. - before_install: - - sudo make install-ros ROS_DISTRO=$ROS_DISTRO UBUNTU_DISTRO=$ROS_CI_DESKTOP - - source /opt/ros/${ROS_DISTRO}/setup.bash - - rosdep update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y libyaml-cpp-dev octave graphviz - - sudo apt install -y libprotobuf-dev protobuf-compiler - - script: - - sudo make install-jsonnet - - make build-tests TYPE=Debug OPTIONS=ros TARGETS="all" ARGS=-V - - - name: "clang_cpp11_ros" - dist: xenial - compiler: clang - - env: - - ROS_DISTRO=kinetic - - CI_SOURCE_PATH=$(pwd) - - ROS_CI_DESKTOP=${TRAVIS_DIST} - - ROSINSTALL_FILE=$CI_SOURCE_PATH/dependencies.rosinstall - - CATKIN_OPTIONS=$CI_SOURCE_PATH/catkin.options - # Set the python path manually to include /usr/-/python2.7/dist-packages - # as this is where apt-get installs python packages. - - PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages - - # Install system dependencies, namely a very barebones ROS setup. - before_install: - - sudo make install-ros ROS_DISTRO=$ROS_DISTRO UBUNTU_DISTRO=$ROS_CI_DESKTOP - - source /opt/ros/${ROS_DISTRO}/setup.bash - - rosdep update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y libyaml-cpp-dev octave graphviz - - sudo apt install -y libprotobuf-dev protobuf-compiler - - script: - - sudo make install-jsonnet - - make build-tests TYPE=Debug OPTIONS=ros TARGETS="all" ARGS=-V - - - name: "bionic_gcc_cpp11_ros" - dist: bionic - compiler: gcc - - env: - - ROS_DISTRO=melodic - - CI_SOURCE_PATH=$(pwd) - - ROS_CI_DESKTOP=${TRAVIS_DIST} - - ROSINSTALL_FILE=$CI_SOURCE_PATH/dependencies.rosinstall - - CATKIN_OPTIONS=$CI_SOURCE_PATH/catkin.options - # Set the python path manually to include /usr/-/python2.7/dist-packages - # as this is where apt-get installs python packages. - - PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages - - # Install system dependencies, namely a very barebones ROS setup. - before_install: - - sudo make install-ros ROS_DISTRO=$ROS_DISTRO UBUNTU_DISTRO=$ROS_CI_DESKTOP - - source /opt/ros/${ROS_DISTRO}/setup.bash - - rosdep update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y libyaml-cpp-dev octave graphviz - - sudo apt install -y libprotobuf-dev protobuf-compiler - - script: - - sudo make install-jsonnet - - make build-tests TYPE=Debug OPTIONS=ros TARGETS="all" ARGS=-V - - - - name: "bionic_static_checks" - dist: bionic - compiler: gcc - - before_install: - - sudo apt update - - sudo apt install -y cppcheck - - sudo apt install -y python3-pip python3-setuptools - - sudo pip3 install scspell3k - - script: - - make cppcheck - - make spell - - - name: "bionic_gcc_cpp11_ros_scanbuild" - dist: bionic - compiler: gcc - - env: - - ROS_DISTRO=melodic - - CI_SOURCE_PATH=$(pwd) - - ROS_CI_DESKTOP=${TRAVIS_DIST} - - ROSINSTALL_FILE=$CI_SOURCE_PATH/dependencies.rosinstall - - CATKIN_OPTIONS=$CI_SOURCE_PATH/catkin.options - # Set the python path manually to include /usr/-/python2.7/dist-packages - # as this is where apt-get installs python packages. - - PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages - - # Install system dependencies, namely a very barebones ROS setup. - before_install: - - sudo make install-ros ROS_DISTRO=$ROS_DISTRO UBUNTU_DISTRO=$ROS_CI_DESKTOP - - source /opt/ros/${ROS_DISTRO}/setup.bash - - rosdep update - - sudo apt install -y cmake libboost-all-dev libeigen3-dev - - sudo apt install -y libyaml-cpp-dev octave - - sudo apt install -y clang-tools-9 - - sudo apt install -y libprotobuf-dev protobuf-compiler - - script: - - sudo make install-jsonnet - - make clangcheck SCANBUILD=scan-build-9 OPTIONS=ros diff --git a/ariles/CHANGELOG.md b/ariles/CHANGELOG.md index b6c0ffd6..0405c187 100644 --- a/ariles/CHANGELOG.md +++ b/ariles/CHANGELOG.md @@ -1,13 +1,42 @@ CHANGELOG ========= -Unreleased -========== +2.2.0 +===== + +Added +----- +* aggregate visitor: container for multiple visitors applied sequentially. +* ros2param visitor: ROS2 parameters support. + +Changed +------- +* Switched to C++17. +* Disable sanitizers: broken in Ubuntu, a workaround needed. + +Fixed +----- +* Matrix reading logic. +* Exception messages. +* Null pointer handling. + +Removed +------- +* `ARILES_CPP_STANDARD` cmake option. +* `ARILES2_INCLUDED` define. + + +2.1.0 +===== Added ----- * Writers now take `allow_missing_entries_` parameter into account, omitting 'missing' entries, e.g., null pointers. +* Searching for `yaml-cpp` and `msgpack` with `find_package()`. +* `ARILES_CPP_STANDARD` cmake flag. +* `ariles::write::Parameters`: +`allow_missing_entries_` +* `OptionalPointer` wrapper class for pointers that can be NULL if entry is missing. Removed ------- diff --git a/ariles/CMakeLists.txt b/ariles/CMakeLists.txt index 9fd3cb7f..7bee7331 100644 --- a/ariles/CMakeLists.txt +++ b/ariles/CMakeLists.txt @@ -1,6 +1,6 @@ # General parameters -cmake_minimum_required (VERSION 3.0.0) -project(ariles2 VERSION 2.0.3) +cmake_minimum_required (VERSION 3.1.0) +project(ariles2 VERSION 2.2.0) set(ARILES_HOMEPAGE http://asherikov.github.io/ariles/2) @@ -209,10 +209,12 @@ set(CMAKEUT_CPP_SANITIZERS ${ARILES_CPP_SANITIZERS}) set(CMAKEUT_CLANG_TIDY ${ARILES_CPP_CLANG_TIDY}) set(CMAKEUT_CLANG_TIDY_EXTRA_IGNORES "-cppcoreguidelines-special-member-functions,-hicpp-special-member-functions,-altera-struct-pack-align,-llvm-namespace-comment,-misc-no-recursion,-readability-const-return-type,-google-default-arguments,-bugprone-macro-parentheses,-cppcoreguidelines-pro-type-union-access,-hicpp-named-parameter,-readability-named-parameter,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-cppcoreguidelines-pro-type-union-access,-cppcoreguidelines-avoid-non-const-global-variables,-cert-err58-cpp,-cert-env33-c") -cmakeut_compiler_flags("c++11") +set(CMAKE_CXX_STANDARD "17") +cmakeut_compiler_flags("c++${CMAKE_CXX_STANDARD}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKEUT_CXX_FLAGS}") + set (RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") set (LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") set (ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") @@ -277,6 +279,7 @@ if (${ARILES_ENABLE_CORE}) "$" "$" ) + target_compile_features(${PROJECT_NAME}-core INTERFACE "cxx_std_${CMAKE_CXX_STANDARD}") # -------------- @@ -311,16 +314,6 @@ if (${ARILES_ENABLE_CORE}) # -------------- - # -------------- - # cpput - # -------------- - set(CPPUT_EMBEDDED ON CACHE BOOL "" FORCE) - set(CPPUT_EMBEDDED_ID "ARILES2" CACHE STRING "" FORCE) - set(CPPUT_EMBEDDED_COPY_TO_DIR "${ARILES_CORE_BUILD_INCLUDES}/${PROJECT_NAME}/internal/" CACHE STRING "" FORCE) - set(CPPUT_SELECT_HEADERS "config.h;exception.h;visibility.h;misc.h;trace.h" CACHE STRING "" FORCE) - add_subdirectory(cpput) - # -------------- - list(APPEND DEB_ARCHIVE_FILES "./include" "./extra_adapters") diff --git a/ariles/Makefile b/ariles/Makefile index 89e12737..0e5490cd 100644 --- a/ariles/Makefile +++ b/ariles/Makefile @@ -1,5 +1,5 @@ APT_INSTALL?=env DEBIAN_FRONTEND=noninteractive apt --yes --no-install-recommends install -MAKE_FLAGS?=-j7 +MAKE_FLAGS?=-j14 CMAKE_DIR=./cmake/ @@ -140,9 +140,14 @@ test-ros: clean ${MAKE} build-tests TC=${TC} TYPE=Debug OPTIONS=ros TARGETS="${TARGETS}" EXTRA_CMAKE_PARAM="${EXTRA_CMAKE_PARAM}" +test-ros2: clean + #${MAKE} build-tests TC=${TC} TYPE=Debug OPTIONS=default TARGETS="${TARGETS}" EXTRA_CMAKE_PARAM="${EXTRA_CMAKE_PARAM}" + ${MAKE} build-tests TC=${TC} TYPE=Debug OPTIONS=ros2 TARGETS="${TARGETS}" EXTRA_CMAKE_PARAM="${EXTRA_CMAKE_PARAM}" + + test-noros: clean - ${MAKE} build-tests TC=${TC} TYPE=Debug OPTIONS=cpp11_on_noros TARGETS="${TARGETS}" EXTRA_CMAKE_PARAM="${EXTRA_CMAKE_PARAM}" - ${MAKE} clangcheck SCANBUILD=scan-build11 OPTIONS=cpp11_on_noros_tidy + ${MAKE} build-tests TC=${TC} TYPE=Debug OPTIONS=noros TARGETS="${TARGETS}" EXTRA_CMAKE_PARAM="${EXTRA_CMAKE_PARAM}" + ${MAKE} clangcheck SCANBUILD=scan-build18 OPTIONS=noros_tidy ${MAKE} cppcheck ${MAKE} spell @@ -152,18 +157,21 @@ test-noros: clean #---------------------------------------------- addutils: - git remote add --no-tags cmakeut https://github.com/asherikov/cmakeut - git remote add --no-tags cpput https://github.com/asherikov/cpput + -git remote add --no-tags cmakeut https://github.com/asherikov/cmakeut + -git remote add --no-tags cpput https://github.com/asherikov/cpput -updateutils: +updateutils: addutils git fetch --all - git show remotes/cmakeut/master:cmake/FindEigen3.cmake > cmake/FindEigen3.cmake - git show remotes/cmakeut/master:cmake/cmakeut_compiler_flags.cmake > cmake/cmakeut_compiler_flags.cmake - git show remotes/cmakeut/master:cmake/cmakeut_dump_variables.cmake > cmake/cmakeut_dump_variables.cmake - git show remotes/cmakeut/master:cmake/cmakeut_list_filenames.cmake > cmake/cmakeut_list_filenames.cmake - git rm --ignore-unmatch -rf cpput - git read-tree --prefix=cpput -u cpput/master - git rm --ignore-unmatch -rf cpput/package.xml + git show remotes/cmakeut/master:cmake/FindEigen3.cmake > cmake/FindEigen3.cmake + git show remotes/cmakeut/master:cmake/cmakeut_compiler_flags.cmake > cmake/cmakeut_compiler_flags.cmake + git show remotes/cmakeut/master:cmake/cmakeut_dump_variables.cmake > cmake/cmakeut_dump_variables.cmake + git show remotes/cmakeut/master:cmake/cmakeut_list_filenames.cmake > cmake/cmakeut_list_filenames.cmake + # + git show remotes/cpput/master:include/cpput/exception.h > include/ariles2/internal/exception.h + git show remotes/cpput/master:include/cpput/visibility.h > include/ariles2/internal/visibility.h + git show remotes/cpput/master:include/cpput/misc.h > include/ariles2/internal/misc.h + git show remotes/cpput/master:include/cpput/trace.h > include/ariles2/internal/trace.h + git show remotes/cpput/master:include/cpput/concat.h > include/ariles2/internal/concat.h update: @@ -179,27 +187,25 @@ dox: doxclean clean install-ros: - sh -c "echo \"deb http://packages.ros.org/ros/ubuntu ${UBUNTU_DISTRO} main\" > /etc/apt/sources.list.d/ros-latest.list" - sh -c "apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654 \ - || apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654 \ - || apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654" - sh -c "apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key 6B05F25D762E3157 \ - || apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key 6B05F25D762E3157 \ - || apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key 6B05F25D762E3157" - apt update -qq - ${APT_INSTALL} dpkg - ${APT_INSTALL} ros-${ROS_DISTRO}-ros-base + wget -qO- https://raw.githubusercontent.com/ros/rosdistro/master/ros.asc | sudo tee /etc/apt/trusted.gpg.d/ros.asc ${MAKE} install-ros-${ROS_DISTRO} + ${APT_INSTALL} dpkg + ${APT_INSTALL} python3-rosdep python3-rosinstall python3-rosinstall-generator build-essential bash -c 'source /opt/ros/${ROS_DISTRO}/setup.bash; rosdep init' + rosdep update -install-ros-%: - ${APT_INSTALL} python3-rosdep python3-rosinstall python3-rosinstall-generator python3-wstool build-essential +install-ros-noetic: + sh -c 'test -f /etc/apt/sources.list.d/ros-latest.list \ + || (echo "deb http://packages.ros.org/ros/ubuntu ${UBUNTU_DISTRO} main" > /etc/apt/sources.list.d/ros-latest.list)' + apt update -qq + ${APT_INSTALL} ros-${ROS_DISTRO}-ros-base -install-ros-melodic: install-ros-kinetic - # +install-ros-humble: + sh -c 'test -f /etc/apt/sources.list.d/ros2-latest.list \ + || (echo "deb [arch=amd64,arm64] http://repo.ros2.org/ubuntu/main ${UBUNTU_DISTRO} main" > /etc/apt/sources.list.d/ros2-latest.list)' + apt update -qq + ${APT_INSTALL} ros-${ROS_DISTRO}-rclcpp -install-ros-kinetic: - ${APT_INSTALL} python-rosdep python-rosinstall python-rosinstall-generator python-wstool build-essential install-deps: ${APT_INSTALL} cmake libboost-all-dev libeigen3-dev @@ -209,7 +215,7 @@ install-deps: format: - ${FIND_ARILES_SOURCES} | grep -v "better_enum.h" | xargs clang-format-12 -verbose -i + ${FIND_ARILES_SOURCES} | grep -v "better_enum.h" | xargs clang-format15 -verbose -i cppcheck: # --inconclusive @@ -231,6 +237,7 @@ cppcheck: --suppress=unknownMacro \ --suppress=constStatement \ --suppress=unsignedLessThanZero \ + --suppress=duplInheritedMember \ -i build \ -i tests/api_v2/regression_test_230.cpp \ 3>&1 1>&2 2>&3 | tee cppcheck.err @@ -264,7 +271,6 @@ clangcheck: -enable-checker core.uninitialized.UndefReturn \ -enable-checker cplusplus.InnerPointer \ -enable-checker cplusplus.Move \ - -enable-checker cplusplus.NewDelete \ -enable-checker cplusplus.NewDeleteLeaks \ -enable-checker deadcode.DeadStores \ -enable-checker nullability.NullPassedToNonnull \ @@ -277,7 +283,6 @@ clangcheck: -enable-checker optin.performance.GCDAntipattern \ -enable-checker optin.performance.Padding \ -enable-checker optin.portability.UnixAPI \ - -enable-checker optin.cplusplus.VirtualCall \ -enable-checker security.FloatLoopCounter \ -enable-checker security.insecureAPI.DeprecatedOrUnsafeBufferHandling \ -enable-checker security.insecureAPI.UncheckedReturn \ @@ -297,6 +302,8 @@ clangcheck: -enable-checker valist.Uninitialized \ -enable-checker valist.Unterminated \ ${MAKE} build TC=${TC} TYPE=${TYPE} OPTIONS=${OPTIONS} TARGETS="${TARGETS}" EXTRA_CMAKE_PARAM="-DBUILD_SHARED_LIBS=OFF ${EXTRA_CMAKE_PARAM}" +# -enable-checker cplusplus.NewDelete +# -enable-checker optin.cplusplus.VirtualCall spell_interactive: ${MAKE} spell SPELL_XARGS_ARG=-o @@ -308,35 +315,4 @@ spell: | grep -v "./extra_visitors/rapidjson/src/istreamwrapper.h" \ | xargs ${SPELL_XARGS_ARG} scspell --use-builtin-base-dict --override-dictionary ./qa/scspell.dict -travis-apt-clean: - -sudo rm -f \ - /etc/apt/sources.list.d/cassandra.list \ - /etc/apt/sources.list.d/cassandra.list.save \ - /etc/apt/sources.list.d/heroku-toolbelt.list \ - /etc/apt/sources.list.d/heroku-toolbelt.list.save \ - /etc/apt/sources.list.d/chris-lea-redis-server.list \ - /etc/apt/sources.list.d/chris-lea-redis-server.list.save \ - /etc/apt/sources.list.d/mongodb-3.4.list \ - /etc/apt/sources.list.d/mongodb-3.4.list.save \ - /etc/apt/sources.list.d/computology_apt-backport.list \ - /etc/apt/sources.list.d/computology_apt-backport.list.save \ - /etc/apt/sources.list.d/openjdk-r-java-ppa.list \ - /etc/apt/sources.list.d/openjdk-r-java-ppa.list.save \ - /etc/apt/sources.list.d/couchdb.list \ - /etc/apt/sources.list.d/couchdb.list.save \ - /etc/apt/sources.list.d/pgdg.list \ - /etc/apt/sources.list.d/pgdg.list.save \ - /etc/apt/sources.list.d/pollinate.list \ - /etc/apt/sources.list.d/pollinate.list.save \ - /etc/apt/sources.list.d/github_git-lfs.list \ - /etc/apt/sources.list.d/github_git-lfs.list.save \ - /etc/apt/sources.list.d/rabbitmq_rabbitmq-server.list \ - /etc/apt/sources.list.d/rabbitmq_rabbitmq-server.list.save \ - /etc/apt/sources.list.d/git-ppa.list \ - /etc/apt/sources.list.d/git-ppa.list.save \ - /etc/apt/sources.list.d/webupd8team-java-ppa.list \ - /etc/apt/sources.list.d/webupd8team-java-ppa.list.save \ - /etc/apt/sources.list.d/google-chrome.list \ - /etc/apt/sources.list.d/google-chrome.list.save - .PHONY: clean cmake build diff --git a/ariles/README.md b/ariles/README.md index e1ae250e..1cc0e6ae 100644 --- a/ariles/README.md +++ b/ariles/README.md @@ -9,7 +9,7 @@ Ariles pkg_catkin_2
- (ROS/catkin package) + (ROS/ROS2 packages) pkg_freebsd_2
@@ -66,10 +66,10 @@ Contents Links ===== -* Documentation (Doxygen): https://asherikov.github.io/ariles/2/ -* GitHub: https://github.com/asherikov/ariles -* Legacy 1.x.x version: https://github.com/asherikov/ariles/tree/head_1 - (migration guide https://asherikov.github.io/ariles/2/md_doc_migration_1to2.html) +* Documentation (Doxygen): +* GitHub: +* Legacy 1.x.x version: + (migration guide ) @@ -79,8 +79,9 @@ Introduction Loosely speaking, `ariles` is a C++ reflection library, i.e., it provides meta-programming APIs for implementation of class visitors (processors). It also provides a number of (de)serializers based on these APIs, e.g., `YAML`, -`JSON`, `XML`, `ROS` parameter server; and serialization wrappers for some -types, e.g., `STL` containers, smart pointers, `Eigen` matrices, etc. +`JSON`, `XML`, `ROS` parameter server, `ROS2` parameters; and serialization +wrappers for some types, e.g., `STL` containers, smart pointers, `Eigen` +matrices, etc. @@ -151,7 +152,10 @@ ariles2::apply("config.yaml", configurable); ariles2::apply(nh, configurable, "/some_namespace/"); ``` -See demo for more exaples: https://asherikov.github.io/ariles/2/DEMO.html +Note that ROS/ROS2 packages are available in a separate branch +. + +See demo for more exaples: [`./tests/api_v2/demo_api_v2.cpp`] @@ -164,30 +168,37 @@ Visitors representation formats, in particular: * `YAML` via `yaml-cpp`: - https://asherikov.github.io/ariles/2/group__yaml__cpp.html. + . * `msgpack` via `msgpack-c`: - https://asherikov.github.io/ariles/2/group__msgpack.html. + . * `JSON` via `RapidJSON`, with optional Jsonnet preprocessing: - https://asherikov.github.io/ariles/2/group__rapidjson.html and - https://asherikov.github.io/ariles/2/group__jsonnet.html. + and + . * `XML` via `PugiXML`: - https://asherikov.github.io/ariles/2/group__pugixml.html + * `Octave` script, output only, no dependencies: - https://asherikov.github.io/ariles/2/group__octave.html + * `ROS` parameter server, via standard `ROS` libs: - https://asherikov.github.io/ariles/2/group__ros.html + * A set of flattened key-value pairs, output only, no dependencies: - https://asherikov.github.io/ariles/2/group__namevalue.html + * `graphviz` dot files for diagram generation: - https://asherikov.github.io/ariles/2/group__graphviz.html + +* `ROS2` parameters, via standard `rclcpp` lib: + `ROS2` + parameters is not designed to fully reflect yaml structure as explained here + , so while `ariles` can dump and read + anything, there are certain workarounds in place that are described in more + details in the `ROS2` demo [`./tests/api_v2/demo_api_v2_ros2.cpp`] + . There are also a few utility visitors, e.g., @@ -197,7 +208,7 @@ There are also a few utility visitors, e.g., The complete list of modules is available at -https://asherikov.github.io/ariles/2/modules.html + @@ -211,7 +222,7 @@ Supported data types * Some STL classes (WIP): `std::string`, `std::vector`, `std::map`, `std::pair`, `std::shared_ptr`, `std::unique_ptr`. * `Eigen` types: matrices, transforms, quaternions. * `Boost` classes: `boost::optional`, `boost::movelib::unique_ptr`. `boost::shared_ptr`. -* Better enums -> https://github.com/aantron/better-enums. +* Better enums -> . @@ -222,8 +233,8 @@ Dependencies and compilation Dependencies ------------ -- `cmake` >= 3.0 -- `C++11` compatible compiler +- `cmake` >= 3.1 +- `C++17` compatible compiler - `boost` Visitors and corresponding dependencies can be enabled or disabled via cmake @@ -234,7 +245,7 @@ Compilation with catkin ----------------------- An example catkin package is provided in `pkg_catkin_2` branch of the main -repository -> https://github.com/asherikov/ariles/tree/pkg_catkin_2. +repository -> . @@ -242,24 +253,26 @@ repository -> https://github.com/asherikov/ariles/tree/pkg_catkin_2. Related software ================ -* https://github.com/PickNikRobotics/rosparam_shortcuts: a set of wrapper +* : a set of wrapper functions to read individual parameters from ROS parameter server. This tool serves pretty much the same purpose as `ariles2::rosparam::Reader`, but its functionality is more limited. -* https://billyquith.github.io/ponder/: C++14 reflection library, supports +* : C++14 reflection library, supports serialization to XML and JSON. Unlike `ariles` it is more focused on reflection per se rather than applications, for example, it allows to set value by string name of a class member, handles class methods, etc. `Ponder` does not rely as much on preprocessor macro, but is more verbose. -* https://github.com/bytemaster/boost_reflect: discontinued C++ reflection +* : discontinued C++ reflection library, similar to `ponder`. Partially inspired `ariles` 2.x.x API. -* https://github.com/apolukhin/magic_get (aka `pfr`): C++14 library providing +* (aka `pfr`): C++14 library providing tuple like methods for aggregate initializable structures. Addresses a somewhat different but related problem. * Serialization libraries, e.g., `boost::serialization`, - https://github.com/USCiLab/cereal. + . +* A library with similar functionality in C++17 + . diff --git a/ariles/cmake/cmakeut_compiler_flags.cmake b/ariles/cmake/cmakeut_compiler_flags.cmake index b4ad550b..f4640668 100644 --- a/ariles/cmake/cmakeut_compiler_flags.cmake +++ b/ariles/cmake/cmakeut_compiler_flags.cmake @@ -59,7 +59,7 @@ function(cmakeut_compiler_flags STANDARD) if (CMAKEUT_CLANG_TIDY) - find_program(CLANG_TIDY_EXECUTABLE NAMES clang-tidy clang-tidy-12 clang-tidy-14 REQUIRED) + find_program(CLANG_TIDY_EXECUTABLE NAMES clang-tidy clang-tidy18 clang-tidy15 clang-tidy-14 clang-tidy-12 REQUIRED) set(CMAKE_CXX_CLANG_TIDY "${CLANG_TIDY_EXECUTABLE};-warnings-as-errors=*;-checks=*") @@ -74,7 +74,7 @@ function(cmakeut_compiler_flags STANDARD) # member variables can be public/protected set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-cppcoreguidelines-non-private-member-variables-in-classes,-misc-non-private-member-variables-in-classes") # member initialization in constructors -- false positives - set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-cppcoreguidelines-pro-type-member-init,-hicpp-member-init") + set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-cppcoreguidelines-pro-type-member-init,-hicpp-member-init,-cppcoreguidelines-prefer-member-initializer") # default member initialization scatters initializations -- initialization must be done via constructors set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-modernize-use-default-member-init") # calling virtual functions from desctructors is well defined and generally safe @@ -91,6 +91,8 @@ function(cmakeut_compiler_flags STANDARD) set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-hicpp-no-array-decay") # long functions are ok set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-google-readability-function-size,-readability-function-size,-hicpp-function-size") + # do not enforce nested namespace concatenation + set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-modernize-concat-nested-namespaces") # overly restrictive fuchsia stuff @@ -100,6 +102,13 @@ function(cmakeut_compiler_flags STANDARD) # llvmlibc stuff set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-llvmlibc-*") + # noisy + set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-altera-unroll-loops,-altera-id-dependent-backward-branch,-readability-identifier-length,-misc-include-cleaner") + # false positives? + set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-bugprone-exception-escape,-clang-analyzer-cplusplus.NewDelete") + # may be later + set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},-cppcoreguidelines-avoid-const-or-ref-data-members") + set(CMAKE_CXX_CLANG_TIDY "${CMAKE_CXX_CLANG_TIDY},${CMAKEUT_CLANG_TIDY_EXTRA_IGNORES}") # might be useful too @@ -115,22 +124,5 @@ function(cmakeut_compiler_flags STANDARD) set(CXX_GENERIC "-std=${STANDARD} ${CXX_WARNINGS} ${CXX_OTHER} ${CXX_SANITIZERS}") - if ("${STANDARD}" STREQUAL "c++11") - - # -Wsuggest-override -Wsuggest-final-methods - set (CMAKEUT_CXX_FLAGS "${CXX_GENERIC}" PARENT_SCOPE) - - elseif ("${STANDARD}" STREQUAL "c++03") - - set (CMAKEUT_CXX_FLAGS "${CXX_GENERIC}" PARENT_SCOPE) - - elseif ("${STANDARD}" STREQUAL "c++98") - - set (CMAKEUT_CXX_FLAGS "${CXX_GENERIC}" PARENT_SCOPE) - - else() - - message(FATAL_ERROR "Unknown standard") - - endif() + set (CMAKEUT_CXX_FLAGS "${CXX_GENERIC}" PARENT_SCOPE) endfunction() diff --git a/ariles/cmake/options_deb_packages_bionic.cmake b/ariles/cmake/options_deb_packages_bionic.cmake index e4152a5e..36d64ae0 100644 --- a/ariles/cmake/options_deb_packages_bionic.cmake +++ b/ariles/cmake/options_deb_packages_bionic.cmake @@ -5,3 +5,4 @@ set(ARILES_BUILD_REGRESSION_TESTS "OFF" CACHE STRING "") set(ARILES_VISITORS_DEFAULT_MODE "ON" CACHE STRING "") set(ARILES_VISITOR_rosparam "$ENV{ROS_DISTRO}" CACHE STRING "") +set(ARILES_VISITOR_ros2param "OFF" CACHE STRING "") diff --git a/ariles/cmake/options_deb_packages_focal.cmake b/ariles/cmake/options_deb_packages_focal.cmake index 9b43f264..9be67f94 100644 --- a/ariles/cmake/options_deb_packages_focal.cmake +++ b/ariles/cmake/options_deb_packages_focal.cmake @@ -6,3 +6,4 @@ set(ARILES_BUILD_REGRESSION_TESTS "OFF" CACHE STRING "") set(ARILES_VISITORS_DEFAULT_MODE "ON" CACHE STRING "") set(ARILES_VISITOR_rosparam "$ENV{ROS_DISTRO}" CACHE STRING "") set(ARILES_VISITOR_msgpack "OFF" CACHE STRING "") +set(ARILES_VISITOR_ros2param "OFF" CACHE STRING "") diff --git a/ariles/cmake/options_deb_packages_jammy.cmake b/ariles/cmake/options_deb_packages_jammy.cmake index 280aca58..5a4ca904 100644 --- a/ariles/cmake/options_deb_packages_jammy.cmake +++ b/ariles/cmake/options_deb_packages_jammy.cmake @@ -5,3 +5,4 @@ set(ARILES_BUILD_REGRESSION_TESTS "OFF" CACHE STRING "") set(ARILES_VISITORS_DEFAULT_MODE "ON" CACHE STRING "") set(ARILES_VISITOR_rosparam "OFF" CACHE STRING "") +set(ARILES_VISITOR_ros2param "$ENV{ROS_DISTRO}" CACHE STRING "") diff --git a/ariles/cmake/options_deb_packages_xenial.cmake b/ariles/cmake/options_deb_packages_xenial.cmake index 45ea3d67..09b8983a 100644 --- a/ariles/cmake/options_deb_packages_xenial.cmake +++ b/ariles/cmake/options_deb_packages_xenial.cmake @@ -6,3 +6,4 @@ set(ARILES_VISITORS_DEFAULT_MODE "ON" CACHE STRING "") set(ARILES_VISITOR_rosparam "$ENV{ROS_DISTRO}" CACHE STRING "") set(ARILES_VISITOR_jsonnet "OFF" CACHE STRING "") set(ARILES_VISITOR_msgpack "OFF" CACHE STRING "") +set(ARILES_VISITOR_ros2param "OFF" CACHE STRING "") diff --git a/ariles/cmake/options_default.cmake b/ariles/cmake/options_default.cmake index f9483459..344c225a 100644 --- a/ariles/cmake/options_default.cmake +++ b/ariles/cmake/options_default.cmake @@ -1 +1 @@ -set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") +#set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") diff --git a/ariles/cmake/options_noros.cmake b/ariles/cmake/options_noros.cmake index 024a3db0..10feaa62 100644 --- a/ariles/cmake/options_noros.cmake +++ b/ariles/cmake/options_noros.cmake @@ -1,4 +1,4 @@ -set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") +#set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") set(ARILES_VISITOR_graphviz "ON" CACHE STRING "") set(ARILES_VISITOR_pugixml "ON" CACHE STRING "") @@ -7,3 +7,4 @@ set(ARILES_VISITOR_jsonnet "ON" CACHE STRING "") set(ARILES_VISITOR_msgpack "ON" CACHE STRING "") set(ARILES_VISITOR_yaml_cpp "ON" CACHE STRING "") set(ARILES_VISITOR_rosparam "OFF" CACHE STRING "") +set(ARILES_VISITOR_ros2param "OFF" CACHE STRING "") diff --git a/ariles/cmake/options_noros_tidy.cmake b/ariles/cmake/options_noros_tidy.cmake index 0d036799..3a2492b8 100644 --- a/ariles/cmake/options_noros_tidy.cmake +++ b/ariles/cmake/options_noros_tidy.cmake @@ -1,4 +1,4 @@ -set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") +#set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") set(ARILES_CPP_CLANG_TIDY "ON" CACHE STRING "") set(ARILES_VISITOR_graphviz "ON" CACHE STRING "") @@ -8,3 +8,4 @@ set(ARILES_VISITOR_jsonnet "ON" CACHE STRING "") set(ARILES_VISITOR_msgpack "ON" CACHE STRING "") set(ARILES_VISITOR_yaml_cpp "ON" CACHE STRING "") set(ARILES_VISITOR_rosparam "OFF" CACHE STRING "") +set(ARILES_VISITOR_ros2param "OFF" CACHE STRING "") diff --git a/ariles/cmake/options_noros_xenial.cmake b/ariles/cmake/options_noros_xenial.cmake index e735c7b6..58e279e0 100644 --- a/ariles/cmake/options_noros_xenial.cmake +++ b/ariles/cmake/options_noros_xenial.cmake @@ -1,7 +1,7 @@ #- rapidjson-dev # not found #- libmsgpack-dev # version is too old -set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") +#set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") set(ARILES_VISITOR_graphviz "ON" CACHE STRING "") set(ARILES_VISITOR_pugixml "ON" CACHE STRING "") @@ -10,3 +10,4 @@ set(ARILES_VISITOR_jsonnet "OFF" CACHE STRING "") set(ARILES_VISITOR_msgpack "OFF" CACHE STRING "") set(ARILES_VISITOR_yaml_cpp "ON" CACHE STRING "") set(ARILES_VISITOR_rosparam "OFF" CACHE STRING "") +set(ARILES_VISITOR_ros2param "OFF" CACHE STRING "") diff --git a/ariles/cmake/options_ros.cmake b/ariles/cmake/options_ros.cmake index f7489f45..a68315aa 100644 --- a/ariles/cmake/options_ros.cmake +++ b/ariles/cmake/options_ros.cmake @@ -1,6 +1,7 @@ -set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") +#set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") set(ARILES_VISITOR_msgpack "OFF" CACHE STRING "") set(ARILES_VISITOR_pugixml "OFF" CACHE STRING "") set(ARILES_VISITOR_rapidjson "OFF" CACHE STRING "") set(ARILES_VISITOR_jsonnet "OFF" CACHE STRING "") +set(ARILES_VISITOR_ros2param "OFF" CACHE STRING "") diff --git a/ariles/cmake/options_ros2.cmake b/ariles/cmake/options_ros2.cmake new file mode 100644 index 00000000..5fb46b7a --- /dev/null +++ b/ariles/cmake/options_ros2.cmake @@ -0,0 +1,7 @@ +#set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") + +set(ARILES_VISITOR_msgpack "OFF" CACHE STRING "") +set(ARILES_VISITOR_pugixml "OFF" CACHE STRING "") +set(ARILES_VISITOR_rapidjson "OFF" CACHE STRING "") +set(ARILES_VISITOR_jsonnet "OFF" CACHE STRING "") +set(ARILES_VISITOR_rosparam "OFF" CACHE STRING "") diff --git a/ariles/cmake/options_ros2_tidy.cmake b/ariles/cmake/options_ros2_tidy.cmake new file mode 100644 index 00000000..b0fb455d --- /dev/null +++ b/ariles/cmake/options_ros2_tidy.cmake @@ -0,0 +1,8 @@ +#set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") +set(ARILES_CPP_CLANG_TIDY "ON" CACHE STRING "") + +set(ARILES_VISITOR_msgpack "OFF" CACHE STRING "") +set(ARILES_VISITOR_pugixml "OFF" CACHE STRING "") +set(ARILES_VISITOR_rapidjson "OFF" CACHE STRING "") +set(ARILES_VISITOR_jsonnet "OFF" CACHE STRING "") +set(ARILES_VISITOR_rosparam "OFF" CACHE STRING "") diff --git a/ariles/cmake/options_ros_tidy.cmake b/ariles/cmake/options_ros_tidy.cmake index f007d4ed..c4a017fa 100644 --- a/ariles/cmake/options_ros_tidy.cmake +++ b/ariles/cmake/options_ros_tidy.cmake @@ -1,7 +1,8 @@ -set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") +#set(ARILES_CPP_SANITIZERS "ON" CACHE STRING "") set(ARILES_CPP_CLANG_TIDY "ON" CACHE STRING "") set(ARILES_VISITOR_msgpack "OFF" CACHE STRING "") set(ARILES_VISITOR_pugixml "OFF" CACHE STRING "") set(ARILES_VISITOR_rapidjson "OFF" CACHE STRING "") set(ARILES_VISITOR_jsonnet "OFF" CACHE STRING "") +set(ARILES_VISITOR_ros2param "OFF" CACHE STRING "") diff --git a/ariles/cpput/.gitignore b/ariles/cpput/.gitignore deleted file mode 100644 index d40a8d47..00000000 --- a/ariles/cpput/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -build -include/cpput/config.h -include/cpput/deprecation.h -include/cpput/exception.h -include/cpput/flags.h -include/cpput/floating_point_utils.h -include/cpput/location.h -include/cpput/math_utils.h -include/cpput/misc.h -include/cpput/print_backtrace.h -include/cpput/timer.h -include/cpput/trace.h -include/cpput/traits.h -include/cpput/visibility.h -include/cpput/cpput_config.h -include/cpput/cpput_deprecation.h -include/cpput/cpput_exception.h -include/cpput/cpput_flags.h -include/cpput/cpput_floating_point_utils.h -include/cpput/cpput_location.h -include/cpput/cpput_math_utils.h -include/cpput/cpput_misc.h -include/cpput/cpput_print_backtrace.h -include/cpput/cpput_timer.h -include/cpput/cpput_visibility.h -include/cpput/cpput_trace.h -include/cpput/cpput_traits.h diff --git a/ariles/cpput/.gitmodules b/ariles/cpput/.gitmodules deleted file mode 100644 index e69de29b..00000000 diff --git a/ariles/cpput/.travis.yml b/ariles/cpput/.travis.yml deleted file mode 100644 index 859795d8..00000000 --- a/ariles/cpput/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: cpp - -notifications: - email: - recipients: - - asherikov@yandex.com - on_success: always - on_failure: always - -compiler: - - clang - - gcc - -os: linux -dist: bionic - -addons: - apt: - update: true - packages: - - libboost-all-dev - - libeigen3-dev - -script: - - git submodule update --init - - make test diff --git a/ariles/cpput/CMakeLists.txt b/ariles/cpput/CMakeLists.txt deleted file mode 100644 index 1f4e969a..00000000 --- a/ariles/cpput/CMakeLists.txt +++ /dev/null @@ -1,156 +0,0 @@ -# General parameters -cmake_minimum_required (VERSION 3.0.0) -project(cpput VERSION 1.1.1) - - -# -------------- -# Options -# -------------- -set(CMAKE_VERBOSE_MAKEFILE ON) -option(CPPUT_EMBEDDED "Embedded in another project" OFF) -option(CPPUT_BUILD_TESTS "Build tests" ON) -set(CPPUT_EMBEDDED_ID "" CACHE STRING "Overrides header guards, namespace (does not apply to 3rdparty headers).") -set(CPPUT_EMBEDDED_COPY_TO_DIR "" CACHE STRING "Installation destination.") -set(CPPUT_SELECT_HEADERS "" CACHE STRING "Selection a subset of headers for installation.") -# -------------- - - -# -------------- -# Process options -# -------------- -set(CPPUT_ID "CPPUT") -if (CPPUT_EMBEDDED) - set(CPPUT_BUILD_TESTS OFF) - if(CPPUT_EMBEDDED_ID) - set(CPPUT_ID "${CPPUT_EMBEDDED_ID}") - endif() - if(NOT CPPUT_EMBEDDED_COPY_TO_DIR) - message(FATAL_ERROR "CPPUT_EMBEDDED_COPY_TO_DIR must be set with CPPUT_EMBEDDED=ON") - endif() -else() - if (CPPUT_EMBEDDED_ID OR CPPUT_EMBEDDED_COPY_TO_DIR) - message(WARNING "CPPUT_EMBEDDED_ID and CPPUT_EMBEDDED_COPY_TO_DIR ignored since CPPUT_EMBEDDED=OFF") - endif() -endif() - -string(TOLOWER "${CPPUT_ID}" CPPUT_ID_LOWER_CASE) - -set(CPPUT_HEADER_DIR "${PROJECT_SOURCE_DIR}/include/cpput") -set(CPPUT_OUTPUT_HEADER_DIR "${PROJECT_BINARY_DIR}/include/cpput") -# -------------- - - -# -------------- -# Packaging & installation paths -# -------------- -if (NOT CPPUT_EMBEDDED) - include(CMakePackageConfigHelpers) - set(CPPUT_INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/share/cpput/") - set(CPPUT_INCLUDES "${CMAKE_INSTALL_PREFIX}/include") - - configure_package_config_file( "cmake/cpputConfig.cmake.in" - "${PROJECT_BINARY_DIR}/cpputConfig.cmake" - INSTALL_DESTINATION "${CMAKE_INSTALL_PREFIX}/share/cpput/" - NO_SET_AND_CHECK_MACRO - NO_CHECK_REQUIRED_COMPONENTS_MACRO) - - write_basic_package_version_file( - ${PROJECT_BINARY_DIR}/cpputConfigVersion.cmake - VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH} - COMPATIBILITY SameMajorVersion) -endif() - - -if (NOT CPPUT_EMBEDDED) - set(CPPUT_INCLUDE_INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/include/${CPPUT_ID_LOWER_CASE}) -endif() -# -------------- - - -# -------------- -# Load cmake modules -# -------------- -include(CMakeParseArguments) -list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/") -# -------------- - - -# -------------- -# Configure headers -# -------------- -include(cmakeut_list_filenames) -include(cmakeut_detect_func_macro) -cmakeut_detect_func_macro() - -execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory - "${CPPUT_HEADER_DIR}" - "${CPPUT_OUTPUT_HEADER_DIR}" -) -cmakeut_list_filenames("${CPPUT_OUTPUT_HEADER_DIR}/" "CPPUT_HEADERS") -foreach (CPPUT_HEADER ${CPPUT_HEADERS}) - if (${CPPUT_HEADER} MATCHES ".h.in\$") - string(REPLACE ".h.in" ".h" CPPUT_HEADER_NO_SUFFIX "${CPPUT_HEADER}") - message(STATUS "Configuring header ${CPPUT_OUTPUT_HEADER_DIR}/${CPPUT_HEADER} -> ${CPPUT_OUTPUT_HEADER_DIR}/${CPPUT_HEADER_NO_SUFFIX}") - configure_file( "${CPPUT_OUTPUT_HEADER_DIR}/${CPPUT_HEADER}" - "${CPPUT_OUTPUT_HEADER_DIR}/${CPPUT_HEADER_NO_SUFFIX}") - endif() -endforeach() - -include_directories ("${CPPUT_OUTPUT_HEADER_DIR}/../") -# -------------- - - -# -------------- -# tests -# -------------- -if(CPPUT_BUILD_TESTS) - enable_testing() - add_subdirectory("${PROJECT_SOURCE_DIR}/test") -endif() -# -------------- - - -# -------------- -# Install -# -------------- -if (CPPUT_EMBEDDED) - if (NOT CPPUT_SELECT_HEADERS) - cmakeut_list_filenames("${CPPUT_OUTPUT_HEADER_DIR}/" "CPPUT_HEADERS") - foreach (CPPUT_HEADER ${CPPUT_HEADERS}) - if (NOT ${CPPUT_HEADER} MATCHES ".h.in\$" AND NOT ${CPPUT_HEADER} MATCHES "all.h") - list(APPEND CPPUT_SELECT_HEADERS "${CPPUT_HEADER}") - endif() - endforeach() - endif() - - if (CPPUT_SELECT_HEADERS) - foreach (CPPUT_HEADER ${CPPUT_SELECT_HEADERS}) - if (CPPUT_HEADER) - file( COPY "${CPPUT_OUTPUT_HEADER_DIR}/${CPPUT_HEADER}" - DESTINATION "${PROJECT_BINARY_DIR}/") - file( RENAME "${PROJECT_BINARY_DIR}/${CPPUT_HEADER}" - "${CPPUT_EMBEDDED_COPY_TO_DIR}/cpput_${CPPUT_HEADER}") - endif() - endforeach() - endif() -else() - install (FILES "${PROJECT_BINARY_DIR}/cpputConfig.cmake" - DESTINATION "${CPPUT_INSTALL_PATH}/") - - install (FILES "${PROJECT_BINARY_DIR}/cpputConfigVersion.cmake" - DESTINATION "${CPPUT_INSTALL_PATH}/") - - if (CPPUT_SELECT_HEADERS) - foreach (CPPUT_HEADER ${CPPUT_SELECT_HEADERS}) - if (CPPUT_HEADER) - install (FILES "${CPPUT_OUTPUT_HEADER_DIR}/${CPPUT_HEADER}" - DESTINATION "${CPPUT_INCLUDE_INSTALL_DESTINATION}/") - endif() - endforeach() - else() - install (DIRECTORY "${CPPUT_OUTPUT_HEADER_DIR}/" - DESTINATION "${CPPUT_INCLUDE_INSTALL_DESTINATION}" - FILES_MATCHING PATTERN "*.h") - endif() -endif() -# -------------- diff --git a/ariles/cpput/Makefile b/ariles/cpput/Makefile deleted file mode 100644 index dabe8266..00000000 --- a/ariles/cpput/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -BUILD_DIR?=build -MAKE_FLAGS?=-j1 - -INCLUDE_DIR=include/cpput/ - -default: - @grep -v "^ " Makefile | grep -v "^$$" - -clean: - rm -Rf ${BUILD_DIR} - ls ${INCLUDE_DIR}/*.in | sed 's/\.in$$//g' | xargs rm -f - ls ${INCLUDE_DIR}/*.in | sed 's/\.in$$//g' | sed 's=${INCLUDE_DIR}/=${INCLUDE_DIR}/cpput_=' | xargs rm -f - -build: - mkdir -p ${BUILD_DIR} - cd ${BUILD_DIR}; cmake .. - cd ${BUILD_DIR}; make ${MAKE_FLAGS} - -test: build - cd build; ${MAKE} ${MAKE_FLAGS} test - - -addutils: - git remote add cmakeut https://github.com/asherikov/cmakeut - git remote add better_enums https://github.com/aantron/better-enums - git remote add popl https://github.com/badaix/popl - git remote add safe_int https://github.com/dcleblanc/SafeInt - git remote add backward https://github.com/bombela/backward-cpp - -updateutils: - git fetch --all - git show remotes/cmakeut/master:cmake/cmakeut_add_cpp_test.cmake > cmake/cmakeut_add_cpp_test.cmake - git show remotes/cmakeut/master:cmake/cmakeut_compiler_flags.cmake > cmake/cmakeut_compiler_flags.cmake - git show remotes/cmakeut/master:cmake/cmakeut_detect_func_macro.cmake > cmake/cmakeut_detect_func_macro.cmake - git show remotes/cmakeut/master:cmake/cmakeut_list_filenames.cmake > cmake/cmakeut_list_filenames.cmake - git show remotes/better_enums/master:enum.h > ${INCLUDE_DIR}/better_enum.h - git show remotes/popl/master:include/popl.hpp > ${INCLUDE_DIR}/popl.h - git show remotes/safe_int/master:SafeInt.hpp > ${INCLUDE_DIR}/safe_int.h - git show remotes/backward/master:backward.hpp > ${INCLUDE_DIR}/backward.h - ${MAKE} allheader - -allheader: - echo "#ifndef H_CPPUT_ALL" > ${INCLUDE_DIR}/all.h - echo "#define H_CPPUT_ALL" >> ${INCLUDE_DIR}/all.h - cd ${INCLUDE_DIR}; ls *.h | grep -v "all.h" | sed 's/^\(.*\)/#include "\1"/' >> all.h - cd ${INCLUDE_DIR}; ls *.h.in | grep -v "all.h" | sed 's/\.in$$//g' | sed 's/^\(.*\)/#include "\1"/' >> all.h - echo "#endif" >> ${INCLUDE_DIR}/all.h - cat ${INCLUDE_DIR}/all.h - -gitignore: - echo "build" > .gitignore - ls ${INCLUDE_DIR}*.in | sed 's/\.in$$//g' >> .gitignore - ls ${INCLUDE_DIR}*.in | sed 's/\.in$$//g' | sed 's=${INCLUDE_DIR}=${INCLUDE_DIR}cpput_=' >> .gitignore - -.PHONY: build test 3rdparty diff --git a/ariles/cpput/README.md b/ariles/cpput/README.md deleted file mode 100644 index 9a762394..00000000 --- a/ariles/cpput/README.md +++ /dev/null @@ -1,17 +0,0 @@ -Travis CI: https://travis-ci.org/asherikov/cpput [![Build Status](https://travis-ci.org/asherikov/cpput.svg?branch=master)](https://travis-ci.org/asherikov/cpput) - -This repo contains C++ utilities from various sources, all satisfy the -following conditions: - -- permissive licences (Apache, BSD, MIT, etc), see comments in the headers; -- all utilities are header only; -- no external dependencies. - -Utilities may require C++11 support. - -Third party utils (likely to be outdated): -- `backward-cpp` -- https://github.com/bombela/backward-cpp -- `better_enums` -- http://github.com/aantron/better-enums -- `popl` -- https://github.com/badaix/popl -- `print_backtrace` -- https://panthema.net/2008/0901-stacktrace-demangled/ -- `SafeInt` -- https://github.com/dcleblanc/SafeInt diff --git a/ariles/cpput/cmake/cmakeut_add_cpp_test.cmake b/ariles/cpput/cmake/cmakeut_add_cpp_test.cmake deleted file mode 100644 index bdb5b3d7..00000000 --- a/ariles/cpput/cmake/cmakeut_add_cpp_test.cmake +++ /dev/null @@ -1,18 +0,0 @@ -function(cmakeut_add_cpp_test TEST_NAME) - - #set(options OPTION0) - set(oneValueArgs WORKING_DIRECTORY) - set(multiValueArgs LIBS DEPENDS FLAGS) - cmake_parse_arguments("CMAKEUT" "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) - - set(TGT_NAME "${PROJECT_NAME}_${TEST_NAME}") - add_executable(${TGT_NAME} "./${TEST_NAME}.cpp") - set_target_properties(${TGT_NAME} PROPERTIES COMPILE_FLAGS "${CMAKEUT_FLAGS}" OUTPUT_NAME ${TEST_NAME}) - - target_link_libraries(${TGT_NAME} "${CMAKEUT_LIBS}") - if (CMAKEUT_DEPENDS) - add_dependencies(${TGT_NAME} "${CMAKEUT_DEPENDS}") - endif() - add_test(NAME ${TGT_NAME} COMMAND ${CMAKE_CURRENT_BINARY_DIR}/${TEST_NAME} WORKING_DIRECTORY ${CMAKEUT_WORKING_DIRECTORY}) - -endfunction(cmakeut_add_cpp_test) diff --git a/ariles/cpput/cmake/cmakeut_compiler_flags.cmake b/ariles/cpput/cmake/cmakeut_compiler_flags.cmake deleted file mode 100644 index ff884be4..00000000 --- a/ariles/cpput/cmake/cmakeut_compiler_flags.cmake +++ /dev/null @@ -1,82 +0,0 @@ -function(cmakeut_compiler_flags STANDARD) - set (CXX_WARNINGS "-Wall -Wextra -Wshadow -Werror -pedantic-errors") - # --save-temps - set (CXX_OTHER "-fPIC") - - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") - - if (NOT CMAKE_CXX_COMPILER_VERSION OR CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.0) - # workaround for clang50 - set(CXX_WARNINGS "${CXX_WARNINGS} -Wno-error=unused-command-line-argument") - endif() - set(CXX_WARNINGS "${CXX_WARNINGS} -Werror=extra-tokens") - - elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - - # using GCC - set(CXX_WARNINGS "${CXX_WARNINGS}") - - elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel") - - # using Intel C++ - - elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") - - # using Visual Studio C++ - - endif() - - - set(CXX_SANITIZERS "") - if(CMAKEUT_CPP_SANITIZERS) - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") - - if ("${CMAKE_SYSTEM_NAME}" STREQUAL "FreeBSD") - # -fsanitize=address segfaults on boost UTF. - set(CXX_SANITIZERS "-fsanitize=undefined") - else() - set(CXX_SANITIZERS "-fsanitize=address -fsanitize=undefined") - endif() - - elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - - if (NOT CMAKE_CXX_COMPILER_VERSION OR CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9) - message(WARNING "GCC version is unknown or too old. Disabling sanitizers.") - else() - set(CXX_SANITIZERS "-fsanitize=address -fsanitize=undefined -fsanitize-undefined-trap-on-error") - endif() - - elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel") - - # using Intel C++ - - elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") - - # using Visual Studio C++ - - endif() - endif() - - - set(CXX_GENERIC "-std=${STANDARD} ${CXX_WARNINGS} ${CXX_OTHER} ${CXX_SANITIZERS}") - - - if ("${STANDARD}" STREQUAL "c++11") - - # -Wsuggest-override -Wsuggest-final-methods - set (CMAKEUT_CXX_FLAGS "${CXX_GENERIC}" PARENT_SCOPE) - - elseif ("${STANDARD}" STREQUAL "c++03") - - set (CMAKEUT_CXX_FLAGS "${CXX_GENERIC}" PARENT_SCOPE) - - elseif ("${STANDARD}" STREQUAL "c++98") - - set (CMAKEUT_CXX_FLAGS "${CXX_GENERIC}" PARENT_SCOPE) - - else() - - message(FATAL_ERROR "Unknown standard") - - endif() -endfunction() diff --git a/ariles/cpput/cmake/cmakeut_detect_func_macro.cmake b/ariles/cpput/cmake/cmakeut_detect_func_macro.cmake deleted file mode 100644 index 59c6635d..00000000 --- a/ariles/cpput/cmake/cmakeut_detect_func_macro.cmake +++ /dev/null @@ -1,21 +0,0 @@ -function(cmakeut_detect_func_macro) - include (CheckCXXSourceCompiles) - - CHECK_CXX_SOURCE_COMPILES(" - #include - int main(void) - { - std::cout << __func__ << std::endl; - return 0; - }" - CMAKEUT_COMPILER_SUPPORTS_FUNC_) - - CHECK_CXX_SOURCE_COMPILES(" - #include - int main(void) - { - std::cout << __FUNCTION__ << std::endl; - return 0; - }" - CMAKEUT_COMPILER_SUPPORTS_FUNCTION_) -endfunction() diff --git a/ariles/cpput/cmake/cmakeut_list_filenames.cmake b/ariles/cpput/cmake/cmakeut_list_filenames.cmake deleted file mode 100644 index 4cbba6be..00000000 --- a/ariles/cpput/cmake/cmakeut_list_filenames.cmake +++ /dev/null @@ -1,24 +0,0 @@ -# List filenames (all intermediate directories are stripped) in the given -# directory. -# This is equivalent to 'file(GLOB ... RELATIVE ... ...)', but behaves more -# consistently with different versions of cmake. -# -function(cmakeut_list_filenames DIR LISTNAME) - set(options DIRS_WITH_CMAKELISTS) - cmake_parse_arguments("CMAKEUT" "${options}" "" "" ${ARGN}) - - file(GLOB FILENAMES_TMP "${DIR}/*") - - set (FILENAMES "") - foreach(FILENAME_TMP ${FILENAMES_TMP}) - if(CMAKEUT_DIRS_WITH_CMAKELISTS) - if (NOT EXISTS "${FILENAME_TMP}/CMakeLists.txt") - continue() - endif() - endif() - get_filename_component(FILENAME_TMP ${FILENAME_TMP} NAME) - list(APPEND FILENAMES ${FILENAME_TMP}) - endforeach(FILENAME_TMP) - - set(${LISTNAME} "${FILENAMES}" PARENT_SCOPE) -endfunction() diff --git a/ariles/cpput/cmake/cpputConfig.cmake.in b/ariles/cpput/cmake/cpputConfig.cmake.in deleted file mode 100644 index 4b6ff1f4..00000000 --- a/ariles/cpput/cmake/cpputConfig.cmake.in +++ /dev/null @@ -1,7 +0,0 @@ -set (cpput_VERSION @PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@) - -@PACKAGE_INIT@ - -set (cpput_LIBRARIES "") -set (cpput_INCLUDE_DIRS "@CPPUT_INCLUDES@") -set (cpput_LIBRARY_DIRS "") diff --git a/ariles/cpput/include/cpput/all.h b/ariles/cpput/include/cpput/all.h deleted file mode 100644 index 1749d020..00000000 --- a/ariles/cpput/include/cpput/all.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef H_CPPUT_ALL -#define H_CPPUT_ALL -#include "backward.h" -#include "better_enum.h" -#include "popl.h" -#include "safe_int.h" -#include "config.h" -#include "deprecation.h" -#include "exception.h" -#include "flags.h" -#include "floating_point_utils.h" -#include "location.h" -#include "math_utils.h" -#include "misc.h" -#include "print_backtrace.h" -#include "timer.h" -#include "trace.h" -#include "traits.h" -#include "visibility.h" -#endif diff --git a/ariles/cpput/include/cpput/backward.h b/ariles/cpput/include/cpput/backward.h deleted file mode 100644 index 8fba93dd..00000000 --- a/ariles/cpput/include/cpput/backward.h +++ /dev/null @@ -1,4173 +0,0 @@ -/* - * backward.hpp - * Copyright 2013 Google Inc. All Rights Reserved. - * - * 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 H_6B9572DA_A64B_49E6_B234_051480991C89 -#define H_6B9572DA_A64B_49E6_B234_051480991C89 - -#ifndef __cplusplus -#error "It's not going to compile without a C++ compiler..." -#endif - -#if defined(BACKWARD_CXX11) -#elif defined(BACKWARD_CXX98) -#else -#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800) -#define BACKWARD_CXX11 -#define BACKWARD_ATLEAST_CXX11 -#define BACKWARD_ATLEAST_CXX98 -#else -#define BACKWARD_CXX98 -#define BACKWARD_ATLEAST_CXX98 -#endif -#endif - -// You can define one of the following (or leave it to the auto-detection): -// -// #define BACKWARD_SYSTEM_LINUX -// - specialization for linux -// -// #define BACKWARD_SYSTEM_DARWIN -// - specialization for Mac OS X 10.5 and later. -// -// #define BACKWARD_SYSTEM_UNKNOWN -// - placebo implementation, does nothing. -// -#if defined(BACKWARD_SYSTEM_LINUX) -#elif defined(BACKWARD_SYSTEM_DARWIN) -#elif defined(BACKWARD_SYSTEM_UNKNOWN) -#elif defined(BACKWARD_SYSTEM_WINDOWS) -#else -#if defined(__linux) || defined(__linux__) -#define BACKWARD_SYSTEM_LINUX -#elif defined(__APPLE__) -#define BACKWARD_SYSTEM_DARWIN -#elif defined(_WIN32) -#define BACKWARD_SYSTEM_WINDOWS -#else -#define BACKWARD_SYSTEM_UNKNOWN -#endif -#endif - -#define NOINLINE __attribute__((noinline)) - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(BACKWARD_SYSTEM_LINUX) - -// On linux, backtrace can back-trace or "walk" the stack using the following -// libraries: -// -// #define BACKWARD_HAS_UNWIND 1 -// - unwind comes from libgcc, but I saw an equivalent inside clang itself. -// - with unwind, the stacktrace is as accurate as it can possibly be, since -// this is used by the C++ runtine in gcc/clang for stack unwinding on -// exception. -// - normally libgcc is already linked to your program by default. -// -// #define BACKWARD_HAS_BACKTRACE == 1 -// - backtrace seems to be a little bit more portable than libunwind, but on -// linux, it uses unwind anyway, but abstract away a tiny information that is -// sadly really important in order to get perfectly accurate stack traces. -// - backtrace is part of the (e)glib library. -// -// The default is: -// #define BACKWARD_HAS_UNWIND == 1 -// -// Note that only one of the define should be set to 1 at a time. -// -#if BACKWARD_HAS_UNWIND == 1 -#elif BACKWARD_HAS_BACKTRACE == 1 -#else -#undef BACKWARD_HAS_UNWIND -#define BACKWARD_HAS_UNWIND 1 -#undef BACKWARD_HAS_BACKTRACE -#define BACKWARD_HAS_BACKTRACE 0 -#endif - -// On linux, backward can extract detailed information about a stack trace -// using one of the following libraries: -// -// #define BACKWARD_HAS_DW 1 -// - libdw gives you the most juicy details out of your stack traces: -// - object filename -// - function name -// - source filename -// - line and column numbers -// - source code snippet (assuming the file is accessible) -// - variables name and values (if not optimized out) -// - You need to link with the lib "dw": -// - apt-get install libdw-dev -// - g++/clang++ -ldw ... -// -// #define BACKWARD_HAS_BFD 1 -// - With libbfd, you get a fair amount of details: -// - object filename -// - function name -// - source filename -// - line numbers -// - source code snippet (assuming the file is accessible) -// - You need to link with the lib "bfd": -// - apt-get install binutils-dev -// - g++/clang++ -lbfd ... -// -// #define BACKWARD_HAS_DWARF 1 -// - libdwarf gives you the most juicy details out of your stack traces: -// - object filename -// - function name -// - source filename -// - line and column numbers -// - source code snippet (assuming the file is accessible) -// - variables name and values (if not optimized out) -// - You need to link with the lib "dwarf": -// - apt-get install libdwarf-dev -// - g++/clang++ -ldwarf ... -// -// #define BACKWARD_HAS_BACKTRACE_SYMBOL 1 -// - backtrace provides minimal details for a stack trace: -// - object filename -// - function name -// - backtrace is part of the (e)glib library. -// -// The default is: -// #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1 -// -// Note that only one of the define should be set to 1 at a time. -// -#if BACKWARD_HAS_DW == 1 -#elif BACKWARD_HAS_BFD == 1 -#elif BACKWARD_HAS_DWARF == 1 -#elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1 -#else -#undef BACKWARD_HAS_DW -#define BACKWARD_HAS_DW 0 -#undef BACKWARD_HAS_BFD -#define BACKWARD_HAS_BFD 0 -#undef BACKWARD_HAS_DWARF -#define BACKWARD_HAS_DWARF 0 -#undef BACKWARD_HAS_BACKTRACE_SYMBOL -#define BACKWARD_HAS_BACKTRACE_SYMBOL 1 -#endif - -#include -#include -#ifdef __ANDROID__ -// Old Android API levels define _Unwind_Ptr in both link.h and -// unwind.h Rename the one in link.h as we are not going to be using -// it -#define _Unwind_Ptr _Unwind_Ptr_Custom -#include -#undef _Unwind_Ptr -#else -#include -#endif -#include -#include -#include -#include - -#if BACKWARD_HAS_BFD == 1 -// NOTE: defining PACKAGE{,_VERSION} is required before including -// bfd.h on some platforms, see also: -// https://sourceware.org/bugzilla/show_bug.cgi?id=14243 -#ifndef PACKAGE -#define PACKAGE -#endif -#ifndef PACKAGE_VERSION -#define PACKAGE_VERSION -#endif -#include -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#include -#undef _GNU_SOURCE -#else -#include -#endif -#endif - -#if BACKWARD_HAS_DW == 1 -#include -#include -#include -#endif - -#if BACKWARD_HAS_DWARF == 1 -#include -#include -#include -#include -#include -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#include -#undef _GNU_SOURCE -#else -#include -#endif -#endif - -#if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1) -// then we shall rely on backtrace -#include -#endif - -#endif // defined(BACKWARD_SYSTEM_LINUX) - -#if defined(BACKWARD_SYSTEM_DARWIN) -// On Darwin, backtrace can back-trace or "walk" the stack using the following -// libraries: -// -// #define BACKWARD_HAS_UNWIND 1 -// - unwind comes from libgcc, but I saw an equivalent inside clang itself. -// - with unwind, the stacktrace is as accurate as it can possibly be, since -// this is used by the C++ runtine in gcc/clang for stack unwinding on -// exception. -// - normally libgcc is already linked to your program by default. -// -// #define BACKWARD_HAS_BACKTRACE == 1 -// - backtrace is available by default, though it does not produce as much -// information as another library might. -// -// The default is: -// #define BACKWARD_HAS_UNWIND == 1 -// -// Note that only one of the define should be set to 1 at a time. -// -#if BACKWARD_HAS_UNWIND == 1 -#elif BACKWARD_HAS_BACKTRACE == 1 -#else -#undef BACKWARD_HAS_UNWIND -#define BACKWARD_HAS_UNWIND 1 -#undef BACKWARD_HAS_BACKTRACE -#define BACKWARD_HAS_BACKTRACE 0 -#endif - -// On Darwin, backward can extract detailed information about a stack trace -// using one of the following libraries: -// -// #define BACKWARD_HAS_BACKTRACE_SYMBOL 1 -// - backtrace provides minimal details for a stack trace: -// - object filename -// - function name -// -// The default is: -// #define BACKWARD_HAS_BACKTRACE_SYMBOL == 1 -// -#if BACKWARD_HAS_BACKTRACE_SYMBOL == 1 -#else -#undef BACKWARD_HAS_BACKTRACE_SYMBOL -#define BACKWARD_HAS_BACKTRACE_SYMBOL 1 -#endif - -#include -#include -#include -#include -#include -#include - -#if (BACKWARD_HAS_BACKTRACE == 1) || (BACKWARD_HAS_BACKTRACE_SYMBOL == 1) -#include -#endif -#endif // defined(BACKWARD_SYSTEM_DARWIN) - -#if defined(BACKWARD_SYSTEM_WINDOWS) - -#include -#include -#include - -#include -typedef SSIZE_T ssize_t; - -#define NOMINMAX -#include -#include - -#include -#include - -#ifndef __clang__ -#undef NOINLINE -#define NOINLINE __declspec(noinline) -#endif - -#pragma comment(lib, "psapi.lib") -#pragma comment(lib, "dbghelp.lib") - -// Comment / packing is from stackoverflow: -// https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227 -// Some versions of imagehlp.dll lack the proper packing directives themselves -// so we need to do it. -#pragma pack(push, before_imagehlp, 8) -#include -#pragma pack(pop, before_imagehlp) - -// TODO maybe these should be undefined somewhere else? -#undef BACKWARD_HAS_UNWIND -#undef BACKWARD_HAS_BACKTRACE -#if BACKWARD_HAS_PDB_SYMBOL == 1 -#else -#undef BACKWARD_HAS_PDB_SYMBOL -#define BACKWARD_HAS_PDB_SYMBOL 1 -#endif - -#endif - -#if BACKWARD_HAS_UNWIND == 1 - -#include -// while gcc's unwind.h defines something like that: -// extern _Unwind_Ptr _Unwind_GetIP (struct _Unwind_Context *); -// extern _Unwind_Ptr _Unwind_GetIPInfo (struct _Unwind_Context *, int *); -// -// clang's unwind.h defines something like this: -// uintptr_t _Unwind_GetIP(struct _Unwind_Context* __context); -// -// Even if the _Unwind_GetIPInfo can be linked to, it is not declared, worse we -// cannot just redeclare it because clang's unwind.h doesn't define _Unwind_Ptr -// anyway. -// -// Luckily we can play on the fact that the guard macros have a different name: -#ifdef __CLANG_UNWIND_H -// In fact, this function still comes from libgcc (on my different linux boxes, -// clang links against libgcc). -#include -extern "C" uintptr_t _Unwind_GetIPInfo(_Unwind_Context *, int *); -#endif - -#endif // BACKWARD_HAS_UNWIND == 1 - -#ifdef BACKWARD_ATLEAST_CXX11 -#include -#include // for std::swap -namespace backward { -namespace details { -template struct hashtable { - typedef std::unordered_map type; -}; -using std::move; -} // namespace details -} // namespace backward -#else // NOT BACKWARD_ATLEAST_CXX11 -#define nullptr NULL -#define override -#include -namespace backward { -namespace details { -template struct hashtable { - typedef std::map type; -}; -template const T &move(const T &v) { return v; } -template T &move(T &v) { return v; } -} // namespace details -} // namespace backward -#endif // BACKWARD_ATLEAST_CXX11 - -namespace backward { -namespace details { -#if defined(BACKWARD_SYSTEM_WINDOWS) -const char kBackwardPathDelimiter[] = ";"; -#else -const char kBackwardPathDelimiter[] = ":"; -#endif -} // namespace details -} // namespace backward - -namespace backward { - -namespace system_tag { -struct linux_tag; // seems that I cannot call that "linux" because the name -// is already defined... so I am adding _tag everywhere. -struct darwin_tag; -struct windows_tag; -struct unknown_tag; - -#if defined(BACKWARD_SYSTEM_LINUX) -typedef linux_tag current_tag; -#elif defined(BACKWARD_SYSTEM_DARWIN) -typedef darwin_tag current_tag; -#elif defined(BACKWARD_SYSTEM_WINDOWS) -typedef windows_tag current_tag; -#elif defined(BACKWARD_SYSTEM_UNKNOWN) -typedef unknown_tag current_tag; -#else -#error "May I please get my system defines?" -#endif -} // namespace system_tag - -namespace trace_resolver_tag { -#if defined(BACKWARD_SYSTEM_LINUX) -struct libdw; -struct libbfd; -struct libdwarf; -struct backtrace_symbol; - -#if BACKWARD_HAS_DW == 1 -typedef libdw current; -#elif BACKWARD_HAS_BFD == 1 -typedef libbfd current; -#elif BACKWARD_HAS_DWARF == 1 -typedef libdwarf current; -#elif BACKWARD_HAS_BACKTRACE_SYMBOL == 1 -typedef backtrace_symbol current; -#else -#error "You shall not pass, until you know what you want." -#endif -#elif defined(BACKWARD_SYSTEM_DARWIN) -struct backtrace_symbol; - -#if BACKWARD_HAS_BACKTRACE_SYMBOL == 1 -typedef backtrace_symbol current; -#else -#error "You shall not pass, until you know what you want." -#endif -#elif defined(BACKWARD_SYSTEM_WINDOWS) -struct pdb_symbol; -#if BACKWARD_HAS_PDB_SYMBOL == 1 -typedef pdb_symbol current; -#else -#error "You shall not pass, until you know what you want." -#endif -#endif -} // namespace trace_resolver_tag - -namespace details { - -template struct rm_ptr { typedef T type; }; - -template struct rm_ptr { typedef T type; }; - -template struct rm_ptr { typedef const T type; }; - -template struct deleter { - template void operator()(U &ptr) const { (*F)(ptr); } -}; - -template struct default_delete { - void operator()(T &ptr) const { delete ptr; } -}; - -template > -class handle { - struct dummy; - T _val; - bool _empty; - -#ifdef BACKWARD_ATLEAST_CXX11 - handle(const handle &) = delete; - handle &operator=(const handle &) = delete; -#endif - -public: - ~handle() { - if (!_empty) { - Deleter()(_val); - } - } - - explicit handle() : _val(), _empty(true) {} - explicit handle(T val) : _val(val), _empty(false) { - if (!_val) - _empty = true; - } - -#ifdef BACKWARD_ATLEAST_CXX11 - handle(handle &&from) : _empty(true) { swap(from); } - handle &operator=(handle &&from) { - swap(from); - return *this; - } -#else - explicit handle(const handle &from) : _empty(true) { - // some sort of poor man's move semantic. - swap(const_cast(from)); - } - handle &operator=(const handle &from) { - // some sort of poor man's move semantic. - swap(const_cast(from)); - return *this; - } -#endif - - void reset(T new_val) { - handle tmp(new_val); - swap(tmp); - } - - void update(T new_val) { - _val = new_val; - _empty = static_cast(new_val); - } - - operator const dummy *() const { - if (_empty) { - return nullptr; - } - return reinterpret_cast(_val); - } - T get() { return _val; } - T release() { - _empty = true; - return _val; - } - void swap(handle &b) { - using std::swap; - swap(b._val, _val); // can throw, we are safe here. - swap(b._empty, _empty); // should not throw: if you cannot swap two - // bools without throwing... It's a lost cause anyway! - } - - T &operator->() { return _val; } - const T &operator->() const { return _val; } - - typedef typename rm_ptr::type &ref_t; - typedef const typename rm_ptr::type &const_ref_t; - ref_t operator*() { return *_val; } - const_ref_t operator*() const { return *_val; } - ref_t operator[](size_t idx) { return _val[idx]; } - - // Watch out, we've got a badass over here - T *operator&() { - _empty = false; - return &_val; - } -}; - -// Default demangler implementation (do nothing). -template struct demangler_impl { - static std::string demangle(const char *funcname) { return funcname; } -}; - -#if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN) - -template <> struct demangler_impl { - demangler_impl() : _demangle_buffer_length(0) {} - - std::string demangle(const char *funcname) { - using namespace details; - char *result = abi::__cxa_demangle(funcname, _demangle_buffer.get(), - &_demangle_buffer_length, nullptr); - if (result) { - _demangle_buffer.update(result); - return result; - } - return funcname; - } - -private: - details::handle _demangle_buffer; - size_t _demangle_buffer_length; -}; - -#endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN - -struct demangler : public demangler_impl {}; - -// Split a string on the platform's PATH delimiter. Example: if delimiter -// is ":" then: -// "" --> [] -// ":" --> ["",""] -// "::" --> ["","",""] -// "/a/b/c" --> ["/a/b/c"] -// "/a/b/c:/d/e/f" --> ["/a/b/c","/d/e/f"] -// etc. -inline std::vector split_source_prefixes(const std::string &s) { - std::vector out; - size_t last = 0; - size_t next = 0; - size_t delimiter_size = sizeof(kBackwardPathDelimiter) - 1; - while ((next = s.find(kBackwardPathDelimiter, last)) != std::string::npos) { - out.push_back(s.substr(last, next - last)); - last = next + delimiter_size; - } - if (last <= s.length()) { - out.push_back(s.substr(last)); - } - return out; -} - -} // namespace details - -/*************** A TRACE ***************/ - -struct Trace { - void *addr; - size_t idx; - - Trace() : addr(nullptr), idx(0) {} - - explicit Trace(void *_addr, size_t _idx) : addr(_addr), idx(_idx) {} -}; - -struct ResolvedTrace : public Trace { - - struct SourceLoc { - std::string function; - std::string filename; - unsigned line; - unsigned col; - - SourceLoc() : line(0), col(0) {} - - bool operator==(const SourceLoc &b) const { - return function == b.function && filename == b.filename && - line == b.line && col == b.col; - } - - bool operator!=(const SourceLoc &b) const { return !(*this == b); } - }; - - // In which binary object this trace is located. - std::string object_filename; - - // The function in the object that contain the trace. This is not the same - // as source.function which can be an function inlined in object_function. - std::string object_function; - - // The source location of this trace. It is possible for filename to be - // empty and for line/col to be invalid (value 0) if this information - // couldn't be deduced, for example if there is no debug information in the - // binary object. - SourceLoc source; - - // An optionals list of "inliners". All the successive sources location - // from where the source location of the trace (the attribute right above) - // is inlined. It is especially useful when you compiled with optimization. - typedef std::vector source_locs_t; - source_locs_t inliners; - - ResolvedTrace() : Trace() {} - ResolvedTrace(const Trace &mini_trace) : Trace(mini_trace) {} -}; - -/*************** STACK TRACE ***************/ - -// default implemention. -template class StackTraceImpl { -public: - size_t size() const { return 0; } - Trace operator[](size_t) const { return Trace(); } - size_t load_here(size_t = 0) { return 0; } - size_t load_from(void *, size_t = 0) { return 0; } - size_t thread_id() const { return 0; } - void skip_n_firsts(size_t) {} -}; - -class StackTraceImplBase { -public: - StackTraceImplBase() : _thread_id(0), _skip(0) {} - - size_t thread_id() const { return _thread_id; } - - void skip_n_firsts(size_t n) { _skip = n; } - -protected: - void load_thread_info() { -#ifdef BACKWARD_SYSTEM_LINUX -#ifndef __ANDROID__ - _thread_id = static_cast(syscall(SYS_gettid)); -#else - _thread_id = static_cast(gettid()); -#endif - if (_thread_id == static_cast(getpid())) { - // If the thread is the main one, let's hide that. - // I like to keep little secret sometimes. - _thread_id = 0; - } -#elif defined(BACKWARD_SYSTEM_DARWIN) - _thread_id = reinterpret_cast(pthread_self()); - if (pthread_main_np() == 1) { - // If the thread is the main one, let's hide that. - _thread_id = 0; - } -#endif - } - - size_t skip_n_firsts() const { return _skip; } - -private: - size_t _thread_id; - size_t _skip; -}; - -class StackTraceImplHolder : public StackTraceImplBase { -public: - size_t size() const { - return _stacktrace.size() ? _stacktrace.size() - skip_n_firsts() : 0; - } - Trace operator[](size_t idx) const { - if (idx >= size()) { - return Trace(); - } - return Trace(_stacktrace[idx + skip_n_firsts()], idx); - } - void *const *begin() const { - if (size()) { - return &_stacktrace[skip_n_firsts()]; - } - return nullptr; - } - -protected: - std::vector _stacktrace; -}; - -#if BACKWARD_HAS_UNWIND == 1 - -namespace details { - -template class Unwinder { -public: - size_t operator()(F &f, size_t depth) { - _f = &f; - _index = -1; - _depth = depth; - _Unwind_Backtrace(&this->backtrace_trampoline, this); - return static_cast(_index); - } - -private: - F *_f; - ssize_t _index; - size_t _depth; - - static _Unwind_Reason_Code backtrace_trampoline(_Unwind_Context *ctx, - void *self) { - return (static_cast(self))->backtrace(ctx); - } - - _Unwind_Reason_Code backtrace(_Unwind_Context *ctx) { - if (_index >= 0 && static_cast(_index) >= _depth) - return _URC_END_OF_STACK; - - int ip_before_instruction = 0; - uintptr_t ip = _Unwind_GetIPInfo(ctx, &ip_before_instruction); - - if (!ip_before_instruction) { - // calculating 0-1 for unsigned, looks like a possible bug to sanitiziers, - // so let's do it explicitly: - if (ip == 0) { - ip = std::numeric_limits::max(); // set it to 0xffff... (as - // from casting 0-1) - } else { - ip -= 1; // else just normally decrement it (no overflow/underflow will - // happen) - } - } - - if (_index >= 0) { // ignore first frame. - (*_f)(static_cast(_index), reinterpret_cast(ip)); - } - _index += 1; - return _URC_NO_REASON; - } -}; - -template size_t unwind(F f, size_t depth) { - Unwinder unwinder; - return unwinder(f, depth); -} - -} // namespace details - -template <> -class StackTraceImpl : public StackTraceImplHolder { -public: - NOINLINE - size_t load_here(size_t depth = 32) { - load_thread_info(); - if (depth == 0) { - return 0; - } - _stacktrace.resize(depth); - size_t trace_cnt = details::unwind(callback(*this), depth); - _stacktrace.resize(trace_cnt); - skip_n_firsts(0); - return size(); - } - size_t load_from(void *addr, size_t depth = 32) { - load_here(depth + 8); - - for (size_t i = 0; i < _stacktrace.size(); ++i) { - if (_stacktrace[i] == addr) { - skip_n_firsts(i); - break; - } - } - - _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth)); - return size(); - } - -private: - struct callback { - StackTraceImpl &self; - callback(StackTraceImpl &_self) : self(_self) {} - - void operator()(size_t idx, void *addr) { self._stacktrace[idx] = addr; } - }; -}; - -#elif defined(BACKWARD_HAS_BACKTRACE) - -template <> -class StackTraceImpl : public StackTraceImplHolder { -public: - NOINLINE - size_t load_here(size_t depth = 32) { - load_thread_info(); - if (depth == 0) { - return 0; - } - _stacktrace.resize(depth + 1); - size_t trace_cnt = backtrace(&_stacktrace[0], _stacktrace.size()); - _stacktrace.resize(trace_cnt); - skip_n_firsts(1); - return size(); - } - - size_t load_from(void *addr, size_t depth = 32) { - load_here(depth + 8); - - for (size_t i = 0; i < _stacktrace.size(); ++i) { - if (_stacktrace[i] == addr) { - skip_n_firsts(i); - _stacktrace[i] = (void *)((uintptr_t)_stacktrace[i] + 1); - break; - } - } - - _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth)); - return size(); - } -}; - -#elif defined(BACKWARD_SYSTEM_WINDOWS) - -template <> -class StackTraceImpl : public StackTraceImplHolder { -public: - // We have to load the machine type from the image info - // So we first initialize the resolver, and it tells us this info - void set_machine_type(DWORD machine_type) { machine_type_ = machine_type; } - void set_context(CONTEXT *ctx) { ctx_ = ctx; } - void set_thread_handle(HANDLE handle) { thd_ = handle; } - - NOINLINE - size_t load_here(size_t depth = 32) { - - CONTEXT localCtx; // used when no context is provided - - if (depth == 0) { - return 0; - } - - if (!ctx_) { - ctx_ = &localCtx; - RtlCaptureContext(ctx_); - } - - if (!thd_) { - thd_ = GetCurrentThread(); - } - - HANDLE process = GetCurrentProcess(); - - STACKFRAME64 s; - memset(&s, 0, sizeof(STACKFRAME64)); - - // TODO: 32 bit context capture - s.AddrStack.Mode = AddrModeFlat; - s.AddrFrame.Mode = AddrModeFlat; - s.AddrPC.Mode = AddrModeFlat; -#ifdef _M_X64 - s.AddrPC.Offset = ctx_->Rip; - s.AddrStack.Offset = ctx_->Rsp; - s.AddrFrame.Offset = ctx_->Rbp; -#else - s.AddrPC.Offset = ctx_->Eip; - s.AddrStack.Offset = ctx_->Esp; - s.AddrFrame.Offset = ctx_->Ebp; -#endif - - if (!machine_type_) { -#ifdef _M_X64 - machine_type_ = IMAGE_FILE_MACHINE_AMD64; -#else - machine_type_ = IMAGE_FILE_MACHINE_I386; -#endif - } - - for (;;) { - // NOTE: this only works if PDBs are already loaded! - SetLastError(0); - if (!StackWalk64(machine_type_, process, thd_, &s, ctx_, NULL, - SymFunctionTableAccess64, SymGetModuleBase64, NULL)) - break; - - if (s.AddrReturn.Offset == 0) - break; - - _stacktrace.push_back(reinterpret_cast(s.AddrPC.Offset)); - - if (size() >= depth) - break; - } - - return size(); - } - - size_t load_from(void *addr, size_t depth = 32) { - load_here(depth + 8); - - for (size_t i = 0; i < _stacktrace.size(); ++i) { - if (_stacktrace[i] == addr) { - skip_n_firsts(i); - break; - } - } - - _stacktrace.resize(std::min(_stacktrace.size(), skip_n_firsts() + depth)); - return size(); - } - -private: - DWORD machine_type_ = 0; - HANDLE thd_ = 0; - CONTEXT *ctx_ = nullptr; -}; - -#endif - -class StackTrace : public StackTraceImpl {}; - -/*************** TRACE RESOLVER ***************/ - -template class TraceResolverImpl; - -#ifdef BACKWARD_SYSTEM_UNKNOWN - -template <> class TraceResolverImpl { -public: - template void load_stacktrace(ST &) {} - ResolvedTrace resolve(ResolvedTrace t) { return t; } -}; - -#endif - -class TraceResolverImplBase { -protected: - std::string demangle(const char *funcname) { - return _demangler.demangle(funcname); - } - -private: - details::demangler _demangler; -}; - -#ifdef BACKWARD_SYSTEM_LINUX - -class TraceResolverLinuxBase : public TraceResolverImplBase { -public: - TraceResolverLinuxBase() - : argv0_(get_argv0()), exec_path_(read_symlink("/proc/self/exe")) {} - std::string resolve_exec_path(Dl_info &symbol_info) const { - // mutates symbol_info.dli_fname to be filename to open and returns filename - // to display - if (symbol_info.dli_fname == argv0_) { - // dladdr returns argv[0] in dli_fname for symbols contained in - // the main executable, which is not a valid path if the - // executable was found by a search of the PATH environment - // variable; In that case, we actually open /proc/self/exe, which - // is always the actual executable (even if it was deleted/replaced!) - // but display the path that /proc/self/exe links to. - symbol_info.dli_fname = "/proc/self/exe"; - return exec_path_; - } else { - return symbol_info.dli_fname; - } - } - -private: - std::string argv0_; - std::string exec_path_; - - static std::string get_argv0() { - std::string argv0; - std::ifstream ifs("/proc/self/cmdline"); - std::getline(ifs, argv0, '\0'); - return argv0; - } - - static std::string read_symlink(std::string const &symlink_path) { - std::string path; - path.resize(100); - - while (true) { - ssize_t len = - ::readlink(symlink_path.c_str(), &*path.begin(), path.size()); - if (len < 0) { - return ""; - } - if (static_cast(len) == path.size()) { - path.resize(path.size() * 2); - } else { - path.resize(static_cast(len)); - break; - } - } - - return path; - } -}; - -template class TraceResolverLinuxImpl; - -#if BACKWARD_HAS_BACKTRACE_SYMBOL == 1 - -template <> -class TraceResolverLinuxImpl - : public TraceResolverLinuxBase { -public: - template void load_stacktrace(ST &st) { - using namespace details; - if (st.size() == 0) { - return; - } - _symbols.reset(backtrace_symbols(st.begin(), (int)st.size())); - } - - ResolvedTrace resolve(ResolvedTrace trace) { - char *filename = _symbols[trace.idx]; - char *funcname = filename; - while (*funcname && *funcname != '(') { - funcname += 1; - } - trace.object_filename.assign(filename, - funcname); // ok even if funcname is the ending - // \0 (then we assign entire string) - - if (*funcname) { // if it's not end of string (e.g. from last frame ip==0) - funcname += 1; - char *funcname_end = funcname; - while (*funcname_end && *funcname_end != ')' && *funcname_end != '+') { - funcname_end += 1; - } - *funcname_end = '\0'; - trace.object_function = this->demangle(funcname); - trace.source.function = trace.object_function; // we cannot do better. - } - return trace; - } - -private: - details::handle _symbols; -}; - -#endif // BACKWARD_HAS_BACKTRACE_SYMBOL == 1 - -#if BACKWARD_HAS_BFD == 1 - -template <> -class TraceResolverLinuxImpl - : public TraceResolverLinuxBase { -public: - TraceResolverLinuxImpl() : _bfd_loaded(false) {} - - template void load_stacktrace(ST &) {} - - ResolvedTrace resolve(ResolvedTrace trace) { - Dl_info symbol_info; - - // trace.addr is a virtual address in memory pointing to some code. - // Let's try to find from which loaded object it comes from. - // The loaded object can be yourself btw. - if (!dladdr(trace.addr, &symbol_info)) { - return trace; // dat broken trace... - } - - // Now we get in symbol_info: - // .dli_fname: - // pathname of the shared object that contains the address. - // .dli_fbase: - // where the object is loaded in memory. - // .dli_sname: - // the name of the nearest symbol to trace.addr, we expect a - // function name. - // .dli_saddr: - // the exact address corresponding to .dli_sname. - - if (symbol_info.dli_sname) { - trace.object_function = demangle(symbol_info.dli_sname); - } - - if (!symbol_info.dli_fname) { - return trace; - } - - trace.object_filename = resolve_exec_path(symbol_info); - bfd_fileobject &fobj = load_object_with_bfd(symbol_info.dli_fname); - if (!fobj.handle) { - return trace; // sad, we couldn't load the object :( - } - - find_sym_result *details_selected; // to be filled. - - // trace.addr is the next instruction to be executed after returning - // from the nested stack frame. In C++ this usually relate to the next - // statement right after the function call that leaded to a new stack - // frame. This is not usually what you want to see when printing out a - // stacktrace... - find_sym_result details_call_site = - find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase); - details_selected = &details_call_site; - -#if BACKWARD_HAS_UNWIND == 0 - // ...this is why we also try to resolve the symbol that is right - // before the return address. If we are lucky enough, we will get the - // line of the function that was called. But if the code is optimized, - // we might get something absolutely not related since the compiler - // can reschedule the return address with inline functions and - // tail-call optimisation (among other things that I don't even know - // or cannot even dream about with my tiny limited brain). - find_sym_result details_adjusted_call_site = find_symbol_details( - fobj, (void *)(uintptr_t(trace.addr) - 1), symbol_info.dli_fbase); - - // In debug mode, we should always get the right thing(TM). - if (details_call_site.found && details_adjusted_call_site.found) { - // Ok, we assume that details_adjusted_call_site is a better estimation. - details_selected = &details_adjusted_call_site; - trace.addr = (void *)(uintptr_t(trace.addr) - 1); - } - - if (details_selected == &details_call_site && details_call_site.found) { - // we have to re-resolve the symbol in order to reset some - // internal state in BFD... so we can call backtrace_inliners - // thereafter... - details_call_site = - find_symbol_details(fobj, trace.addr, symbol_info.dli_fbase); - } -#endif // BACKWARD_HAS_UNWIND - - if (details_selected->found) { - if (details_selected->filename) { - trace.source.filename = details_selected->filename; - } - trace.source.line = details_selected->line; - - if (details_selected->funcname) { - // this time we get the name of the function where the code is - // located, instead of the function were the address is - // located. In short, if the code was inlined, we get the - // function correspoding to the code. Else we already got in - // trace.function. - trace.source.function = demangle(details_selected->funcname); - - if (!symbol_info.dli_sname) { - // for the case dladdr failed to find the symbol name of - // the function, we might as well try to put something - // here. - trace.object_function = trace.source.function; - } - } - - // Maybe the source of the trace got inlined inside the function - // (trace.source.function). Let's see if we can get all the inlined - // calls along the way up to the initial call site. - trace.inliners = backtrace_inliners(fobj, *details_selected); - -#if 0 - if (trace.inliners.size() == 0) { - // Maybe the trace was not inlined... or maybe it was and we - // are lacking the debug information. Let's try to make the - // world better and see if we can get the line number of the - // function (trace.source.function) now. - // - // We will get the location of where the function start (to be - // exact: the first instruction that really start the - // function), not where the name of the function is defined. - // This can be quite far away from the name of the function - // btw. - // - // If the source of the function is the same as the source of - // the trace, we cannot say if the trace was really inlined or - // not. However, if the filename of the source is different - // between the function and the trace... we can declare it as - // an inliner. This is not 100% accurate, but better than - // nothing. - - if (symbol_info.dli_saddr) { - find_sym_result details = find_symbol_details(fobj, - symbol_info.dli_saddr, - symbol_info.dli_fbase); - - if (details.found) { - ResolvedTrace::SourceLoc diy_inliner; - diy_inliner.line = details.line; - if (details.filename) { - diy_inliner.filename = details.filename; - } - if (details.funcname) { - diy_inliner.function = demangle(details.funcname); - } else { - diy_inliner.function = trace.source.function; - } - if (diy_inliner != trace.source) { - trace.inliners.push_back(diy_inliner); - } - } - } - } -#endif - } - - return trace; - } - -private: - bool _bfd_loaded; - - typedef details::handle> - bfd_handle_t; - - typedef details::handle bfd_symtab_t; - - struct bfd_fileobject { - bfd_handle_t handle; - bfd_vma base_addr; - bfd_symtab_t symtab; - bfd_symtab_t dynamic_symtab; - }; - - typedef details::hashtable::type fobj_bfd_map_t; - fobj_bfd_map_t _fobj_bfd_map; - - bfd_fileobject &load_object_with_bfd(const std::string &filename_object) { - using namespace details; - - if (!_bfd_loaded) { - using namespace details; - bfd_init(); - _bfd_loaded = true; - } - - fobj_bfd_map_t::iterator it = _fobj_bfd_map.find(filename_object); - if (it != _fobj_bfd_map.end()) { - return it->second; - } - - // this new object is empty for now. - bfd_fileobject &r = _fobj_bfd_map[filename_object]; - - // we do the work temporary in this one; - bfd_handle_t bfd_handle; - - int fd = open(filename_object.c_str(), O_RDONLY); - bfd_handle.reset(bfd_fdopenr(filename_object.c_str(), "default", fd)); - if (!bfd_handle) { - close(fd); - return r; - } - - if (!bfd_check_format(bfd_handle.get(), bfd_object)) { - return r; // not an object? You lose. - } - - if ((bfd_get_file_flags(bfd_handle.get()) & HAS_SYMS) == 0) { - return r; // that's what happen when you forget to compile in debug. - } - - ssize_t symtab_storage_size = bfd_get_symtab_upper_bound(bfd_handle.get()); - - ssize_t dyn_symtab_storage_size = - bfd_get_dynamic_symtab_upper_bound(bfd_handle.get()); - - if (symtab_storage_size <= 0 && dyn_symtab_storage_size <= 0) { - return r; // weird, is the file is corrupted? - } - - bfd_symtab_t symtab, dynamic_symtab; - ssize_t symcount = 0, dyn_symcount = 0; - - if (symtab_storage_size > 0) { - symtab.reset(static_cast( - malloc(static_cast(symtab_storage_size)))); - symcount = bfd_canonicalize_symtab(bfd_handle.get(), symtab.get()); - } - - if (dyn_symtab_storage_size > 0) { - dynamic_symtab.reset(static_cast( - malloc(static_cast(dyn_symtab_storage_size)))); - dyn_symcount = bfd_canonicalize_dynamic_symtab(bfd_handle.get(), - dynamic_symtab.get()); - } - - if (symcount <= 0 && dyn_symcount <= 0) { - return r; // damned, that's a stripped file that you got there! - } - - r.handle = move(bfd_handle); - r.symtab = move(symtab); - r.dynamic_symtab = move(dynamic_symtab); - return r; - } - - struct find_sym_result { - bool found; - const char *filename; - const char *funcname; - unsigned int line; - }; - - struct find_sym_context { - TraceResolverLinuxImpl *self; - bfd_fileobject *fobj; - void *addr; - void *base_addr; - find_sym_result result; - }; - - find_sym_result find_symbol_details(bfd_fileobject &fobj, void *addr, - void *base_addr) { - find_sym_context context; - context.self = this; - context.fobj = &fobj; - context.addr = addr; - context.base_addr = base_addr; - context.result.found = false; - bfd_map_over_sections(fobj.handle.get(), &find_in_section_trampoline, - static_cast(&context)); - return context.result; - } - - static void find_in_section_trampoline(bfd *, asection *section, void *data) { - find_sym_context *context = static_cast(data); - context->self->find_in_section( - reinterpret_cast(context->addr), - reinterpret_cast(context->base_addr), *context->fobj, section, - context->result); - } - - void find_in_section(bfd_vma addr, bfd_vma base_addr, bfd_fileobject &fobj, - asection *section, find_sym_result &result) { - if (result.found) - return; - -#ifdef bfd_get_section_flags - if ((bfd_get_section_flags(fobj.handle.get(), section) & SEC_ALLOC) == 0) -#else - if ((bfd_section_flags(section) & SEC_ALLOC) == 0) -#endif - return; // a debug section is never loaded automatically. - -#ifdef bfd_get_section_vma - bfd_vma sec_addr = bfd_get_section_vma(fobj.handle.get(), section); -#else - bfd_vma sec_addr = bfd_section_vma(section); -#endif -#ifdef bfd_get_section_size - bfd_size_type size = bfd_get_section_size(section); -#else - bfd_size_type size = bfd_section_size(section); -#endif - - // are we in the boundaries of the section? - if (addr < sec_addr || addr >= sec_addr + size) { - addr -= base_addr; // oups, a relocated object, lets try again... - if (addr < sec_addr || addr >= sec_addr + size) { - return; - } - } - -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" -#endif - if (!result.found && fobj.symtab) { - result.found = bfd_find_nearest_line( - fobj.handle.get(), section, fobj.symtab.get(), addr - sec_addr, - &result.filename, &result.funcname, &result.line); - } - - if (!result.found && fobj.dynamic_symtab) { - result.found = bfd_find_nearest_line( - fobj.handle.get(), section, fobj.dynamic_symtab.get(), - addr - sec_addr, &result.filename, &result.funcname, &result.line); - } -#if defined(__clang__) -#pragma clang diagnostic pop -#endif - } - - ResolvedTrace::source_locs_t - backtrace_inliners(bfd_fileobject &fobj, find_sym_result previous_result) { - // This function can be called ONLY after a SUCCESSFUL call to - // find_symbol_details. The state is global to the bfd_handle. - ResolvedTrace::source_locs_t results; - while (previous_result.found) { - find_sym_result result; - result.found = bfd_find_inliner_info(fobj.handle.get(), &result.filename, - &result.funcname, &result.line); - - if (result - .found) /* and not ( - cstrings_eq(previous_result.filename, - result.filename) and - cstrings_eq(previous_result.funcname, result.funcname) - and result.line == previous_result.line - )) */ - { - ResolvedTrace::SourceLoc src_loc; - src_loc.line = result.line; - if (result.filename) { - src_loc.filename = result.filename; - } - if (result.funcname) { - src_loc.function = demangle(result.funcname); - } - results.push_back(src_loc); - } - previous_result = result; - } - return results; - } - - bool cstrings_eq(const char *a, const char *b) { - if (!a || !b) { - return false; - } - return strcmp(a, b) == 0; - } -}; -#endif // BACKWARD_HAS_BFD == 1 - -#if BACKWARD_HAS_DW == 1 - -template <> -class TraceResolverLinuxImpl - : public TraceResolverLinuxBase { -public: - TraceResolverLinuxImpl() : _dwfl_handle_initialized(false) {} - - template void load_stacktrace(ST &) {} - - ResolvedTrace resolve(ResolvedTrace trace) { - using namespace details; - - Dwarf_Addr trace_addr = (Dwarf_Addr)trace.addr; - - if (!_dwfl_handle_initialized) { - // initialize dwfl... - _dwfl_cb.reset(new Dwfl_Callbacks); - _dwfl_cb->find_elf = &dwfl_linux_proc_find_elf; - _dwfl_cb->find_debuginfo = &dwfl_standard_find_debuginfo; - _dwfl_cb->debuginfo_path = 0; - - _dwfl_handle.reset(dwfl_begin(_dwfl_cb.get())); - _dwfl_handle_initialized = true; - - if (!_dwfl_handle) { - return trace; - } - - // ...from the current process. - dwfl_report_begin(_dwfl_handle.get()); - int r = dwfl_linux_proc_report(_dwfl_handle.get(), getpid()); - dwfl_report_end(_dwfl_handle.get(), NULL, NULL); - if (r < 0) { - return trace; - } - } - - if (!_dwfl_handle) { - return trace; - } - - // find the module (binary object) that contains the trace's address. - // This is not using any debug information, but the addresses ranges of - // all the currently loaded binary object. - Dwfl_Module *mod = dwfl_addrmodule(_dwfl_handle.get(), trace_addr); - if (mod) { - // now that we found it, lets get the name of it, this will be the - // full path to the running binary or one of the loaded library. - const char *module_name = dwfl_module_info(mod, 0, 0, 0, 0, 0, 0, 0); - if (module_name) { - trace.object_filename = module_name; - } - // We also look after the name of the symbol, equal or before this - // address. This is found by walking the symtab. We should get the - // symbol corresponding to the function (mangled) containing the - // address. If the code corresponding to the address was inlined, - // this is the name of the out-most inliner function. - const char *sym_name = dwfl_module_addrname(mod, trace_addr); - if (sym_name) { - trace.object_function = demangle(sym_name); - } - } - - // now let's get serious, and find out the source location (file and - // line number) of the address. - - // This function will look in .debug_aranges for the address and map it - // to the location of the compilation unit DIE in .debug_info and - // return it. - Dwarf_Addr mod_bias = 0; - Dwarf_Die *cudie = dwfl_module_addrdie(mod, trace_addr, &mod_bias); - -#if 1 - if (!cudie) { - // Sadly clang does not generate the section .debug_aranges, thus - // dwfl_module_addrdie will fail early. Clang doesn't either set - // the lowpc/highpc/range info for every compilation unit. - // - // So in order to save the world: - // for every compilation unit, we will iterate over every single - // DIEs. Normally functions should have a lowpc/highpc/range, which - // we will use to infer the compilation unit. - - // note that this is probably badly inefficient. - while ((cudie = dwfl_module_nextcu(mod, cudie, &mod_bias))) { - Dwarf_Die die_mem; - Dwarf_Die *fundie = - find_fundie_by_pc(cudie, trace_addr - mod_bias, &die_mem); - if (fundie) { - break; - } - } - } -#endif - -//#define BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE -#ifdef BACKWARD_I_DO_NOT_RECOMMEND_TO_ENABLE_THIS_HORRIBLE_PIECE_OF_CODE - if (!cudie) { - // If it's still not enough, lets dive deeper in the shit, and try - // to save the world again: for every compilation unit, we will - // load the corresponding .debug_line section, and see if we can - // find our address in it. - - Dwarf_Addr cfi_bias; - Dwarf_CFI *cfi_cache = dwfl_module_eh_cfi(mod, &cfi_bias); - - Dwarf_Addr bias; - while ((cudie = dwfl_module_nextcu(mod, cudie, &bias))) { - if (dwarf_getsrc_die(cudie, trace_addr - bias)) { - - // ...but if we get a match, it might be a false positive - // because our (address - bias) might as well be valid in a - // different compilation unit. So we throw our last card on - // the table and lookup for the address into the .eh_frame - // section. - - handle frame; - dwarf_cfi_addrframe(cfi_cache, trace_addr - cfi_bias, &frame); - if (frame) { - break; - } - } - } - } -#endif - - if (!cudie) { - return trace; // this time we lost the game :/ - } - - // Now that we have a compilation unit DIE, this function will be able - // to load the corresponding section in .debug_line (if not already - // loaded) and hopefully find the source location mapped to our - // address. - Dwarf_Line *srcloc = dwarf_getsrc_die(cudie, trace_addr - mod_bias); - - if (srcloc) { - const char *srcfile = dwarf_linesrc(srcloc, 0, 0); - if (srcfile) { - trace.source.filename = srcfile; - } - int line = 0, col = 0; - dwarf_lineno(srcloc, &line); - dwarf_linecol(srcloc, &col); - trace.source.line = line; - trace.source.col = col; - } - - deep_first_search_by_pc(cudie, trace_addr - mod_bias, - inliners_search_cb(trace)); - if (trace.source.function.size() == 0) { - // fallback. - trace.source.function = trace.object_function; - } - - return trace; - } - -private: - typedef details::handle> - dwfl_handle_t; - details::handle> - _dwfl_cb; - dwfl_handle_t _dwfl_handle; - bool _dwfl_handle_initialized; - - // defined here because in C++98, template function cannot take locally - // defined types... grrr. - struct inliners_search_cb { - void operator()(Dwarf_Die *die) { - switch (dwarf_tag(die)) { - const char *name; - case DW_TAG_subprogram: - if ((name = dwarf_diename(die))) { - trace.source.function = name; - } - break; - - case DW_TAG_inlined_subroutine: - ResolvedTrace::SourceLoc sloc; - Dwarf_Attribute attr_mem; - - if ((name = dwarf_diename(die))) { - sloc.function = name; - } - if ((name = die_call_file(die))) { - sloc.filename = name; - } - - Dwarf_Word line = 0, col = 0; - dwarf_formudata(dwarf_attr(die, DW_AT_call_line, &attr_mem), &line); - dwarf_formudata(dwarf_attr(die, DW_AT_call_column, &attr_mem), &col); - sloc.line = (unsigned)line; - sloc.col = (unsigned)col; - - trace.inliners.push_back(sloc); - break; - }; - } - ResolvedTrace &trace; - inliners_search_cb(ResolvedTrace &t) : trace(t) {} - }; - - static bool die_has_pc(Dwarf_Die *die, Dwarf_Addr pc) { - Dwarf_Addr low, high; - - // continuous range - if (dwarf_hasattr(die, DW_AT_low_pc) && dwarf_hasattr(die, DW_AT_high_pc)) { - if (dwarf_lowpc(die, &low) != 0) { - return false; - } - if (dwarf_highpc(die, &high) != 0) { - Dwarf_Attribute attr_mem; - Dwarf_Attribute *attr = dwarf_attr(die, DW_AT_high_pc, &attr_mem); - Dwarf_Word value; - if (dwarf_formudata(attr, &value) != 0) { - return false; - } - high = low + value; - } - return pc >= low && pc < high; - } - - // non-continuous range. - Dwarf_Addr base; - ptrdiff_t offset = 0; - while ((offset = dwarf_ranges(die, offset, &base, &low, &high)) > 0) { - if (pc >= low && pc < high) { - return true; - } - } - return false; - } - - static Dwarf_Die *find_fundie_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc, - Dwarf_Die *result) { - if (dwarf_child(parent_die, result) != 0) { - return 0; - } - - Dwarf_Die *die = result; - do { - switch (dwarf_tag(die)) { - case DW_TAG_subprogram: - case DW_TAG_inlined_subroutine: - if (die_has_pc(die, pc)) { - return result; - } - }; - bool declaration = false; - Dwarf_Attribute attr_mem; - dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem), - &declaration); - if (!declaration) { - // let's be curious and look deeper in the tree, - // function are not necessarily at the first level, but - // might be nested inside a namespace, structure etc. - Dwarf_Die die_mem; - Dwarf_Die *indie = find_fundie_by_pc(die, pc, &die_mem); - if (indie) { - *result = die_mem; - return result; - } - } - } while (dwarf_siblingof(die, result) == 0); - return 0; - } - - template - static bool deep_first_search_by_pc(Dwarf_Die *parent_die, Dwarf_Addr pc, - CB cb) { - Dwarf_Die die_mem; - if (dwarf_child(parent_die, &die_mem) != 0) { - return false; - } - - bool branch_has_pc = false; - Dwarf_Die *die = &die_mem; - do { - bool declaration = false; - Dwarf_Attribute attr_mem; - dwarf_formflag(dwarf_attr(die, DW_AT_declaration, &attr_mem), - &declaration); - if (!declaration) { - // let's be curious and look deeper in the tree, function are - // not necessarily at the first level, but might be nested - // inside a namespace, structure, a function, an inlined - // function etc. - branch_has_pc = deep_first_search_by_pc(die, pc, cb); - } - if (!branch_has_pc) { - branch_has_pc = die_has_pc(die, pc); - } - if (branch_has_pc) { - cb(die); - } - } while (dwarf_siblingof(die, &die_mem) == 0); - return branch_has_pc; - } - - static const char *die_call_file(Dwarf_Die *die) { - Dwarf_Attribute attr_mem; - Dwarf_Sword file_idx = 0; - - dwarf_formsdata(dwarf_attr(die, DW_AT_call_file, &attr_mem), &file_idx); - - if (file_idx == 0) { - return 0; - } - - Dwarf_Die die_mem; - Dwarf_Die *cudie = dwarf_diecu(die, &die_mem, 0, 0); - if (!cudie) { - return 0; - } - - Dwarf_Files *files = 0; - size_t nfiles; - dwarf_getsrcfiles(cudie, &files, &nfiles); - if (!files) { - return 0; - } - - return dwarf_filesrc(files, file_idx, 0, 0); - } -}; -#endif // BACKWARD_HAS_DW == 1 - -#if BACKWARD_HAS_DWARF == 1 - -template <> -class TraceResolverLinuxImpl - : public TraceResolverLinuxBase { -public: - TraceResolverLinuxImpl() : _dwarf_loaded(false) {} - - template void load_stacktrace(ST &) {} - - ResolvedTrace resolve(ResolvedTrace trace) { - // trace.addr is a virtual address in memory pointing to some code. - // Let's try to find from which loaded object it comes from. - // The loaded object can be yourself btw. - - Dl_info symbol_info; - int dladdr_result = 0; -#if defined(__GLIBC__) - link_map *link_map; - // We request the link map so we can get information about offsets - dladdr_result = - dladdr1(trace.addr, &symbol_info, reinterpret_cast(&link_map), - RTLD_DL_LINKMAP); -#else - // Android doesn't have dladdr1. Don't use the linker map. - dladdr_result = dladdr(trace.addr, &symbol_info); -#endif - if (!dladdr_result) { - return trace; // dat broken trace... - } - - // Now we get in symbol_info: - // .dli_fname: - // pathname of the shared object that contains the address. - // .dli_fbase: - // where the object is loaded in memory. - // .dli_sname: - // the name of the nearest symbol to trace.addr, we expect a - // function name. - // .dli_saddr: - // the exact address corresponding to .dli_sname. - // - // And in link_map: - // .l_addr: - // difference between the address in the ELF file and the address - // in memory - // l_name: - // absolute pathname where the object was found - - if (symbol_info.dli_sname) { - trace.object_function = demangle(symbol_info.dli_sname); - } - - if (!symbol_info.dli_fname) { - return trace; - } - - trace.object_filename = resolve_exec_path(symbol_info); - dwarf_fileobject &fobj = load_object_with_dwarf(symbol_info.dli_fname); - if (!fobj.dwarf_handle) { - return trace; // sad, we couldn't load the object :( - } - -#if defined(__GLIBC__) - // Convert the address to a module relative one by looking at - // the module's loading address in the link map - Dwarf_Addr address = reinterpret_cast(trace.addr) - - reinterpret_cast(link_map->l_addr); -#else - Dwarf_Addr address = reinterpret_cast(trace.addr); -#endif - - if (trace.object_function.empty()) { - symbol_cache_t::iterator it = fobj.symbol_cache.lower_bound(address); - - if (it != fobj.symbol_cache.end()) { - if (it->first != address) { - if (it != fobj.symbol_cache.begin()) { - --it; - } - } - trace.object_function = demangle(it->second.c_str()); - } - } - - // Get the Compilation Unit DIE for the address - Dwarf_Die die = find_die(fobj, address); - - if (!die) { - return trace; // this time we lost the game :/ - } - - // libdwarf doesn't give us direct access to its objects, it always - // allocates a copy for the caller. We keep that copy alive in a cache - // and we deallocate it later when it's no longer required. - die_cache_entry &die_object = get_die_cache(fobj, die); - if (die_object.isEmpty()) - return trace; // We have no line section for this DIE - - die_linemap_t::iterator it = die_object.line_section.lower_bound(address); - - if (it != die_object.line_section.end()) { - if (it->first != address) { - if (it == die_object.line_section.begin()) { - // If we are on the first item of the line section - // but the address does not match it means that - // the address is below the range of the DIE. Give up. - return trace; - } else { - --it; - } - } - } else { - return trace; // We didn't find the address. - } - - // Get the Dwarf_Line that the address points to and call libdwarf - // to get source file, line and column info. - Dwarf_Line line = die_object.line_buffer[it->second]; - Dwarf_Error error = DW_DLE_NE; - - char *filename; - if (dwarf_linesrc(line, &filename, &error) == DW_DLV_OK) { - trace.source.filename = std::string(filename); - dwarf_dealloc(fobj.dwarf_handle.get(), filename, DW_DLA_STRING); - } - - Dwarf_Unsigned number = 0; - if (dwarf_lineno(line, &number, &error) == DW_DLV_OK) { - trace.source.line = number; - } else { - trace.source.line = 0; - } - - if (dwarf_lineoff_b(line, &number, &error) == DW_DLV_OK) { - trace.source.col = number; - } else { - trace.source.col = 0; - } - - std::vector namespace_stack; - deep_first_search_by_pc(fobj, die, address, namespace_stack, - inliners_search_cb(trace, fobj, die)); - - dwarf_dealloc(fobj.dwarf_handle.get(), die, DW_DLA_DIE); - - return trace; - } - -public: - static int close_dwarf(Dwarf_Debug dwarf) { - return dwarf_finish(dwarf, NULL); - } - -private: - bool _dwarf_loaded; - - typedef details::handle> - dwarf_file_t; - - typedef details::handle> - dwarf_elf_t; - - typedef details::handle> - dwarf_handle_t; - - typedef std::map die_linemap_t; - - typedef std::map die_specmap_t; - - struct die_cache_entry { - die_specmap_t spec_section; - die_linemap_t line_section; - Dwarf_Line *line_buffer; - Dwarf_Signed line_count; - Dwarf_Line_Context line_context; - - inline bool isEmpty() { - return line_buffer == NULL || line_count == 0 || line_context == NULL || - line_section.empty(); - } - - die_cache_entry() : line_buffer(0), line_count(0), line_context(0) {} - - ~die_cache_entry() { - if (line_context) { - dwarf_srclines_dealloc_b(line_context); - } - } - }; - - typedef std::map die_cache_t; - - typedef std::map symbol_cache_t; - - struct dwarf_fileobject { - dwarf_file_t file_handle; - dwarf_elf_t elf_handle; - dwarf_handle_t dwarf_handle; - symbol_cache_t symbol_cache; - - // Die cache - die_cache_t die_cache; - die_cache_entry *current_cu; - }; - - typedef details::hashtable::type - fobj_dwarf_map_t; - fobj_dwarf_map_t _fobj_dwarf_map; - - static bool cstrings_eq(const char *a, const char *b) { - if (!a || !b) { - return false; - } - return strcmp(a, b) == 0; - } - - dwarf_fileobject &load_object_with_dwarf(const std::string &filename_object) { - - if (!_dwarf_loaded) { - // Set the ELF library operating version - // If that fails there's nothing we can do - _dwarf_loaded = elf_version(EV_CURRENT) != EV_NONE; - } - - fobj_dwarf_map_t::iterator it = _fobj_dwarf_map.find(filename_object); - if (it != _fobj_dwarf_map.end()) { - return it->second; - } - - // this new object is empty for now - dwarf_fileobject &r = _fobj_dwarf_map[filename_object]; - - dwarf_file_t file_handle; - file_handle.reset(open(filename_object.c_str(), O_RDONLY)); - if (file_handle.get() < 0) { - return r; - } - - // Try to get an ELF handle. We need to read the ELF sections - // because we want to see if there is a .gnu_debuglink section - // that points to a split debug file - dwarf_elf_t elf_handle; - elf_handle.reset(elf_begin(file_handle.get(), ELF_C_READ, NULL)); - if (!elf_handle) { - return r; - } - - const char *e_ident = elf_getident(elf_handle.get(), 0); - if (!e_ident) { - return r; - } - - // Get the number of sections - // We use the new APIs as elf_getshnum is deprecated - size_t shdrnum = 0; - if (elf_getshdrnum(elf_handle.get(), &shdrnum) == -1) { - return r; - } - - // Get the index to the string section - size_t shdrstrndx = 0; - if (elf_getshdrstrndx(elf_handle.get(), &shdrstrndx) == -1) { - return r; - } - - std::string debuglink; - // Iterate through the ELF sections to try to get a gnu_debuglink - // note and also to cache the symbol table. - // We go the preprocessor way to avoid having to create templated - // classes or using gelf (which might throw a compiler error if 64 bit - // is not supported -#define ELF_GET_DATA(ARCH) \ - Elf_Scn *elf_section = 0; \ - Elf_Data *elf_data = 0; \ - Elf##ARCH##_Shdr *section_header = 0; \ - Elf_Scn *symbol_section = 0; \ - size_t symbol_count = 0; \ - size_t symbol_strings = 0; \ - Elf##ARCH##_Sym *symbol = 0; \ - const char *section_name = 0; \ - \ - while ((elf_section = elf_nextscn(elf_handle.get(), elf_section)) != NULL) { \ - section_header = elf##ARCH##_getshdr(elf_section); \ - if (section_header == NULL) { \ - return r; \ - } \ - \ - if ((section_name = elf_strptr(elf_handle.get(), shdrstrndx, \ - section_header->sh_name)) == NULL) { \ - return r; \ - } \ - \ - if (cstrings_eq(section_name, ".gnu_debuglink")) { \ - elf_data = elf_getdata(elf_section, NULL); \ - if (elf_data && elf_data->d_size > 0) { \ - debuglink = \ - std::string(reinterpret_cast(elf_data->d_buf)); \ - } \ - } \ - \ - switch (section_header->sh_type) { \ - case SHT_SYMTAB: \ - symbol_section = elf_section; \ - symbol_count = section_header->sh_size / section_header->sh_entsize; \ - symbol_strings = section_header->sh_link; \ - break; \ - \ - /* We use .dynsyms as a last resort, we prefer .symtab */ \ - case SHT_DYNSYM: \ - if (!symbol_section) { \ - symbol_section = elf_section; \ - symbol_count = section_header->sh_size / section_header->sh_entsize; \ - symbol_strings = section_header->sh_link; \ - } \ - break; \ - } \ - } \ - \ - if (symbol_section && symbol_count && symbol_strings) { \ - elf_data = elf_getdata(symbol_section, NULL); \ - symbol = reinterpret_cast(elf_data->d_buf); \ - for (size_t i = 0; i < symbol_count; ++i) { \ - int type = ELF##ARCH##_ST_TYPE(symbol->st_info); \ - if (type == STT_FUNC && symbol->st_value > 0) { \ - r.symbol_cache[symbol->st_value] = std::string( \ - elf_strptr(elf_handle.get(), symbol_strings, symbol->st_name)); \ - } \ - ++symbol; \ - } \ - } - - if (e_ident[EI_CLASS] == ELFCLASS32) { - ELF_GET_DATA(32) - } else if (e_ident[EI_CLASS] == ELFCLASS64) { - // libelf might have been built without 64 bit support -#if __LIBELF64 - ELF_GET_DATA(64) -#endif - } - - if (!debuglink.empty()) { - // We have a debuglink section! Open an elf instance on that - // file instead. If we can't open the file, then return - // the elf handle we had already opened. - dwarf_file_t debuglink_file; - debuglink_file.reset(open(debuglink.c_str(), O_RDONLY)); - if (debuglink_file.get() > 0) { - dwarf_elf_t debuglink_elf; - debuglink_elf.reset(elf_begin(debuglink_file.get(), ELF_C_READ, NULL)); - - // If we have a valid elf handle, return the new elf handle - // and file handle and discard the original ones - if (debuglink_elf) { - elf_handle = move(debuglink_elf); - file_handle = move(debuglink_file); - } - } - } - - // Ok, we have a valid ELF handle, let's try to get debug symbols - Dwarf_Debug dwarf_debug; - Dwarf_Error error = DW_DLE_NE; - dwarf_handle_t dwarf_handle; - - int dwarf_result = dwarf_elf_init(elf_handle.get(), DW_DLC_READ, NULL, NULL, - &dwarf_debug, &error); - - // We don't do any special handling for DW_DLV_NO_ENTRY specially. - // If we get an error, or the file doesn't have debug information - // we just return. - if (dwarf_result != DW_DLV_OK) { - return r; - } - - dwarf_handle.reset(dwarf_debug); - - r.file_handle = move(file_handle); - r.elf_handle = move(elf_handle); - r.dwarf_handle = move(dwarf_handle); - - return r; - } - - die_cache_entry &get_die_cache(dwarf_fileobject &fobj, Dwarf_Die die) { - Dwarf_Error error = DW_DLE_NE; - - // Get the die offset, we use it as the cache key - Dwarf_Off die_offset; - if (dwarf_dieoffset(die, &die_offset, &error) != DW_DLV_OK) { - die_offset = 0; - } - - die_cache_t::iterator it = fobj.die_cache.find(die_offset); - - if (it != fobj.die_cache.end()) { - fobj.current_cu = &it->second; - return it->second; - } - - die_cache_entry &de = fobj.die_cache[die_offset]; - fobj.current_cu = &de; - - Dwarf_Addr line_addr; - Dwarf_Small table_count; - - // The addresses in the line section are not fully sorted (they might - // be sorted by block of code belonging to the same file), which makes - // it necessary to do so before searching is possible. - // - // As libdwarf allocates a copy of everything, let's get the contents - // of the line section and keep it around. We also create a map of - // program counter to line table indices so we can search by address - // and get the line buffer index. - // - // To make things more difficult, the same address can span more than - // one line, so we need to keep the index pointing to the first line - // by using insert instead of the map's [ operator. - - // Get the line context for the DIE - if (dwarf_srclines_b(die, 0, &table_count, &de.line_context, &error) == - DW_DLV_OK) { - // Get the source lines for this line context, to be deallocated - // later - if (dwarf_srclines_from_linecontext(de.line_context, &de.line_buffer, - &de.line_count, - &error) == DW_DLV_OK) { - - // Add all the addresses to our map - for (int i = 0; i < de.line_count; i++) { - if (dwarf_lineaddr(de.line_buffer[i], &line_addr, &error) != - DW_DLV_OK) { - line_addr = 0; - } - de.line_section.insert(std::pair(line_addr, i)); - } - } - } - - // For each CU, cache the function DIEs that contain the - // DW_AT_specification attribute. When building with -g3 the function - // DIEs are separated in declaration and specification, with the - // declaration containing only the name and parameters and the - // specification the low/high pc and other compiler attributes. - // - // We cache those specifications so we don't skip over the declarations, - // because they have no pc, and we can do namespace resolution for - // DWARF function names. - Dwarf_Debug dwarf = fobj.dwarf_handle.get(); - Dwarf_Die current_die = 0; - if (dwarf_child(die, ¤t_die, &error) == DW_DLV_OK) { - for (;;) { - Dwarf_Die sibling_die = 0; - - Dwarf_Half tag_value; - dwarf_tag(current_die, &tag_value, &error); - - if (tag_value == DW_TAG_subprogram || - tag_value == DW_TAG_inlined_subroutine) { - - Dwarf_Bool has_attr = 0; - if (dwarf_hasattr(current_die, DW_AT_specification, &has_attr, - &error) == DW_DLV_OK) { - if (has_attr) { - Dwarf_Attribute attr_mem; - if (dwarf_attr(current_die, DW_AT_specification, &attr_mem, - &error) == DW_DLV_OK) { - Dwarf_Off spec_offset = 0; - if (dwarf_formref(attr_mem, &spec_offset, &error) == - DW_DLV_OK) { - Dwarf_Off spec_die_offset; - if (dwarf_dieoffset(current_die, &spec_die_offset, &error) == - DW_DLV_OK) { - de.spec_section[spec_offset] = spec_die_offset; - } - } - } - dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR); - } - } - } - - int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error); - if (result == DW_DLV_ERROR) { - break; - } else if (result == DW_DLV_NO_ENTRY) { - break; - } - - if (current_die != die) { - dwarf_dealloc(dwarf, current_die, DW_DLA_DIE); - current_die = 0; - } - - current_die = sibling_die; - } - } - return de; - } - - static Dwarf_Die get_referenced_die(Dwarf_Debug dwarf, Dwarf_Die die, - Dwarf_Half attr, bool global) { - Dwarf_Error error = DW_DLE_NE; - Dwarf_Attribute attr_mem; - - Dwarf_Die found_die = NULL; - if (dwarf_attr(die, attr, &attr_mem, &error) == DW_DLV_OK) { - Dwarf_Off offset; - int result = 0; - if (global) { - result = dwarf_global_formref(attr_mem, &offset, &error); - } else { - result = dwarf_formref(attr_mem, &offset, &error); - } - - if (result == DW_DLV_OK) { - if (dwarf_offdie(dwarf, offset, &found_die, &error) != DW_DLV_OK) { - found_die = NULL; - } - } - dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR); - } - return found_die; - } - - static std::string get_referenced_die_name(Dwarf_Debug dwarf, Dwarf_Die die, - Dwarf_Half attr, bool global) { - Dwarf_Error error = DW_DLE_NE; - std::string value; - - Dwarf_Die found_die = get_referenced_die(dwarf, die, attr, global); - - if (found_die) { - char *name; - if (dwarf_diename(found_die, &name, &error) == DW_DLV_OK) { - if (name) { - value = std::string(name); - } - dwarf_dealloc(dwarf, name, DW_DLA_STRING); - } - dwarf_dealloc(dwarf, found_die, DW_DLA_DIE); - } - - return value; - } - - // Returns a spec DIE linked to the passed one. The caller should - // deallocate the DIE - static Dwarf_Die get_spec_die(dwarf_fileobject &fobj, Dwarf_Die die) { - Dwarf_Debug dwarf = fobj.dwarf_handle.get(); - Dwarf_Error error = DW_DLE_NE; - Dwarf_Off die_offset; - if (fobj.current_cu && - dwarf_die_CU_offset(die, &die_offset, &error) == DW_DLV_OK) { - die_specmap_t::iterator it = - fobj.current_cu->spec_section.find(die_offset); - - // If we have a DIE that completes the current one, check if - // that one has the pc we are looking for - if (it != fobj.current_cu->spec_section.end()) { - Dwarf_Die spec_die = 0; - if (dwarf_offdie(dwarf, it->second, &spec_die, &error) == DW_DLV_OK) { - return spec_die; - } - } - } - - // Maybe we have an abstract origin DIE with the function information? - return get_referenced_die(fobj.dwarf_handle.get(), die, - DW_AT_abstract_origin, true); - } - - static bool die_has_pc(dwarf_fileobject &fobj, Dwarf_Die die, Dwarf_Addr pc) { - Dwarf_Addr low_pc = 0, high_pc = 0; - Dwarf_Half high_pc_form = 0; - Dwarf_Form_Class return_class; - Dwarf_Error error = DW_DLE_NE; - Dwarf_Debug dwarf = fobj.dwarf_handle.get(); - bool has_lowpc = false; - bool has_highpc = false; - bool has_ranges = false; - - if (dwarf_lowpc(die, &low_pc, &error) == DW_DLV_OK) { - // If we have a low_pc check if there is a high pc. - // If we don't have a high pc this might mean we have a base - // address for the ranges list or just an address. - has_lowpc = true; - - if (dwarf_highpc_b(die, &high_pc, &high_pc_form, &return_class, &error) == - DW_DLV_OK) { - // We do have a high pc. In DWARF 4+ this is an offset from the - // low pc, but in earlier versions it's an absolute address. - - has_highpc = true; - // In DWARF 2/3 this would be a DW_FORM_CLASS_ADDRESS - if (return_class == DW_FORM_CLASS_CONSTANT) { - high_pc = low_pc + high_pc; - } - - // We have low and high pc, check if our address - // is in that range - return pc >= low_pc && pc < high_pc; - } - } else { - // Reset the low_pc, in case dwarf_lowpc failing set it to some - // undefined value. - low_pc = 0; - } - - // Check if DW_AT_ranges is present and search for the PC in the - // returned ranges list. We always add the low_pc, as it not set it will - // be 0, in case we had a DW_AT_low_pc and DW_AT_ranges pair - bool result = false; - - Dwarf_Attribute attr; - if (dwarf_attr(die, DW_AT_ranges, &attr, &error) == DW_DLV_OK) { - - Dwarf_Off offset; - if (dwarf_global_formref(attr, &offset, &error) == DW_DLV_OK) { - Dwarf_Ranges *ranges; - Dwarf_Signed ranges_count = 0; - Dwarf_Unsigned byte_count = 0; - - if (dwarf_get_ranges_a(dwarf, offset, die, &ranges, &ranges_count, - &byte_count, &error) == DW_DLV_OK) { - has_ranges = ranges_count != 0; - for (int i = 0; i < ranges_count; i++) { - if (ranges[i].dwr_addr1 != 0 && - pc >= ranges[i].dwr_addr1 + low_pc && - pc < ranges[i].dwr_addr2 + low_pc) { - result = true; - break; - } - } - dwarf_ranges_dealloc(dwarf, ranges, ranges_count); - } - } - } - - // Last attempt. We might have a single address set as low_pc. - if (!result && low_pc != 0 && pc == low_pc) { - result = true; - } - - // If we don't have lowpc, highpc and ranges maybe this DIE is a - // declaration that relies on a DW_AT_specification DIE that happens - // later. Use the specification cache we filled when we loaded this CU. - if (!result && (!has_lowpc && !has_highpc && !has_ranges)) { - Dwarf_Die spec_die = get_spec_die(fobj, die); - if (spec_die) { - result = die_has_pc(fobj, spec_die, pc); - dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE); - } - } - - return result; - } - - static void get_type(Dwarf_Debug dwarf, Dwarf_Die die, std::string &type) { - Dwarf_Error error = DW_DLE_NE; - - Dwarf_Die child = 0; - if (dwarf_child(die, &child, &error) == DW_DLV_OK) { - get_type(dwarf, child, type); - } - - if (child) { - type.insert(0, "::"); - dwarf_dealloc(dwarf, child, DW_DLA_DIE); - } - - char *name; - if (dwarf_diename(die, &name, &error) == DW_DLV_OK) { - type.insert(0, std::string(name)); - dwarf_dealloc(dwarf, name, DW_DLA_STRING); - } else { - type.insert(0, ""); - } - } - - static std::string get_type_by_signature(Dwarf_Debug dwarf, Dwarf_Die die) { - Dwarf_Error error = DW_DLE_NE; - - Dwarf_Sig8 signature; - Dwarf_Bool has_attr = 0; - if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) == DW_DLV_OK) { - if (has_attr) { - Dwarf_Attribute attr_mem; - if (dwarf_attr(die, DW_AT_signature, &attr_mem, &error) == DW_DLV_OK) { - if (dwarf_formsig8(attr_mem, &signature, &error) != DW_DLV_OK) { - return std::string(""); - } - } - dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR); - } - } - - Dwarf_Unsigned next_cu_header; - Dwarf_Sig8 tu_signature; - std::string result; - bool found = false; - - while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, &tu_signature, 0, - &next_cu_header, 0, &error) == DW_DLV_OK) { - - if (strncmp(signature.signature, tu_signature.signature, 8) == 0) { - Dwarf_Die type_cu_die = 0; - if (dwarf_siblingof_b(dwarf, 0, 0, &type_cu_die, &error) == DW_DLV_OK) { - Dwarf_Die child_die = 0; - if (dwarf_child(type_cu_die, &child_die, &error) == DW_DLV_OK) { - get_type(dwarf, child_die, result); - found = !result.empty(); - dwarf_dealloc(dwarf, child_die, DW_DLA_DIE); - } - dwarf_dealloc(dwarf, type_cu_die, DW_DLA_DIE); - } - } - } - - if (found) { - while (dwarf_next_cu_header_d(dwarf, 0, 0, 0, 0, 0, 0, 0, 0, 0, - &next_cu_header, 0, &error) == DW_DLV_OK) { - // Reset the cu header state. Unfortunately, libdwarf's - // next_cu_header API keeps its own iterator per Dwarf_Debug - // that can't be reset. We need to keep fetching elements until - // the end. - } - } else { - // If we couldn't resolve the type just print out the signature - std::ostringstream string_stream; - string_stream << "<0x" << std::hex << std::setfill('0'); - for (int i = 0; i < 8; ++i) { - string_stream << std::setw(2) << std::hex - << (int)(unsigned char)(signature.signature[i]); - } - string_stream << ">"; - result = string_stream.str(); - } - return result; - } - - struct type_context_t { - bool is_const; - bool is_typedef; - bool has_type; - bool has_name; - std::string text; - - type_context_t() - : is_const(false), is_typedef(false), has_type(false), has_name(false) { - } - }; - - // Types are resolved from right to left: we get the variable name first - // and then all specifiers (like const or pointer) in a chain of DW_AT_type - // DIEs. Call this function recursively until we get a complete type - // string. - static void set_parameter_string(dwarf_fileobject &fobj, Dwarf_Die die, - type_context_t &context) { - char *name; - Dwarf_Error error = DW_DLE_NE; - - // typedefs contain also the base type, so we skip it and only - // print the typedef name - if (!context.is_typedef) { - if (dwarf_diename(die, &name, &error) == DW_DLV_OK) { - if (!context.text.empty()) { - context.text.insert(0, " "); - } - context.text.insert(0, std::string(name)); - dwarf_dealloc(fobj.dwarf_handle.get(), name, DW_DLA_STRING); - } - } else { - context.is_typedef = false; - context.has_type = true; - if (context.is_const) { - context.text.insert(0, "const "); - context.is_const = false; - } - } - - bool next_type_is_const = false; - bool is_keyword = true; - - Dwarf_Half tag = 0; - Dwarf_Bool has_attr = 0; - if (dwarf_tag(die, &tag, &error) == DW_DLV_OK) { - switch (tag) { - case DW_TAG_structure_type: - case DW_TAG_union_type: - case DW_TAG_class_type: - case DW_TAG_enumeration_type: - context.has_type = true; - if (dwarf_hasattr(die, DW_AT_signature, &has_attr, &error) == - DW_DLV_OK) { - // If we have a signature it means the type is defined - // in .debug_types, so we need to load the DIE pointed - // at by the signature and resolve it - if (has_attr) { - std::string type = - get_type_by_signature(fobj.dwarf_handle.get(), die); - if (context.is_const) - type.insert(0, "const "); - - if (!context.text.empty()) - context.text.insert(0, " "); - context.text.insert(0, type); - } - - // Treat enums like typedefs, and skip printing its - // base type - context.is_typedef = (tag == DW_TAG_enumeration_type); - } - break; - case DW_TAG_const_type: - next_type_is_const = true; - break; - case DW_TAG_pointer_type: - context.text.insert(0, "*"); - break; - case DW_TAG_reference_type: - context.text.insert(0, "&"); - break; - case DW_TAG_restrict_type: - context.text.insert(0, "restrict "); - break; - case DW_TAG_rvalue_reference_type: - context.text.insert(0, "&&"); - break; - case DW_TAG_volatile_type: - context.text.insert(0, "volatile "); - break; - case DW_TAG_typedef: - // Propagate the const-ness to the next type - // as typedefs are linked to its base type - next_type_is_const = context.is_const; - context.is_typedef = true; - context.has_type = true; - break; - case DW_TAG_base_type: - context.has_type = true; - break; - case DW_TAG_formal_parameter: - context.has_name = true; - break; - default: - is_keyword = false; - break; - } - } - - if (!is_keyword && context.is_const) { - context.text.insert(0, "const "); - } - - context.is_const = next_type_is_const; - - Dwarf_Die ref = - get_referenced_die(fobj.dwarf_handle.get(), die, DW_AT_type, true); - if (ref) { - set_parameter_string(fobj, ref, context); - dwarf_dealloc(fobj.dwarf_handle.get(), ref, DW_DLA_DIE); - } - - if (!context.has_type && context.has_name) { - context.text.insert(0, "void "); - context.has_type = true; - } - } - - // Resolve the function return type and parameters - static void set_function_parameters(std::string &function_name, - std::vector &ns, - dwarf_fileobject &fobj, Dwarf_Die die) { - Dwarf_Debug dwarf = fobj.dwarf_handle.get(); - Dwarf_Error error = DW_DLE_NE; - Dwarf_Die current_die = 0; - std::string parameters; - bool has_spec = true; - // Check if we have a spec DIE. If we do we use it as it contains - // more information, like parameter names. - Dwarf_Die spec_die = get_spec_die(fobj, die); - if (!spec_die) { - has_spec = false; - spec_die = die; - } - - std::vector::const_iterator it = ns.begin(); - std::string ns_name; - for (it = ns.begin(); it < ns.end(); ++it) { - ns_name.append(*it).append("::"); - } - - if (!ns_name.empty()) { - function_name.insert(0, ns_name); - } - - // See if we have a function return type. It can be either on the - // current die or in its spec one (usually true for inlined functions) - std::string return_type = - get_referenced_die_name(dwarf, die, DW_AT_type, true); - if (return_type.empty()) { - return_type = get_referenced_die_name(dwarf, spec_die, DW_AT_type, true); - } - if (!return_type.empty()) { - return_type.append(" "); - function_name.insert(0, return_type); - } - - if (dwarf_child(spec_die, ¤t_die, &error) == DW_DLV_OK) { - for (;;) { - Dwarf_Die sibling_die = 0; - - Dwarf_Half tag_value; - dwarf_tag(current_die, &tag_value, &error); - - if (tag_value == DW_TAG_formal_parameter) { - // Ignore artificial (ie, compiler generated) parameters - bool is_artificial = false; - Dwarf_Attribute attr_mem; - if (dwarf_attr(current_die, DW_AT_artificial, &attr_mem, &error) == - DW_DLV_OK) { - Dwarf_Bool flag = 0; - if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) { - is_artificial = flag != 0; - } - dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR); - } - - if (!is_artificial) { - type_context_t context; - set_parameter_string(fobj, current_die, context); - - if (parameters.empty()) { - parameters.append("("); - } else { - parameters.append(", "); - } - parameters.append(context.text); - } - } - - int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error); - if (result == DW_DLV_ERROR) { - break; - } else if (result == DW_DLV_NO_ENTRY) { - break; - } - - if (current_die != die) { - dwarf_dealloc(dwarf, current_die, DW_DLA_DIE); - current_die = 0; - } - - current_die = sibling_die; - } - } - if (parameters.empty()) - parameters = "("; - parameters.append(")"); - - // If we got a spec DIE we need to deallocate it - if (has_spec) - dwarf_dealloc(dwarf, spec_die, DW_DLA_DIE); - - function_name.append(parameters); - } - - // defined here because in C++98, template function cannot take locally - // defined types... grrr. - struct inliners_search_cb { - void operator()(Dwarf_Die die, std::vector &ns) { - Dwarf_Error error = DW_DLE_NE; - Dwarf_Half tag_value; - Dwarf_Attribute attr_mem; - Dwarf_Debug dwarf = fobj.dwarf_handle.get(); - - dwarf_tag(die, &tag_value, &error); - - switch (tag_value) { - char *name; - case DW_TAG_subprogram: - if (!trace.source.function.empty()) - break; - if (dwarf_diename(die, &name, &error) == DW_DLV_OK) { - trace.source.function = std::string(name); - dwarf_dealloc(dwarf, name, DW_DLA_STRING); - } else { - // We don't have a function name in this DIE. - // Check if there is a referenced non-defining - // declaration. - trace.source.function = - get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true); - if (trace.source.function.empty()) { - trace.source.function = - get_referenced_die_name(dwarf, die, DW_AT_specification, true); - } - } - - // Append the function parameters, if available - set_function_parameters(trace.source.function, ns, fobj, die); - - // If the object function name is empty, it's possible that - // there is no dynamic symbol table (maybe the executable - // was stripped or not built with -rdynamic). See if we have - // a DWARF linkage name to use instead. We try both - // linkage_name and MIPS_linkage_name because the MIPS tag - // was the unofficial one until it was adopted in DWARF4. - // Old gcc versions generate MIPS_linkage_name - if (trace.object_function.empty()) { - details::demangler demangler; - - if (dwarf_attr(die, DW_AT_linkage_name, &attr_mem, &error) != - DW_DLV_OK) { - if (dwarf_attr(die, DW_AT_MIPS_linkage_name, &attr_mem, &error) != - DW_DLV_OK) { - break; - } - } - - char *linkage; - if (dwarf_formstring(attr_mem, &linkage, &error) == DW_DLV_OK) { - trace.object_function = demangler.demangle(linkage); - dwarf_dealloc(dwarf, linkage, DW_DLA_STRING); - } - dwarf_dealloc(dwarf, name, DW_DLA_ATTR); - } - break; - - case DW_TAG_inlined_subroutine: - ResolvedTrace::SourceLoc sloc; - - if (dwarf_diename(die, &name, &error) == DW_DLV_OK) { - sloc.function = std::string(name); - dwarf_dealloc(dwarf, name, DW_DLA_STRING); - } else { - // We don't have a name for this inlined DIE, it could - // be that there is an abstract origin instead. - // Get the DW_AT_abstract_origin value, which is a - // reference to the source DIE and try to get its name - sloc.function = - get_referenced_die_name(dwarf, die, DW_AT_abstract_origin, true); - } - - set_function_parameters(sloc.function, ns, fobj, die); - - std::string file = die_call_file(dwarf, die, cu_die); - if (!file.empty()) - sloc.filename = file; - - Dwarf_Unsigned number = 0; - if (dwarf_attr(die, DW_AT_call_line, &attr_mem, &error) == DW_DLV_OK) { - if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) { - sloc.line = number; - } - dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR); - } - - if (dwarf_attr(die, DW_AT_call_column, &attr_mem, &error) == - DW_DLV_OK) { - if (dwarf_formudata(attr_mem, &number, &error) == DW_DLV_OK) { - sloc.col = number; - } - dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR); - } - - trace.inliners.push_back(sloc); - break; - }; - } - ResolvedTrace &trace; - dwarf_fileobject &fobj; - Dwarf_Die cu_die; - inliners_search_cb(ResolvedTrace &t, dwarf_fileobject &f, Dwarf_Die c) - : trace(t), fobj(f), cu_die(c) {} - }; - - static Dwarf_Die find_fundie_by_pc(dwarf_fileobject &fobj, - Dwarf_Die parent_die, Dwarf_Addr pc, - Dwarf_Die result) { - Dwarf_Die current_die = 0; - Dwarf_Error error = DW_DLE_NE; - Dwarf_Debug dwarf = fobj.dwarf_handle.get(); - - if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) { - return NULL; - } - - for (;;) { - Dwarf_Die sibling_die = 0; - Dwarf_Half tag_value; - dwarf_tag(current_die, &tag_value, &error); - - switch (tag_value) { - case DW_TAG_subprogram: - case DW_TAG_inlined_subroutine: - if (die_has_pc(fobj, current_die, pc)) { - return current_die; - } - }; - bool declaration = false; - Dwarf_Attribute attr_mem; - if (dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) == - DW_DLV_OK) { - Dwarf_Bool flag = 0; - if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) { - declaration = flag != 0; - } - dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR); - } - - if (!declaration) { - // let's be curious and look deeper in the tree, functions are - // not necessarily at the first level, but might be nested - // inside a namespace, structure, a function, an inlined - // function etc. - Dwarf_Die die_mem = 0; - Dwarf_Die indie = find_fundie_by_pc(fobj, current_die, pc, die_mem); - if (indie) { - result = die_mem; - return result; - } - } - - int res = dwarf_siblingof(dwarf, current_die, &sibling_die, &error); - if (res == DW_DLV_ERROR) { - return NULL; - } else if (res == DW_DLV_NO_ENTRY) { - break; - } - - if (current_die != parent_die) { - dwarf_dealloc(dwarf, current_die, DW_DLA_DIE); - current_die = 0; - } - - current_die = sibling_die; - } - return NULL; - } - - template - static bool deep_first_search_by_pc(dwarf_fileobject &fobj, - Dwarf_Die parent_die, Dwarf_Addr pc, - std::vector &ns, CB cb) { - Dwarf_Die current_die = 0; - Dwarf_Debug dwarf = fobj.dwarf_handle.get(); - Dwarf_Error error = DW_DLE_NE; - - if (dwarf_child(parent_die, ¤t_die, &error) != DW_DLV_OK) { - return false; - } - - bool branch_has_pc = false; - bool has_namespace = false; - for (;;) { - Dwarf_Die sibling_die = 0; - - Dwarf_Half tag; - if (dwarf_tag(current_die, &tag, &error) == DW_DLV_OK) { - if (tag == DW_TAG_namespace || tag == DW_TAG_class_type) { - char *ns_name = NULL; - if (dwarf_diename(current_die, &ns_name, &error) == DW_DLV_OK) { - if (ns_name) { - ns.push_back(std::string(ns_name)); - } else { - ns.push_back(""); - } - dwarf_dealloc(dwarf, ns_name, DW_DLA_STRING); - } else { - ns.push_back(""); - } - has_namespace = true; - } - } - - bool declaration = false; - Dwarf_Attribute attr_mem; - if (tag != DW_TAG_class_type && - dwarf_attr(current_die, DW_AT_declaration, &attr_mem, &error) == - DW_DLV_OK) { - Dwarf_Bool flag = 0; - if (dwarf_formflag(attr_mem, &flag, &error) == DW_DLV_OK) { - declaration = flag != 0; - } - dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR); - } - - if (!declaration) { - // let's be curious and look deeper in the tree, function are - // not necessarily at the first level, but might be nested - // inside a namespace, structure, a function, an inlined - // function etc. - branch_has_pc = deep_first_search_by_pc(fobj, current_die, pc, ns, cb); - } - - if (!branch_has_pc) { - branch_has_pc = die_has_pc(fobj, current_die, pc); - } - - if (branch_has_pc) { - cb(current_die, ns); - } - - int result = dwarf_siblingof(dwarf, current_die, &sibling_die, &error); - if (result == DW_DLV_ERROR) { - return false; - } else if (result == DW_DLV_NO_ENTRY) { - break; - } - - if (current_die != parent_die) { - dwarf_dealloc(dwarf, current_die, DW_DLA_DIE); - current_die = 0; - } - - if (has_namespace) { - has_namespace = false; - ns.pop_back(); - } - current_die = sibling_die; - } - - if (has_namespace) { - ns.pop_back(); - } - return branch_has_pc; - } - - static std::string die_call_file(Dwarf_Debug dwarf, Dwarf_Die die, - Dwarf_Die cu_die) { - Dwarf_Attribute attr_mem; - Dwarf_Error error = DW_DLE_NE; - Dwarf_Signed file_index; - - std::string file; - - if (dwarf_attr(die, DW_AT_call_file, &attr_mem, &error) == DW_DLV_OK) { - if (dwarf_formsdata(attr_mem, &file_index, &error) != DW_DLV_OK) { - file_index = 0; - } - dwarf_dealloc(dwarf, attr_mem, DW_DLA_ATTR); - - if (file_index == 0) { - return file; - } - - char **srcfiles = 0; - Dwarf_Signed file_count = 0; - if (dwarf_srcfiles(cu_die, &srcfiles, &file_count, &error) == DW_DLV_OK) { - if (file_index <= file_count) - file = std::string(srcfiles[file_index - 1]); - - // Deallocate all strings! - for (int i = 0; i < file_count; ++i) { - dwarf_dealloc(dwarf, srcfiles[i], DW_DLA_STRING); - } - dwarf_dealloc(dwarf, srcfiles, DW_DLA_LIST); - } - } - return file; - } - - Dwarf_Die find_die(dwarf_fileobject &fobj, Dwarf_Addr addr) { - // Let's get to work! First see if we have a debug_aranges section so - // we can speed up the search - - Dwarf_Debug dwarf = fobj.dwarf_handle.get(); - Dwarf_Error error = DW_DLE_NE; - Dwarf_Arange *aranges; - Dwarf_Signed arange_count; - - Dwarf_Die returnDie; - bool found = false; - if (dwarf_get_aranges(dwarf, &aranges, &arange_count, &error) != - DW_DLV_OK) { - aranges = NULL; - } - - if (aranges) { - // We have aranges. Get the one where our address is. - Dwarf_Arange arange; - if (dwarf_get_arange(aranges, arange_count, addr, &arange, &error) == - DW_DLV_OK) { - - // We found our address. Get the compilation-unit DIE offset - // represented by the given address range. - Dwarf_Off cu_die_offset; - if (dwarf_get_cu_die_offset(arange, &cu_die_offset, &error) == - DW_DLV_OK) { - // Get the DIE at the offset returned by the aranges search. - // We set is_info to 1 to specify that the offset is from - // the .debug_info section (and not .debug_types) - int dwarf_result = - dwarf_offdie_b(dwarf, cu_die_offset, 1, &returnDie, &error); - - found = dwarf_result == DW_DLV_OK; - } - dwarf_dealloc(dwarf, arange, DW_DLA_ARANGE); - } - } - - if (found) - return returnDie; // The caller is responsible for freeing the die - - // The search for aranges failed. Try to find our address by scanning - // all compilation units. - Dwarf_Unsigned next_cu_header; - Dwarf_Half tag = 0; - returnDie = 0; - - while (!found && - dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0, - &next_cu_header, 0, &error) == DW_DLV_OK) { - - if (returnDie) - dwarf_dealloc(dwarf, returnDie, DW_DLA_DIE); - - if (dwarf_siblingof(dwarf, 0, &returnDie, &error) == DW_DLV_OK) { - if ((dwarf_tag(returnDie, &tag, &error) == DW_DLV_OK) && - tag == DW_TAG_compile_unit) { - if (die_has_pc(fobj, returnDie, addr)) { - found = true; - } - } - } - } - - if (found) { - while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0, - &next_cu_header, 0, &error) == DW_DLV_OK) { - // Reset the cu header state. Libdwarf's next_cu_header API - // keeps its own iterator per Dwarf_Debug that can't be reset. - // We need to keep fetching elements until the end. - } - } - - if (found) - return returnDie; - - // We couldn't find any compilation units with ranges or a high/low pc. - // Try again by looking at all DIEs in all compilation units. - Dwarf_Die cudie; - while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0, - &next_cu_header, 0, &error) == DW_DLV_OK) { - if (dwarf_siblingof(dwarf, 0, &cudie, &error) == DW_DLV_OK) { - Dwarf_Die die_mem = 0; - Dwarf_Die resultDie = find_fundie_by_pc(fobj, cudie, addr, die_mem); - - if (resultDie) { - found = true; - break; - } - } - } - - if (found) { - while (dwarf_next_cu_header_d(dwarf, 1, 0, 0, 0, 0, 0, 0, 0, 0, - &next_cu_header, 0, &error) == DW_DLV_OK) { - // Reset the cu header state. Libdwarf's next_cu_header API - // keeps its own iterator per Dwarf_Debug that can't be reset. - // We need to keep fetching elements until the end. - } - } - - if (found) - return cudie; - - // We failed. - return NULL; - } -}; -#endif // BACKWARD_HAS_DWARF == 1 - -template <> -class TraceResolverImpl - : public TraceResolverLinuxImpl {}; - -#endif // BACKWARD_SYSTEM_LINUX - -#ifdef BACKWARD_SYSTEM_DARWIN - -template class TraceResolverDarwinImpl; - -template <> -class TraceResolverDarwinImpl - : public TraceResolverImplBase { -public: - template void load_stacktrace(ST &st) { - using namespace details; - if (st.size() == 0) { - return; - } - _symbols.reset(backtrace_symbols(st.begin(), st.size())); - } - - ResolvedTrace resolve(ResolvedTrace trace) { - // parse: - // + - char *filename = _symbols[trace.idx]; - - // skip " " - while (*filename && *filename != ' ') - filename++; - while (*filename == ' ') - filename++; - - // find start of from end ( may contain a space) - char *p = filename + strlen(filename) - 1; - // skip to start of " + " - while (p > filename && *p != ' ') - p--; - while (p > filename && *p == ' ') - p--; - while (p > filename && *p != ' ') - p--; - while (p > filename && *p == ' ') - p--; - char *funcname_end = p + 1; - - // skip to start of "" - while (p > filename && *p != ' ') - p--; - char *funcname = p + 1; - - // skip to start of " " - while (p > filename && *p == ' ') - p--; - while (p > filename && *p != ' ') - p--; - while (p > filename && *p == ' ') - p--; - - // skip "", handling the case where it contains a - char *filename_end = p + 1; - if (p == filename) { - // something went wrong, give up - filename_end = filename + strlen(filename); - funcname = filename_end; - } - trace.object_filename.assign( - filename, filename_end); // ok even if filename_end is the ending \0 - // (then we assign entire string) - - if (*funcname) { // if it's not end of string - *funcname_end = '\0'; - - trace.object_function = this->demangle(funcname); - trace.object_function += " "; - trace.object_function += (funcname_end + 1); - trace.source.function = trace.object_function; // we cannot do better. - } - return trace; - } - -private: - details::handle _symbols; -}; - -template <> -class TraceResolverImpl - : public TraceResolverDarwinImpl {}; - -#endif // BACKWARD_SYSTEM_DARWIN - -#ifdef BACKWARD_SYSTEM_WINDOWS - -// Load all symbol info -// Based on: -// https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app/28276227#28276227 - -struct module_data { - std::string image_name; - std::string module_name; - void *base_address; - DWORD load_size; -}; - -class get_mod_info { - HANDLE process; - static const int buffer_length = 4096; - -public: - get_mod_info(HANDLE h) : process(h) {} - - module_data operator()(HMODULE module) { - module_data ret; - char temp[buffer_length]; - MODULEINFO mi; - - GetModuleInformation(process, module, &mi, sizeof(mi)); - ret.base_address = mi.lpBaseOfDll; - ret.load_size = mi.SizeOfImage; - - GetModuleFileNameEx(process, module, temp, sizeof(temp)); - ret.image_name = temp; - GetModuleBaseName(process, module, temp, sizeof(temp)); - ret.module_name = temp; - std::vector img(ret.image_name.begin(), ret.image_name.end()); - std::vector mod(ret.module_name.begin(), ret.module_name.end()); - SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address, - ret.load_size); - return ret; - } -}; - -template <> class TraceResolverImpl { -public: - TraceResolverImpl() { - - HANDLE process = GetCurrentProcess(); - - std::vector modules; - DWORD cbNeeded; - std::vector module_handles(1); - SymInitialize(process, NULL, false); - DWORD symOptions = SymGetOptions(); - symOptions |= SYMOPT_LOAD_LINES | SYMOPT_UNDNAME; - SymSetOptions(symOptions); - EnumProcessModules(process, &module_handles[0], - module_handles.size() * sizeof(HMODULE), &cbNeeded); - module_handles.resize(cbNeeded / sizeof(HMODULE)); - EnumProcessModules(process, &module_handles[0], - module_handles.size() * sizeof(HMODULE), &cbNeeded); - std::transform(module_handles.begin(), module_handles.end(), - std::back_inserter(modules), get_mod_info(process)); - void *base = modules[0].base_address; - IMAGE_NT_HEADERS *h = ImageNtHeader(base); - image_type = h->FileHeader.Machine; - } - - template void load_stacktrace(ST &) {} - - static const int max_sym_len = 255; - struct symbol_t { - SYMBOL_INFO sym; - char buffer[max_sym_len]; - } sym; - - DWORD64 displacement; - - ResolvedTrace resolve(ResolvedTrace t) { - HANDLE process = GetCurrentProcess(); - - char name[256]; - - memset(&sym, 0, sizeof sym); - sym.sym.SizeOfStruct = sizeof(SYMBOL_INFO); - sym.sym.MaxNameLen = max_sym_len; - - if (!SymFromAddr(process, (ULONG64)t.addr, &displacement, &sym.sym)) { - // TODO: error handling everywhere - LPTSTR lpMsgBuf; - DWORD dw = GetLastError(); - - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR)&lpMsgBuf, 0, NULL); - - printf(lpMsgBuf); - - // abort(); - } - UnDecorateSymbolName(sym.sym.Name, (PSTR)name, 256, UNDNAME_COMPLETE); - - DWORD offset = 0; - IMAGEHLP_LINE line; - if (SymGetLineFromAddr(process, (ULONG64)t.addr, &offset, &line)) { - t.object_filename = line.FileName; - t.source.filename = line.FileName; - t.source.line = line.LineNumber; - t.source.col = offset; - } - - t.source.function = name; - t.object_filename = ""; - t.object_function = name; - - return t; - } - - DWORD machine_type() const { return image_type; } - -private: - DWORD image_type; -}; - -#endif - -class TraceResolver : public TraceResolverImpl {}; - -/*************** CODE SNIPPET ***************/ - -class SourceFile { -public: - typedef std::vector> lines_t; - - SourceFile() {} - SourceFile(const std::string &path) { - // 1. If BACKWARD_CXX_SOURCE_PREFIXES is set then assume it contains - // a colon-separated list of path prefixes. Try prepending each - // to the given path until a valid file is found. - const std::vector &prefixes = get_paths_from_env_variable(); - for (size_t i = 0; i < prefixes.size(); ++i) { - // Double slashes (//) should not be a problem. - std::string new_path = prefixes[i] + '/' + path; - _file.reset(new std::ifstream(new_path.c_str())); - if (is_open()) - break; - } - // 2. If no valid file found then fallback to opening the path as-is. - if (!_file || !is_open()) { - _file.reset(new std::ifstream(path.c_str())); - } - } - bool is_open() const { return _file->is_open(); } - - lines_t &get_lines(unsigned line_start, unsigned line_count, lines_t &lines) { - using namespace std; - // This function make uses of the dumbest algo ever: - // 1) seek(0) - // 2) read lines one by one and discard until line_start - // 3) read line one by one until line_start + line_count - // - // If you are getting snippets many time from the same file, it is - // somewhat a waste of CPU, feel free to benchmark and propose a - // better solution ;) - - _file->clear(); - _file->seekg(0); - string line; - unsigned line_idx; - - for (line_idx = 1; line_idx < line_start; ++line_idx) { - std::getline(*_file, line); - if (!*_file) { - return lines; - } - } - - // think of it like a lambda in C++98 ;) - // but look, I will reuse it two times! - // What a good boy am I. - struct isspace { - bool operator()(char c) { return std::isspace(c); } - }; - - bool started = false; - for (; line_idx < line_start + line_count; ++line_idx) { - getline(*_file, line); - if (!*_file) { - return lines; - } - if (!started) { - if (std::find_if(line.begin(), line.end(), not_isspace()) == line.end()) - continue; - started = true; - } - lines.push_back(make_pair(line_idx, line)); - } - - lines.erase( - std::find_if(lines.rbegin(), lines.rend(), not_isempty()).base(), - lines.end()); - return lines; - } - - lines_t get_lines(unsigned line_start, unsigned line_count) { - lines_t lines; - return get_lines(line_start, line_count, lines); - } - - // there is no find_if_not in C++98, lets do something crappy to - // workaround. - struct not_isspace { - bool operator()(char c) { return !std::isspace(c); } - }; - // and define this one here because C++98 is not happy with local defined - // struct passed to template functions, fuuuu. - struct not_isempty { - bool operator()(const lines_t::value_type &p) { - return !(std::find_if(p.second.begin(), p.second.end(), not_isspace()) == - p.second.end()); - } - }; - - void swap(SourceFile &b) { _file.swap(b._file); } - -#ifdef BACKWARD_ATLEAST_CXX11 - SourceFile(SourceFile &&from) : _file(nullptr) { swap(from); } - SourceFile &operator=(SourceFile &&from) { - swap(from); - return *this; - } -#else - explicit SourceFile(const SourceFile &from) { - // some sort of poor man's move semantic. - swap(const_cast(from)); - } - SourceFile &operator=(const SourceFile &from) { - // some sort of poor man's move semantic. - swap(const_cast(from)); - return *this; - } -#endif - -private: - details::handle> - _file; - - std::vector get_paths_from_env_variable_impl() { - std::vector paths; - const char *prefixes_str = std::getenv("BACKWARD_CXX_SOURCE_PREFIXES"); - if (prefixes_str && prefixes_str[0]) { - paths = details::split_source_prefixes(prefixes_str); - } - return paths; - } - - const std::vector &get_paths_from_env_variable() { - static std::vector paths = get_paths_from_env_variable_impl(); - return paths; - } - -#ifdef BACKWARD_ATLEAST_CXX11 - SourceFile(const SourceFile &) = delete; - SourceFile &operator=(const SourceFile &) = delete; -#endif -}; - -class SnippetFactory { -public: - typedef SourceFile::lines_t lines_t; - - lines_t get_snippet(const std::string &filename, unsigned line_start, - unsigned context_size) { - - SourceFile &src_file = get_src_file(filename); - unsigned start = line_start - context_size / 2; - return src_file.get_lines(start, context_size); - } - - lines_t get_combined_snippet(const std::string &filename_a, unsigned line_a, - const std::string &filename_b, unsigned line_b, - unsigned context_size) { - SourceFile &src_file_a = get_src_file(filename_a); - SourceFile &src_file_b = get_src_file(filename_b); - - lines_t lines = - src_file_a.get_lines(line_a - context_size / 4, context_size / 2); - src_file_b.get_lines(line_b - context_size / 4, context_size / 2, lines); - return lines; - } - - lines_t get_coalesced_snippet(const std::string &filename, unsigned line_a, - unsigned line_b, unsigned context_size) { - SourceFile &src_file = get_src_file(filename); - - using std::max; - using std::min; - unsigned a = min(line_a, line_b); - unsigned b = max(line_a, line_b); - - if ((b - a) < (context_size / 3)) { - return src_file.get_lines((a + b - context_size + 1) / 2, context_size); - } - - lines_t lines = src_file.get_lines(a - context_size / 4, context_size / 2); - src_file.get_lines(b - context_size / 4, context_size / 2, lines); - return lines; - } - -private: - typedef details::hashtable::type src_files_t; - src_files_t _src_files; - - SourceFile &get_src_file(const std::string &filename) { - src_files_t::iterator it = _src_files.find(filename); - if (it != _src_files.end()) { - return it->second; - } - SourceFile &new_src_file = _src_files[filename]; - new_src_file = SourceFile(filename); - return new_src_file; - } -}; - -/*************** PRINTER ***************/ - -namespace ColorMode { -enum type { automatic, never, always }; -} - -class cfile_streambuf : public std::streambuf { -public: - cfile_streambuf(FILE *_sink) : sink(_sink) {} - int_type underflow() override { return traits_type::eof(); } - int_type overflow(int_type ch) override { - if (traits_type::not_eof(ch) && fwrite(&ch, sizeof ch, 1, sink) == 1) { - return ch; - } - return traits_type::eof(); - } - - std::streamsize xsputn(const char_type *s, std::streamsize count) override { - return static_cast( - fwrite(s, sizeof *s, static_cast(count), sink)); - } - -#ifdef BACKWARD_ATLEAST_CXX11 -public: - cfile_streambuf(const cfile_streambuf &) = delete; - cfile_streambuf &operator=(const cfile_streambuf &) = delete; -#else -private: - cfile_streambuf(const cfile_streambuf &); - cfile_streambuf &operator=(const cfile_streambuf &); -#endif - -private: - FILE *sink; - std::vector buffer; -}; - -#ifdef BACKWARD_SYSTEM_LINUX - -namespace Color { -enum type { yellow = 33, purple = 35, reset = 39 }; -} // namespace Color - -class Colorize { -public: - Colorize(std::ostream &os) : _os(os), _reset(false), _enabled(false) {} - - void activate(ColorMode::type mode) { _enabled = mode == ColorMode::always; } - - void activate(ColorMode::type mode, FILE *fp) { activate(mode, fileno(fp)); } - - void set_color(Color::type ccode) { - if (!_enabled) - return; - - // I assume that the terminal can handle basic colors. Seriously I - // don't want to deal with all the termcap shit. - _os << "\033[" << static_cast(ccode) << "m"; - _reset = (ccode != Color::reset); - } - - ~Colorize() { - if (_reset) { - set_color(Color::reset); - } - } - -private: - void activate(ColorMode::type mode, int fd) { - activate(mode == ColorMode::automatic && isatty(fd) ? ColorMode::always - : mode); - } - - std::ostream &_os; - bool _reset; - bool _enabled; -}; - -#else // ndef BACKWARD_SYSTEM_LINUX - -namespace Color { -enum type { yellow = 0, purple = 0, reset = 0 }; -} // namespace Color - -class Colorize { -public: - Colorize(std::ostream &) {} - void activate(ColorMode::type) {} - void activate(ColorMode::type, FILE *) {} - void set_color(Color::type) {} -}; - -#endif // BACKWARD_SYSTEM_LINUX - -class Printer { -public: - bool snippet; - ColorMode::type color_mode; - bool address; - bool object; - int inliner_context_size; - int trace_context_size; - - Printer() - : snippet(true), color_mode(ColorMode::automatic), address(false), - object(false), inliner_context_size(5), trace_context_size(7) {} - - template FILE *print(ST &st, FILE *fp = stderr) { - cfile_streambuf obuf(fp); - std::ostream os(&obuf); - Colorize colorize(os); - colorize.activate(color_mode, fp); - print_stacktrace(st, os, colorize); - return fp; - } - - template std::ostream &print(ST &st, std::ostream &os) { - Colorize colorize(os); - colorize.activate(color_mode); - print_stacktrace(st, os, colorize); - return os; - } - - template - FILE *print(IT begin, IT end, FILE *fp = stderr, size_t thread_id = 0) { - cfile_streambuf obuf(fp); - std::ostream os(&obuf); - Colorize colorize(os); - colorize.activate(color_mode, fp); - print_stacktrace(begin, end, os, thread_id, colorize); - return fp; - } - - template - std::ostream &print(IT begin, IT end, std::ostream &os, - size_t thread_id = 0) { - Colorize colorize(os); - colorize.activate(color_mode); - print_stacktrace(begin, end, os, thread_id, colorize); - return os; - } - - TraceResolver const &resolver() const { return _resolver; } - -private: - TraceResolver _resolver; - SnippetFactory _snippets; - - template - void print_stacktrace(ST &st, std::ostream &os, Colorize &colorize) { - print_header(os, st.thread_id()); - _resolver.load_stacktrace(st); - for (size_t trace_idx = st.size(); trace_idx > 0; --trace_idx) { - print_trace(os, _resolver.resolve(st[trace_idx - 1]), colorize); - } - } - - template - void print_stacktrace(IT begin, IT end, std::ostream &os, size_t thread_id, - Colorize &colorize) { - print_header(os, thread_id); - for (; begin != end; ++begin) { - print_trace(os, *begin, colorize); - } - } - - void print_header(std::ostream &os, size_t thread_id) { - os << "Stack trace (most recent call last)"; - if (thread_id) { - os << " in thread " << thread_id; - } - os << ":\n"; - } - - void print_trace(std::ostream &os, const ResolvedTrace &trace, - Colorize &colorize) { - os << "#" << std::left << std::setw(2) << trace.idx << std::right; - bool already_indented = true; - - if (!trace.source.filename.size() || object) { - os << " Object \"" << trace.object_filename << "\", at " << trace.addr - << ", in " << trace.object_function << "\n"; - already_indented = false; - } - - for (size_t inliner_idx = trace.inliners.size(); inliner_idx > 0; - --inliner_idx) { - if (!already_indented) { - os << " "; - } - const ResolvedTrace::SourceLoc &inliner_loc = - trace.inliners[inliner_idx - 1]; - print_source_loc(os, " | ", inliner_loc); - if (snippet) { - print_snippet(os, " | ", inliner_loc, colorize, Color::purple, - inliner_context_size); - } - already_indented = false; - } - - if (trace.source.filename.size()) { - if (!already_indented) { - os << " "; - } - print_source_loc(os, " ", trace.source, trace.addr); - if (snippet) { - print_snippet(os, " ", trace.source, colorize, Color::yellow, - trace_context_size); - } - } - } - - void print_snippet(std::ostream &os, const char *indent, - const ResolvedTrace::SourceLoc &source_loc, - Colorize &colorize, Color::type color_code, - int context_size) { - using namespace std; - typedef SnippetFactory::lines_t lines_t; - - lines_t lines = _snippets.get_snippet(source_loc.filename, source_loc.line, - static_cast(context_size)); - - for (lines_t::const_iterator it = lines.begin(); it != lines.end(); ++it) { - if (it->first == source_loc.line) { - colorize.set_color(color_code); - os << indent << ">"; - } else { - os << indent << " "; - } - os << std::setw(4) << it->first << ": " << it->second << "\n"; - if (it->first == source_loc.line) { - colorize.set_color(Color::reset); - } - } - } - - void print_source_loc(std::ostream &os, const char *indent, - const ResolvedTrace::SourceLoc &source_loc, - void *addr = nullptr) { - os << indent << "Source \"" << source_loc.filename << "\", line " - << source_loc.line << ", in " << source_loc.function; - - if (address && addr != nullptr) { - os << " [" << addr << "]"; - } - os << "\n"; - } -}; - -/*************** SIGNALS HANDLING ***************/ - -#if defined(BACKWARD_SYSTEM_LINUX) || defined(BACKWARD_SYSTEM_DARWIN) - -class SignalHandling { -public: - static std::vector make_default_signals() { - const int posix_signals[] = { - // Signals for which the default action is "Core". - SIGABRT, // Abort signal from abort(3) - SIGBUS, // Bus error (bad memory access) - SIGFPE, // Floating point exception - SIGILL, // Illegal Instruction - SIGIOT, // IOT trap. A synonym for SIGABRT - SIGQUIT, // Quit from keyboard - SIGSEGV, // Invalid memory reference - SIGSYS, // Bad argument to routine (SVr4) - SIGTRAP, // Trace/breakpoint trap - SIGXCPU, // CPU time limit exceeded (4.2BSD) - SIGXFSZ, // File size limit exceeded (4.2BSD) -#if defined(BACKWARD_SYSTEM_DARWIN) - SIGEMT, // emulation instruction executed -#endif - }; - return std::vector(posix_signals, - posix_signals + - sizeof posix_signals / sizeof posix_signals[0]); - } - - SignalHandling(const std::vector &posix_signals = make_default_signals()) - : _loaded(false) { - bool success = true; - - const size_t stack_size = 1024 * 1024 * 8; - _stack_content.reset(static_cast(malloc(stack_size))); - if (_stack_content) { - stack_t ss; - ss.ss_sp = _stack_content.get(); - ss.ss_size = stack_size; - ss.ss_flags = 0; - if (sigaltstack(&ss, nullptr) < 0) { - success = false; - } - } else { - success = false; - } - - for (size_t i = 0; i < posix_signals.size(); ++i) { - struct sigaction action; - memset(&action, 0, sizeof action); - action.sa_flags = - static_cast(SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND); - sigfillset(&action.sa_mask); - sigdelset(&action.sa_mask, posix_signals[i]); -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdisabled-macro-expansion" -#endif - action.sa_sigaction = &sig_handler; -#if defined(__clang__) -#pragma clang diagnostic pop -#endif - - int r = sigaction(posix_signals[i], &action, nullptr); - if (r < 0) - success = false; - } - - _loaded = success; - } - - bool loaded() const { return _loaded; } - - static void handleSignal(int, siginfo_t *info, void *_ctx) { - ucontext_t *uctx = static_cast(_ctx); - - StackTrace st; - void *error_addr = nullptr; -#ifdef REG_RIP // x86_64 - error_addr = reinterpret_cast(uctx->uc_mcontext.gregs[REG_RIP]); -#elif defined(REG_EIP) // x86_32 - error_addr = reinterpret_cast(uctx->uc_mcontext.gregs[REG_EIP]); -#elif defined(__arm__) - error_addr = reinterpret_cast(uctx->uc_mcontext.arm_pc); -#elif defined(__aarch64__) - error_addr = reinterpret_cast(uctx->uc_mcontext.pc); -#elif defined(__mips__) - error_addr = reinterpret_cast( - reinterpret_cast(&uctx->uc_mcontext)->sc_pc); -#elif defined(__ppc__) || defined(__powerpc) || defined(__powerpc__) || \ - defined(__POWERPC__) - error_addr = reinterpret_cast(uctx->uc_mcontext.regs->nip); -#elif defined(__s390x__) - error_addr = reinterpret_cast(uctx->uc_mcontext.psw.addr); -#elif defined(__APPLE__) && defined(__x86_64__) - error_addr = reinterpret_cast(uctx->uc_mcontext->__ss.__rip); -#elif defined(__APPLE__) - error_addr = reinterpret_cast(uctx->uc_mcontext->__ss.__eip); -#else -#warning ":/ sorry, ain't know no nothing none not of your architecture!" -#endif - if (error_addr) { - st.load_from(error_addr, 32); - } else { - st.load_here(32); - } - - Printer printer; - printer.address = true; - printer.print(st, stderr); - -#if _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L - psiginfo(info, nullptr); -#else - (void)info; -#endif - } - -private: - details::handle _stack_content; - bool _loaded; - -#ifdef __GNUC__ - __attribute__((noreturn)) -#endif - static void - sig_handler(int signo, siginfo_t *info, void *_ctx) { - handleSignal(signo, info, _ctx); - - // try to forward the signal. - raise(info->si_signo); - - // terminate the process immediately. - puts("watf? exit"); - _exit(EXIT_FAILURE); - } -}; - -#endif // BACKWARD_SYSTEM_LINUX || BACKWARD_SYSTEM_DARWIN - -#ifdef BACKWARD_SYSTEM_WINDOWS - -class SignalHandling { -public: - SignalHandling(const std::vector & = std::vector()) - : reporter_thread_([]() { - /* We handle crashes in a utility thread: - backward structures and some Windows functions called here - need stack space, which we do not have when we encounter a - stack overflow. - To support reporting stack traces during a stack overflow, - we create a utility thread at startup, which waits until a - crash happens or the program exits normally. */ - - { - std::unique_lock lk(mtx()); - cv().wait(lk, [] { return crashed() != crash_status::running; }); - } - if (crashed() == crash_status::crashed) { - handle_stacktrace(skip_recs()); - } - { - std::unique_lock lk(mtx()); - crashed() = crash_status::ending; - } - cv().notify_one(); - }) { - SetUnhandledExceptionFilter(crash_handler); - - signal(SIGABRT, signal_handler); - _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); - - set_terminate(&terminator); - set_unexpected(&terminator); - _set_purecall_handler(&terminator); - _set_invalid_parameter_handler(&invalid_parameter_handler); - } - bool loaded() const { return true; } - - ~SignalHandling() { - { - std::unique_lock lk(mtx()); - crashed() = crash_status::normal_exit; - } - - cv().notify_one(); - - reporter_thread_.join(); - } - -private: - static CONTEXT *ctx() { - static CONTEXT data; - return &data; - } - - enum class crash_status { running, crashed, normal_exit, ending }; - - static crash_status &crashed() { - static crash_status data; - return data; - } - - static std::mutex &mtx() { - static std::mutex data; - return data; - } - - static std::condition_variable &cv() { - static std::condition_variable data; - return data; - } - - static HANDLE &thread_handle() { - static HANDLE handle; - return handle; - } - - std::thread reporter_thread_; - - // TODO: how not to hardcode these? - static const constexpr int signal_skip_recs = -#ifdef __clang__ - // With clang, RtlCaptureContext also captures the stack frame of the - // current function Below that, there ar 3 internal Windows functions - 4 -#else - // With MSVC cl, RtlCaptureContext misses the stack frame of the current - // function The first entries during StackWalk are the 3 internal Windows - // functions - 3 -#endif - ; - - static int &skip_recs() { - static int data; - return data; - } - - static inline void terminator() { - crash_handler(signal_skip_recs); - abort(); - } - - static inline void signal_handler(int) { - crash_handler(signal_skip_recs); - abort(); - } - - static inline void __cdecl invalid_parameter_handler(const wchar_t *, - const wchar_t *, - const wchar_t *, - unsigned int, - uintptr_t) { - crash_handler(signal_skip_recs); - abort(); - } - - NOINLINE static LONG WINAPI crash_handler(EXCEPTION_POINTERS *info) { - // The exception info supplies a trace from exactly where the issue was, - // no need to skip records - crash_handler(0, info->ContextRecord); - return EXCEPTION_CONTINUE_SEARCH; - } - - NOINLINE static void crash_handler(int skip, CONTEXT *ct = nullptr) { - - if (ct == nullptr) { - RtlCaptureContext(ctx()); - } else { - memcpy(ctx(), ct, sizeof(CONTEXT)); - } - DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), - GetCurrentProcess(), &thread_handle(), 0, FALSE, - DUPLICATE_SAME_ACCESS); - - skip_recs() = skip; - - { - std::unique_lock lk(mtx()); - crashed() = crash_status::crashed; - } - - cv().notify_one(); - - { - std::unique_lock lk(mtx()); - cv().wait(lk, [] { return crashed() != crash_status::crashed; }); - } - } - - static void handle_stacktrace(int skip_frames = 0) { - // printer creates the TraceResolver, which can supply us a machine type - // for stack walking. Without this, StackTrace can only guess using some - // macros. - // StackTrace also requires that the PDBs are already loaded, which is done - // in the constructor of TraceResolver - Printer printer; - - StackTrace st; - st.set_machine_type(printer.resolver().machine_type()); - st.set_context(ctx()); - st.set_thread_handle(thread_handle()); - st.load_here(32 + skip_frames); - st.skip_n_firsts(skip_frames); - - printer.address = true; - printer.print(st, std::cerr); - } -}; - -#endif // BACKWARD_SYSTEM_WINDOWS - -#ifdef BACKWARD_SYSTEM_UNKNOWN - -class SignalHandling { -public: - SignalHandling(const std::vector & = std::vector()) {} - bool init() { return false; } - bool loaded() { return false; } -}; - -#endif // BACKWARD_SYSTEM_UNKNOWN - -} // namespace backward - -#endif /* H_GUARD */ diff --git a/ariles/cpput/include/cpput/better_enum.h b/ariles/cpput/include/cpput/better_enum.h deleted file mode 100644 index 17433886..00000000 --- a/ariles/cpput/include/cpput/better_enum.h +++ /dev/null @@ -1,1325 +0,0 @@ -// This file is part of Better Enums, released under the BSD 2-clause license. -// See LICENSE.md for details, or visit http://github.com/aantron/better-enums. - -#pragma once - -#ifndef BETTER_ENUMS_ENUM_H -#define BETTER_ENUMS_ENUM_H - - - -#include -#include -#include -#include - - -// in-line, non-#pragma warning handling -// not supported in very old compilers (namely gcc 4.4 or less) -#ifdef __GNUC__ -# ifdef __clang__ -# define BETTER_ENUMS_IGNORE_OLD_CAST_HEADER _Pragma("clang diagnostic push") -# define BETTER_ENUMS_IGNORE_OLD_CAST_BEGIN _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") -# define BETTER_ENUMS_IGNORE_OLD_CAST_END _Pragma("clang diagnostic pop") -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_HEADER -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_BEGIN -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_END -# else -# define BETTER_ENUMS_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) -# if BETTER_ENUMS_GCC_VERSION > 40400 -# define BETTER_ENUMS_IGNORE_OLD_CAST_HEADER _Pragma("GCC diagnostic push") -# define BETTER_ENUMS_IGNORE_OLD_CAST_BEGIN _Pragma("GCC diagnostic ignored \"-Wold-style-cast\"") -# define BETTER_ENUMS_IGNORE_OLD_CAST_END _Pragma("GCC diagnostic pop") -# if (BETTER_ENUMS_GCC_VERSION >= 70300) -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_HEADER _Pragma("GCC diagnostic push") -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_BEGIN _Pragma("GCC diagnostic ignored \"-Wattributes\"") -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_END _Pragma("GCC diagnostic pop") -# else -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_HEADER -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_BEGIN -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_END -# endif -# else -# define BETTER_ENUMS_IGNORE_OLD_CAST_HEADER -# define BETTER_ENUMS_IGNORE_OLD_CAST_BEGIN -# define BETTER_ENUMS_IGNORE_OLD_CAST_END -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_HEADER -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_BEGIN -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_END -# endif -# endif -#else // empty definitions for compilers that don't support _Pragma -# define BETTER_ENUMS_IGNORE_OLD_CAST_HEADER -# define BETTER_ENUMS_IGNORE_OLD_CAST_BEGIN -# define BETTER_ENUMS_IGNORE_OLD_CAST_END -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_HEADER -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_BEGIN -# define BETTER_ENUMS_IGNORE_ATTRIBUTES_END -#endif - -// Feature detection. - -#ifdef __GNUC__ -# ifdef __clang__ -# if __has_feature(cxx_constexpr) -# define BETTER_ENUMS_HAVE_CONSTEXPR -# endif -# if !defined(__EXCEPTIONS) || !__has_feature(cxx_exceptions) -# define BETTER_ENUMS_NO_EXCEPTIONS -# endif -# else -# if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L -# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) -# define BETTER_ENUMS_HAVE_CONSTEXPR -# endif -# endif -# ifndef __EXCEPTIONS -# define BETTER_ENUMS_NO_EXCEPTIONS -# endif -# endif -#endif - -#ifdef _MSC_VER -# if _MSC_VER >= 1911 -# define BETTER_ENUMS_HAVE_CONSTEXPR -# endif -# ifdef __clang__ -# if __has_feature(cxx_constexpr) -# define BETTER_ENUMS_HAVE_CONSTEXPR -# endif -# endif -# ifndef _CPPUNWIND -# define BETTER_ENUMS_NO_EXCEPTIONS -# endif -# if _MSC_VER < 1600 -# define BETTER_ENUMS_VC2008_WORKAROUNDS -# endif -#endif - -#ifdef BETTER_ENUMS_CONSTEXPR -# define BETTER_ENUMS_HAVE_CONSTEXPR -#endif - -#ifdef BETTER_ENUMS_NO_CONSTEXPR -# ifdef BETTER_ENUMS_HAVE_CONSTEXPR -# undef BETTER_ENUMS_HAVE_CONSTEXPR -# endif -#endif - -// GCC (and maybe clang) can be made to warn about using 0 or NULL when nullptr -// is available, so Better Enums tries to use nullptr. This passage uses -// availability of constexpr as a proxy for availability of nullptr, i.e. it -// assumes that nullptr is available when compiling on the right versions of gcc -// and clang with the right -std flag. This is actually slightly wrong, because -// nullptr is also available in Visual C++, but constexpr isn't. This -// imprecision doesn't matter, however, because VC++ doesn't have the warnings -// that make using nullptr necessary. -#ifdef BETTER_ENUMS_HAVE_CONSTEXPR -# define BETTER_ENUMS_CONSTEXPR_ constexpr -# define BETTER_ENUMS_NULLPTR nullptr -#else -# define BETTER_ENUMS_CONSTEXPR_ -# define BETTER_ENUMS_NULLPTR NULL -#endif - -#ifndef BETTER_ENUMS_NO_EXCEPTIONS -# define BETTER_ENUMS_IF_EXCEPTIONS(x) x -#else -# define BETTER_ENUMS_IF_EXCEPTIONS(x) -#endif - -#ifdef __GNUC__ -# define BETTER_ENUMS_UNUSED __attribute__((__unused__)) -#else -# define BETTER_ENUMS_UNUSED -#endif - - - -// Higher-order preprocessor macros. - -#ifdef BETTER_ENUMS_MACRO_FILE -# include BETTER_ENUMS_MACRO_FILE -#else - -#define BETTER_ENUMS_PP_MAP(macro, data, ...) \ - BETTER_ENUMS_ID( \ - BETTER_ENUMS_APPLY( \ - BETTER_ENUMS_PP_MAP_VAR_COUNT, \ - BETTER_ENUMS_PP_COUNT(__VA_ARGS__)) \ - (macro, data, __VA_ARGS__)) - -#define BETTER_ENUMS_PP_MAP_VAR_COUNT(count) BETTER_ENUMS_M ## count - -#define BETTER_ENUMS_APPLY(macro, ...) BETTER_ENUMS_ID(macro(__VA_ARGS__)) - -#define BETTER_ENUMS_ID(x) x - -#define BETTER_ENUMS_M1(m, d, x) m(d,0,x) -#define BETTER_ENUMS_M2(m,d,x,...) m(d,1,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M1(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M3(m,d,x,...) m(d,2,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M2(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M4(m,d,x,...) m(d,3,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M3(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M5(m,d,x,...) m(d,4,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M4(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M6(m,d,x,...) m(d,5,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M5(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M7(m,d,x,...) m(d,6,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M6(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M8(m,d,x,...) m(d,7,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M7(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M9(m,d,x,...) m(d,8,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M8(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M10(m,d,x,...) m(d,9,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M9(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M11(m,d,x,...) m(d,10,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M10(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M12(m,d,x,...) m(d,11,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M11(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M13(m,d,x,...) m(d,12,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M12(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M14(m,d,x,...) m(d,13,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M13(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M15(m,d,x,...) m(d,14,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M14(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M16(m,d,x,...) m(d,15,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M15(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M17(m,d,x,...) m(d,16,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M16(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M18(m,d,x,...) m(d,17,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M17(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M19(m,d,x,...) m(d,18,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M18(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M20(m,d,x,...) m(d,19,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M19(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M21(m,d,x,...) m(d,20,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M20(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M22(m,d,x,...) m(d,21,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M21(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M23(m,d,x,...) m(d,22,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M22(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M24(m,d,x,...) m(d,23,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M23(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M25(m,d,x,...) m(d,24,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M24(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M26(m,d,x,...) m(d,25,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M25(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M27(m,d,x,...) m(d,26,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M26(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M28(m,d,x,...) m(d,27,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M27(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M29(m,d,x,...) m(d,28,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M28(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M30(m,d,x,...) m(d,29,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M29(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M31(m,d,x,...) m(d,30,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M30(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M32(m,d,x,...) m(d,31,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M31(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M33(m,d,x,...) m(d,32,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M32(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M34(m,d,x,...) m(d,33,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M33(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M35(m,d,x,...) m(d,34,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M34(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M36(m,d,x,...) m(d,35,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M35(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M37(m,d,x,...) m(d,36,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M36(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M38(m,d,x,...) m(d,37,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M37(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M39(m,d,x,...) m(d,38,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M38(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M40(m,d,x,...) m(d,39,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M39(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M41(m,d,x,...) m(d,40,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M40(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M42(m,d,x,...) m(d,41,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M41(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M43(m,d,x,...) m(d,42,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M42(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M44(m,d,x,...) m(d,43,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M43(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M45(m,d,x,...) m(d,44,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M44(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M46(m,d,x,...) m(d,45,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M45(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M47(m,d,x,...) m(d,46,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M46(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M48(m,d,x,...) m(d,47,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M47(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M49(m,d,x,...) m(d,48,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M48(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M50(m,d,x,...) m(d,49,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M49(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M51(m,d,x,...) m(d,50,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M50(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M52(m,d,x,...) m(d,51,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M51(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M53(m,d,x,...) m(d,52,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M52(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M54(m,d,x,...) m(d,53,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M53(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M55(m,d,x,...) m(d,54,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M54(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M56(m,d,x,...) m(d,55,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M55(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M57(m,d,x,...) m(d,56,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M56(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M58(m,d,x,...) m(d,57,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M57(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M59(m,d,x,...) m(d,58,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M58(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M60(m,d,x,...) m(d,59,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M59(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M61(m,d,x,...) m(d,60,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M60(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M62(m,d,x,...) m(d,61,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M61(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M63(m,d,x,...) m(d,62,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M62(m,d,__VA_ARGS__)) -#define BETTER_ENUMS_M64(m,d,x,...) m(d,63,x) \ - BETTER_ENUMS_ID(BETTER_ENUMS_M63(m,d,__VA_ARGS__)) - -#define BETTER_ENUMS_PP_COUNT_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, \ - _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, \ - _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, \ - _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, \ - _56, _57, _58, _59, _60, _61, _62, _63, _64, count, ...) count - -#define BETTER_ENUMS_PP_COUNT(...) \ - BETTER_ENUMS_ID(BETTER_ENUMS_PP_COUNT_IMPL(__VA_ARGS__, 64, 63, 62, 61, 60,\ - 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42,\ - 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24,\ - 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, \ - 4, 3, 2, 1)) - -#define BETTER_ENUMS_ITERATE(X, f, l) X(f, l, 0) X(f, l, 1) X(f, l, 2) \ - X(f, l, 3) X(f, l, 4) X(f, l, 5) X(f, l, 6) X(f, l, 7) X(f, l, 8) \ - X(f, l, 9) X(f, l, 10) X(f, l, 11) X(f, l, 12) X(f, l, 13) X(f, l, 14) \ - X(f, l, 15) X(f, l, 16) X(f, l, 17) X(f, l, 18) X(f, l, 19) X(f, l, 20) \ - X(f, l, 21) X(f, l, 22) X(f, l, 23) - -#endif // #ifdef BETTER_ENUMS_MACRO_FILE else case - - - -namespace better_enums { - - -// Optional type. - -template -BETTER_ENUMS_CONSTEXPR_ inline T _default() -{ - return static_cast(0); -} - -template <> -BETTER_ENUMS_CONSTEXPR_ inline const char* _default() -{ - return BETTER_ENUMS_NULLPTR; -} - -template <> -BETTER_ENUMS_CONSTEXPR_ inline std::size_t _default() -{ - return 0; -} - -template -struct optional { - BETTER_ENUMS_CONSTEXPR_ optional() : - _valid(false), _value(_default()) { } - - BETTER_ENUMS_CONSTEXPR_ optional(T v) : _valid(true), _value(v) { } - - BETTER_ENUMS_CONSTEXPR_ const T& operator *() const { return _value; } - BETTER_ENUMS_CONSTEXPR_ const T* operator ->() const { return &_value; } - - BETTER_ENUMS_CONSTEXPR_ operator bool() const { return _valid; } - - BETTER_ENUMS_CONSTEXPR_ const T& value() const { return _value; } - - private: - bool _valid; - T _value; -}; - -template -BETTER_ENUMS_CONSTEXPR_ static optional -_map_index(const Element *array, optional index) -{ - return index ? static_cast(array[*index]) : optional(); -} - -#ifdef BETTER_ENUMS_VC2008_WORKAROUNDS - -#define BETTER_ENUMS_OR_THROW \ - if (!maybe) \ - throw std::runtime_error(message); \ - \ - return *maybe; - -#else - -#define BETTER_ENUMS_OR_THROW \ - return maybe ? *maybe : throw std::runtime_error(message); - -#endif - -BETTER_ENUMS_IF_EXCEPTIONS( -template -BETTER_ENUMS_CONSTEXPR_ static T _or_throw(optional maybe, - const char *message) -{ - BETTER_ENUMS_OR_THROW -} -) - -template -BETTER_ENUMS_CONSTEXPR_ static T* _or_null(optional maybe) -{ - return maybe ? *maybe : BETTER_ENUMS_NULLPTR; -} - -template -BETTER_ENUMS_CONSTEXPR_ static T _or_zero(optional maybe) -{ - return maybe ? *maybe : T::_from_integral_unchecked(0); -} - - - -// Functional sequencing. This is essentially a comma operator wrapped in a -// constexpr function. g++ 4.7 doesn't "accept" integral constants in the second -// position for the comma operator, and emits an external symbol, which then -// causes a linking error. - -template -BETTER_ENUMS_CONSTEXPR_ U -continue_with(T, U value) { return value; } - - - -// Values array declaration helper. - -//! Get intrinsic value of an (Enum::value) by taking advantage of C-conversion's parentheses priority -template -struct _eat_assign { - explicit BETTER_ENUMS_CONSTEXPR_ _eat_assign(EnumType value) : _value(value) - { } - - template - BETTER_ENUMS_CONSTEXPR_ const _eat_assign& - operator =(Any) const { return *this; } - - BETTER_ENUMS_CONSTEXPR_ operator EnumType () const { return _value; } - - private: - EnumType _value; -}; - - - -// Iterables. - -template -struct _iterable { - typedef const Element* iterator; - - BETTER_ENUMS_CONSTEXPR_ iterator begin() const { return iterator(_array); } - BETTER_ENUMS_CONSTEXPR_ iterator end() const - { return iterator(_array + _size); } - BETTER_ENUMS_CONSTEXPR_ std::size_t size() const { return _size; } - BETTER_ENUMS_CONSTEXPR_ const Element& operator [](std::size_t index) const - { return _array[index]; } - - BETTER_ENUMS_CONSTEXPR_ _iterable(const Element *array, std::size_t s) : - _array(array), _size(s) { } - - private: - const Element * const _array; - const std::size_t _size; -}; - - - -// String routines. - -BETTER_ENUMS_CONSTEXPR_ static const char *_name_enders = "= \t\n"; - -BETTER_ENUMS_CONSTEXPR_ inline bool _ends_name(char c, std::size_t index = 0) -{ - return - c == _name_enders[index] ? true : - _name_enders[index] == '\0' ? false : - _ends_name(c, index + 1); -} - -BETTER_ENUMS_CONSTEXPR_ inline bool _has_initializer(const char *s, - std::size_t index = 0) -{ - return - s[index] == '\0' ? false : - s[index] == '=' ? true : - _has_initializer(s, index + 1); -} - -BETTER_ENUMS_CONSTEXPR_ inline std::size_t -_constant_length(const char *s, std::size_t index = 0) -{ - return _ends_name(s[index]) ? index : _constant_length(s, index + 1); -} - -BETTER_ENUMS_CONSTEXPR_ inline char -_select(const char *from, std::size_t from_length, std::size_t index) -{ - return index >= from_length ? '\0' : from[index]; -} - -BETTER_ENUMS_CONSTEXPR_ inline char _to_lower_ascii(char c) -{ - return c >= 0x41 && c <= 0x5A ? static_cast(c + 0x20) : c; -} - -BETTER_ENUMS_CONSTEXPR_ inline bool _names_match(const char *stringizedName, - const char *referenceName, - std::size_t index = 0) -{ - return - _ends_name(stringizedName[index]) ? referenceName[index] == '\0' : - referenceName[index] == '\0' ? false : - stringizedName[index] != referenceName[index] ? false : - _names_match(stringizedName, referenceName, index + 1); -} - -BETTER_ENUMS_CONSTEXPR_ inline bool -_names_match_nocase(const char *stringizedName, const char *referenceName, - std::size_t index = 0) -{ - return - _ends_name(stringizedName[index]) ? referenceName[index] == '\0' : - referenceName[index] == '\0' ? false : - _to_lower_ascii(stringizedName[index]) != - _to_lower_ascii(referenceName[index]) ? false : - _names_match_nocase(stringizedName, referenceName, index + 1); -} - -inline void _trim_names(const char * const *raw_names, - const char **trimmed_names, - char *storage, std::size_t count) -{ - std::size_t offset = 0; - - for (std::size_t index = 0; index < count; ++index) { - trimmed_names[index] = storage + offset; - - std::size_t trimmed_length = - std::strcspn(raw_names[index], _name_enders); - storage[offset + trimmed_length] = '\0'; - - std::size_t raw_length = std::strlen(raw_names[index]); - offset += raw_length + 1; - } -} - - - -// Eager initialization. -template -struct _initialize_at_program_start { - _initialize_at_program_start() { Enum::initialize(); } -}; - -} // namespace better_enums - - - -// Array generation macros. - -#define BETTER_ENUMS_EAT_ASSIGN_SINGLE(EnumType, index, expression) \ - (EnumType)((::better_enums::_eat_assign)EnumType::expression), - -#define BETTER_ENUMS_EAT_ASSIGN(EnumType, ...) \ - BETTER_ENUMS_ID( \ - BETTER_ENUMS_PP_MAP( \ - BETTER_ENUMS_EAT_ASSIGN_SINGLE, EnumType, __VA_ARGS__)) - - - -#ifdef BETTER_ENUMS_HAVE_CONSTEXPR - - - -#define BETTER_ENUMS_SELECT_SINGLE_CHARACTER(from, from_length, index) \ - ::better_enums::_select(from, from_length, index), - -#define BETTER_ENUMS_SELECT_CHARACTERS(from, from_length) \ - BETTER_ENUMS_ITERATE( \ - BETTER_ENUMS_SELECT_SINGLE_CHARACTER, from, from_length) - - - -#define BETTER_ENUMS_TRIM_SINGLE_STRING(ignored, index, expression) \ -constexpr std::size_t _length_ ## index = \ - ::better_enums::_constant_length(#expression); \ -constexpr const char _trimmed_ ## index [] = \ - { BETTER_ENUMS_SELECT_CHARACTERS(#expression, _length_ ## index) }; \ -constexpr const char *_final_ ## index = \ - ::better_enums::_has_initializer(#expression) ? \ - _trimmed_ ## index : #expression; - -#define BETTER_ENUMS_TRIM_STRINGS(...) \ - BETTER_ENUMS_ID( \ - BETTER_ENUMS_PP_MAP( \ - BETTER_ENUMS_TRIM_SINGLE_STRING, ignored, __VA_ARGS__)) - - - -#define BETTER_ENUMS_REFER_TO_SINGLE_STRING(ignored, index, expression) \ - _final_ ## index, - -#define BETTER_ENUMS_REFER_TO_STRINGS(...) \ - BETTER_ENUMS_ID( \ - BETTER_ENUMS_PP_MAP( \ - BETTER_ENUMS_REFER_TO_SINGLE_STRING, ignored, __VA_ARGS__)) - - - -#endif // #ifdef BETTER_ENUMS_HAVE_CONSTEXPR - - - -#define BETTER_ENUMS_STRINGIZE_SINGLE(ignored, index, expression) #expression, - -#define BETTER_ENUMS_STRINGIZE(...) \ - BETTER_ENUMS_ID( \ - BETTER_ENUMS_PP_MAP( \ - BETTER_ENUMS_STRINGIZE_SINGLE, ignored, __VA_ARGS__)) - -#define BETTER_ENUMS_RESERVE_STORAGE_SINGLE(ignored, index, expression) \ - #expression "," - -#define BETTER_ENUMS_RESERVE_STORAGE(...) \ - BETTER_ENUMS_ID( \ - BETTER_ENUMS_PP_MAP( \ - BETTER_ENUMS_RESERVE_STORAGE_SINGLE, ignored, __VA_ARGS__)) - - - -// The enums proper. - -#define BETTER_ENUMS_NS(EnumType) better_enums_data_ ## EnumType - -#ifdef BETTER_ENUMS_VC2008_WORKAROUNDS - -#define BETTER_ENUMS_COPY_CONSTRUCTOR(Enum) \ - BETTER_ENUMS_CONSTEXPR_ Enum(const Enum &other) : \ - _value(other._value) { } - -#else - -#define BETTER_ENUMS_COPY_CONSTRUCTOR(Enum) - -#endif - -#ifndef BETTER_ENUMS_CLASS_ATTRIBUTE -# define BETTER_ENUMS_CLASS_ATTRIBUTE -#endif - -#define BETTER_ENUMS_TYPE(SetUnderlyingType, SwitchType, GenerateSwitchType, \ - GenerateStrings, ToStringConstexpr, \ - DeclareInitialize, DefineInitialize, CallInitialize, \ - Enum, Underlying, ...) \ - \ -namespace better_enums_data_ ## Enum { \ - \ -BETTER_ENUMS_ID(GenerateSwitchType(Underlying, __VA_ARGS__)) \ - \ -} \ - \ -class BETTER_ENUMS_CLASS_ATTRIBUTE Enum { \ - private: \ - typedef ::better_enums::optional _optional; \ - typedef ::better_enums::optional _optional_index; \ - \ - public: \ - typedef Underlying _integral; \ - \ - enum _enumerated SetUnderlyingType(Underlying) { __VA_ARGS__ }; \ - \ - BETTER_ENUMS_CONSTEXPR_ Enum(_enumerated value) : _value(value) { } \ - \ - BETTER_ENUMS_COPY_CONSTRUCTOR(Enum) \ - \ - BETTER_ENUMS_CONSTEXPR_ operator SwitchType(Enum)() const \ - { \ - return SwitchType(Enum)(_value); \ - } \ - \ - BETTER_ENUMS_CONSTEXPR_ _integral _to_integral() const; \ - BETTER_ENUMS_IF_EXCEPTIONS( \ - BETTER_ENUMS_CONSTEXPR_ static Enum _from_integral(_integral value); \ - ) \ - BETTER_ENUMS_CONSTEXPR_ static Enum \ - _from_integral_unchecked(_integral value); \ - BETTER_ENUMS_CONSTEXPR_ static _optional \ - _from_integral_nothrow(_integral value); \ - \ - BETTER_ENUMS_CONSTEXPR_ std::size_t _to_index() const; \ - BETTER_ENUMS_IF_EXCEPTIONS( \ - BETTER_ENUMS_CONSTEXPR_ static Enum _from_index(std::size_t value); \ - ) \ - BETTER_ENUMS_CONSTEXPR_ static Enum \ - _from_index_unchecked(std::size_t value); \ - BETTER_ENUMS_CONSTEXPR_ static _optional \ - _from_index_nothrow(std::size_t value); \ - \ - ToStringConstexpr const char* _to_string() const; \ - BETTER_ENUMS_IF_EXCEPTIONS( \ - BETTER_ENUMS_CONSTEXPR_ static Enum _from_string(const char *name); \ - ) \ - BETTER_ENUMS_CONSTEXPR_ static _optional \ - _from_string_nothrow(const char *name); \ - \ - BETTER_ENUMS_IF_EXCEPTIONS( \ - BETTER_ENUMS_CONSTEXPR_ static Enum _from_string_nocase(const char *name); \ - ) \ - BETTER_ENUMS_CONSTEXPR_ static _optional \ - _from_string_nocase_nothrow(const char *name); \ - \ - BETTER_ENUMS_CONSTEXPR_ static bool _is_valid(_integral value); \ - BETTER_ENUMS_CONSTEXPR_ static bool _is_valid(const char *name); \ - BETTER_ENUMS_CONSTEXPR_ static bool _is_valid_nocase(const char *name); \ - \ - typedef ::better_enums::_iterable _value_iterable; \ - typedef ::better_enums::_iterable _name_iterable; \ - \ - typedef _value_iterable::iterator _value_iterator; \ - typedef _name_iterable::iterator _name_iterator; \ - \ - BETTER_ENUMS_CONSTEXPR_ static const std::size_t _size_constant = \ - BETTER_ENUMS_ID(BETTER_ENUMS_PP_COUNT(__VA_ARGS__)); \ - BETTER_ENUMS_CONSTEXPR_ static std::size_t _size() \ - { return _size_constant; } \ - \ - BETTER_ENUMS_CONSTEXPR_ static const char* _name(); \ - BETTER_ENUMS_CONSTEXPR_ static _value_iterable _values(); \ - ToStringConstexpr static _name_iterable _names(); \ - \ - _integral _value; \ - \ - BETTER_ENUMS_DEFAULT_CONSTRUCTOR(Enum) \ - \ - private: \ - explicit BETTER_ENUMS_CONSTEXPR_ Enum(const _integral &value) : \ - _value(value) { } \ - \ - DeclareInitialize \ - \ - BETTER_ENUMS_CONSTEXPR_ static _optional_index \ - _from_value_loop(_integral value, std::size_t index = 0); \ - BETTER_ENUMS_CONSTEXPR_ static _optional_index \ - _from_string_loop(const char *name, std::size_t index = 0); \ - BETTER_ENUMS_CONSTEXPR_ static _optional_index \ - _from_string_nocase_loop(const char *name, std::size_t index = 0); \ - \ - friend struct ::better_enums::_initialize_at_program_start; \ -}; \ - \ -namespace better_enums_data_ ## Enum { \ - \ -static ::better_enums::_initialize_at_program_start \ - _force_initialization; \ - \ -enum _putNamesInThisScopeAlso { __VA_ARGS__ }; \ - \ -BETTER_ENUMS_IGNORE_OLD_CAST_HEADER \ -BETTER_ENUMS_IGNORE_OLD_CAST_BEGIN \ -BETTER_ENUMS_CONSTEXPR_ const Enum _value_array[] = \ - { BETTER_ENUMS_ID(BETTER_ENUMS_EAT_ASSIGN(Enum, __VA_ARGS__)) }; \ -BETTER_ENUMS_IGNORE_OLD_CAST_END \ - \ -BETTER_ENUMS_ID(GenerateStrings(Enum, __VA_ARGS__)) \ - \ -} \ - \ -BETTER_ENUMS_IGNORE_ATTRIBUTES_HEADER \ -BETTER_ENUMS_IGNORE_ATTRIBUTES_BEGIN \ -BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_ \ -inline const Enum \ -operator +(Enum::_enumerated enumerated) \ -{ \ - return static_cast(enumerated); \ -} \ -BETTER_ENUMS_IGNORE_ATTRIBUTES_END \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum::_optional_index \ -Enum::_from_value_loop(Enum::_integral value, std::size_t index) \ -{ \ - return \ - index == _size() ? \ - _optional_index() : \ - BETTER_ENUMS_NS(Enum)::_value_array[index]._value == value ? \ - _optional_index(index) : \ - _from_value_loop(value, index + 1); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum::_optional_index \ -Enum::_from_string_loop(const char *name, std::size_t index) \ -{ \ - return \ - index == _size() ? _optional_index() : \ - ::better_enums::_names_match( \ - BETTER_ENUMS_NS(Enum)::_raw_names()[index], name) ? \ - _optional_index(index) : \ - _from_string_loop(name, index + 1); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum::_optional_index \ -Enum::_from_string_nocase_loop(const char *name, std::size_t index) \ -{ \ - return \ - index == _size() ? _optional_index() : \ - ::better_enums::_names_match_nocase( \ - BETTER_ENUMS_NS(Enum)::_raw_names()[index], name) ? \ - _optional_index(index) : \ - _from_string_nocase_loop(name, index + 1); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum::_integral Enum::_to_integral() const \ -{ \ - return _integral(_value); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline std::size_t Enum::_to_index() const \ -{ \ - return *_from_value_loop(_value); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum \ -Enum::_from_index_unchecked(std::size_t index) \ -{ \ - return \ - ::better_enums::_or_zero(_from_index_nothrow(index)); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum::_optional \ -Enum::_from_index_nothrow(std::size_t index) \ -{ \ - return \ - index >= _size() ? \ - _optional() : \ - _optional(BETTER_ENUMS_NS(Enum)::_value_array[index]); \ -} \ - \ -BETTER_ENUMS_IF_EXCEPTIONS( \ -BETTER_ENUMS_CONSTEXPR_ inline Enum Enum::_from_index(std::size_t index) \ -{ \ - return \ - ::better_enums::_or_throw(_from_index_nothrow(index), \ - #Enum "::_from_index: invalid argument"); \ -} \ -) \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum \ -Enum::_from_integral_unchecked(_integral value) \ -{ \ - return static_cast<_enumerated>(value); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum::_optional \ -Enum::_from_integral_nothrow(_integral value) \ -{ \ - return \ - ::better_enums::_map_index(BETTER_ENUMS_NS(Enum)::_value_array, \ - _from_value_loop(value)); \ -} \ - \ -BETTER_ENUMS_IF_EXCEPTIONS( \ -BETTER_ENUMS_CONSTEXPR_ inline Enum Enum::_from_integral(_integral value) \ -{ \ - return \ - ::better_enums::_or_throw(_from_integral_nothrow(value), \ - #Enum "::_from_integral: invalid argument"); \ -} \ -) \ - \ -ToStringConstexpr inline const char* Enum::_to_string() const \ -{ \ - return \ - ::better_enums::_or_null( \ - ::better_enums::_map_index( \ - BETTER_ENUMS_NS(Enum)::_name_array(), \ - _from_value_loop(CallInitialize(_value)))); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum::_optional \ -Enum::_from_string_nothrow(const char *name) \ -{ \ - return \ - ::better_enums::_map_index( \ - BETTER_ENUMS_NS(Enum)::_value_array, _from_string_loop(name)); \ -} \ - \ -BETTER_ENUMS_IF_EXCEPTIONS( \ -BETTER_ENUMS_CONSTEXPR_ inline Enum Enum::_from_string(const char *name) \ -{ \ - return \ - ::better_enums::_or_throw(_from_string_nothrow(name), \ - #Enum "::_from_string: invalid argument"); \ -} \ -) \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum::_optional \ -Enum::_from_string_nocase_nothrow(const char *name) \ -{ \ - return \ - ::better_enums::_map_index(BETTER_ENUMS_NS(Enum)::_value_array, \ - _from_string_nocase_loop(name)); \ -} \ - \ -BETTER_ENUMS_IF_EXCEPTIONS( \ -BETTER_ENUMS_CONSTEXPR_ inline Enum Enum::_from_string_nocase(const char *name)\ -{ \ - return \ - ::better_enums::_or_throw( \ - _from_string_nocase_nothrow(name), \ - #Enum "::_from_string_nocase: invalid argument"); \ -} \ -) \ - \ -BETTER_ENUMS_CONSTEXPR_ inline bool Enum::_is_valid(_integral value) \ -{ \ - return _from_value_loop(value); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline bool Enum::_is_valid(const char *name) \ -{ \ - return _from_string_loop(name); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline bool Enum::_is_valid_nocase(const char *name) \ -{ \ - return _from_string_nocase_loop(name); \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline const char* Enum::_name() \ -{ \ - return #Enum; \ -} \ - \ -BETTER_ENUMS_CONSTEXPR_ inline Enum::_value_iterable Enum::_values() \ -{ \ - return _value_iterable(BETTER_ENUMS_NS(Enum)::_value_array, _size()); \ -} \ - \ -ToStringConstexpr inline Enum::_name_iterable Enum::_names() \ -{ \ - return \ - _name_iterable(BETTER_ENUMS_NS(Enum)::_name_array(), \ - CallInitialize(_size())); \ -} \ - \ -DefineInitialize(Enum) \ - \ -BETTER_ENUMS_IGNORE_ATTRIBUTES_HEADER \ -BETTER_ENUMS_IGNORE_ATTRIBUTES_BEGIN \ -BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_ \ -inline bool operator ==(const Enum &a, const Enum &b) \ - { return a._to_integral() == b._to_integral(); } \ - \ -BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_ \ -inline bool operator !=(const Enum &a, const Enum &b) \ - { return a._to_integral() != b._to_integral(); } \ - \ -BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_ \ -inline bool operator <(const Enum &a, const Enum &b) \ - { return a._to_integral() < b._to_integral(); } \ - \ -BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_ \ -inline bool operator <=(const Enum &a, const Enum &b) \ - { return a._to_integral() <= b._to_integral(); } \ - \ -BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_ \ -inline bool operator >(const Enum &a, const Enum &b) \ - { return a._to_integral() > b._to_integral(); } \ - \ -BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_ \ -inline bool operator >=(const Enum &a, const Enum &b) \ - { return a._to_integral() >= b._to_integral(); } \ -BETTER_ENUMS_IGNORE_ATTRIBUTES_END \ - \ - \ -template \ -std::basic_ostream& \ -operator <<(std::basic_ostream& stream, const Enum &value) \ -{ \ - return stream << value._to_string(); \ -} \ - \ -template \ -std::basic_istream& \ -operator >>(std::basic_istream& stream, Enum &value) \ -{ \ - std::basic_string buffer; \ - \ - stream >> buffer; \ - ::better_enums::optional converted = \ - Enum::_from_string_nothrow(buffer.c_str()); \ - \ - if (converted) \ - value = *converted; \ - else \ - stream.setstate(std::basic_istream::failbit); \ - \ - return stream; \ -} - - - -// Enum feature options. - -// C++98, C++11 -#define BETTER_ENUMS_CXX98_UNDERLYING_TYPE(Underlying) - -// C++11 -#define BETTER_ENUMS_CXX11_UNDERLYING_TYPE(Underlying) \ - : Underlying - -#if defined(_MSC_VER) && _MSC_VER >= 1700 -// VS 2012 and above fully support strongly typed enums and will warn about -// incorrect usage. -# define BETTER_ENUMS_LEGACY_UNDERLYING_TYPE(Underlying) \ - BETTER_ENUMS_CXX11_UNDERLYING_TYPE(Underlying) -#else -# define BETTER_ENUMS_LEGACY_UNDERLYING_TYPE(Underlying) \ - BETTER_ENUMS_CXX98_UNDERLYING_TYPE(Underlying) -#endif - -// C++98, C++11 -#define BETTER_ENUMS_REGULAR_ENUM_SWITCH_TYPE(Type) \ - _enumerated - -// C++11 -#define BETTER_ENUMS_ENUM_CLASS_SWITCH_TYPE(Type) \ - BETTER_ENUMS_NS(Type)::_enumClassForSwitchStatements - -// C++98, C++11 -#define BETTER_ENUMS_REGULAR_ENUM_SWITCH_TYPE_GENERATE(Underlying, ...) - -// C++11 -#define BETTER_ENUMS_ENUM_CLASS_SWITCH_TYPE_GENERATE(Underlying, ...) \ - enum class _enumClassForSwitchStatements : Underlying { __VA_ARGS__ }; - -// C++98 -#define BETTER_ENUMS_CXX98_TRIM_STRINGS_ARRAYS(Enum, ...) \ - inline const char** _raw_names() \ - { \ - static const char *value[] = \ - { BETTER_ENUMS_ID(BETTER_ENUMS_STRINGIZE(__VA_ARGS__)) }; \ - return value; \ - } \ - \ - inline char* _name_storage() \ - { \ - static char storage[] = \ - BETTER_ENUMS_ID(BETTER_ENUMS_RESERVE_STORAGE(__VA_ARGS__)); \ - return storage; \ - } \ - \ - inline const char** _name_array() \ - { \ - static const char *value[Enum::_size_constant]; \ - return value; \ - } \ - \ - inline bool& _initialized() \ - { \ - static bool value = false; \ - return value; \ - } - -// C++11 fast version -#define BETTER_ENUMS_CXX11_PARTIAL_CONSTEXPR_TRIM_STRINGS_ARRAYS(Enum, ...) \ - constexpr const char *_the_raw_names[] = \ - { BETTER_ENUMS_ID(BETTER_ENUMS_STRINGIZE(__VA_ARGS__)) }; \ - \ - constexpr const char * const * _raw_names() \ - { \ - return _the_raw_names; \ - } \ - \ - inline char* _name_storage() \ - { \ - static char storage[] = \ - BETTER_ENUMS_ID(BETTER_ENUMS_RESERVE_STORAGE(__VA_ARGS__)); \ - return storage; \ - } \ - \ - inline const char** _name_array() \ - { \ - static const char *value[Enum::_size_constant]; \ - return value; \ - } \ - \ - inline bool& _initialized() \ - { \ - static bool value = false; \ - return value; \ - } - -// C++11 slow all-constexpr version -#define BETTER_ENUMS_CXX11_FULL_CONSTEXPR_TRIM_STRINGS_ARRAYS(Enum, ...) \ - BETTER_ENUMS_ID(BETTER_ENUMS_TRIM_STRINGS(__VA_ARGS__)) \ - \ - constexpr const char * const _the_name_array[] = \ - { BETTER_ENUMS_ID(BETTER_ENUMS_REFER_TO_STRINGS(__VA_ARGS__)) }; \ - \ - constexpr const char * const * _name_array() \ - { \ - return _the_name_array; \ - } \ - \ - constexpr const char * const * _raw_names() \ - { \ - return _the_name_array; \ - } - -// C++98, C++11 fast version -#define BETTER_ENUMS_NO_CONSTEXPR_TO_STRING_KEYWORD - -// C++11 slow all-constexpr version -#define BETTER_ENUMS_CONSTEXPR_TO_STRING_KEYWORD \ - constexpr - -// C++98, C++11 fast version -#define BETTER_ENUMS_DO_DECLARE_INITIALIZE \ - static int initialize(); - -// C++11 slow all-constexpr version -#define BETTER_ENUMS_DECLARE_EMPTY_INITIALIZE \ - static int initialize() { return 0; } - -// C++98, C++11 fast version -#define BETTER_ENUMS_DO_DEFINE_INITIALIZE(Enum) \ - inline int Enum::initialize() \ - { \ - if (BETTER_ENUMS_NS(Enum)::_initialized()) \ - return 0; \ - \ - ::better_enums::_trim_names(BETTER_ENUMS_NS(Enum)::_raw_names(), \ - BETTER_ENUMS_NS(Enum)::_name_array(), \ - BETTER_ENUMS_NS(Enum)::_name_storage(), \ - _size()); \ - \ - BETTER_ENUMS_NS(Enum)::_initialized() = true; \ - \ - return 0; \ - } - -// C++11 slow all-constexpr version -#define BETTER_ENUMS_DO_NOT_DEFINE_INITIALIZE(Enum) - -// C++98, C++11 fast version -#define BETTER_ENUMS_DO_CALL_INITIALIZE(value) \ - ::better_enums::continue_with(initialize(), value) - -// C++11 slow all-constexpr version -#define BETTER_ENUMS_DO_NOT_CALL_INITIALIZE(value) \ - value - - - -// User feature selection. - -#ifdef BETTER_ENUMS_STRICT_CONVERSION -# define BETTER_ENUMS_DEFAULT_SWITCH_TYPE \ - BETTER_ENUMS_ENUM_CLASS_SWITCH_TYPE -# define BETTER_ENUMS_DEFAULT_SWITCH_TYPE_GENERATE \ - BETTER_ENUMS_ENUM_CLASS_SWITCH_TYPE_GENERATE -#else -# define BETTER_ENUMS_DEFAULT_SWITCH_TYPE \ - BETTER_ENUMS_REGULAR_ENUM_SWITCH_TYPE -# define BETTER_ENUMS_DEFAULT_SWITCH_TYPE_GENERATE \ - BETTER_ENUMS_REGULAR_ENUM_SWITCH_TYPE_GENERATE -#endif - - - -#ifndef BETTER_ENUMS_DEFAULT_CONSTRUCTOR -# define BETTER_ENUMS_DEFAULT_CONSTRUCTOR(Enum) \ - private: \ - Enum() : _value(0) { } -#endif - - - -#ifdef BETTER_ENUMS_HAVE_CONSTEXPR - -#ifdef BETTER_ENUMS_CONSTEXPR_TO_STRING -# define BETTER_ENUMS_DEFAULT_TRIM_STRINGS_ARRAYS \ - BETTER_ENUMS_CXX11_FULL_CONSTEXPR_TRIM_STRINGS_ARRAYS -# define BETTER_ENUMS_DEFAULT_TO_STRING_KEYWORD \ - BETTER_ENUMS_CONSTEXPR_TO_STRING_KEYWORD -# define BETTER_ENUMS_DEFAULT_DECLARE_INITIALIZE \ - BETTER_ENUMS_DECLARE_EMPTY_INITIALIZE -# define BETTER_ENUMS_DEFAULT_DEFINE_INITIALIZE \ - BETTER_ENUMS_DO_NOT_DEFINE_INITIALIZE -# define BETTER_ENUMS_DEFAULT_CALL_INITIALIZE \ - BETTER_ENUMS_DO_NOT_CALL_INITIALIZE -#else -# define BETTER_ENUMS_DEFAULT_TRIM_STRINGS_ARRAYS \ - BETTER_ENUMS_CXX11_PARTIAL_CONSTEXPR_TRIM_STRINGS_ARRAYS -# define BETTER_ENUMS_DEFAULT_TO_STRING_KEYWORD \ - BETTER_ENUMS_NO_CONSTEXPR_TO_STRING_KEYWORD -# define BETTER_ENUMS_DEFAULT_DECLARE_INITIALIZE \ - BETTER_ENUMS_DO_DECLARE_INITIALIZE -# define BETTER_ENUMS_DEFAULT_DEFINE_INITIALIZE \ - BETTER_ENUMS_DO_DEFINE_INITIALIZE -# define BETTER_ENUMS_DEFAULT_CALL_INITIALIZE \ - BETTER_ENUMS_DO_CALL_INITIALIZE -#endif - - - -// Top-level macros. - -#define BETTER_ENUM(Enum, Underlying, ...) \ - BETTER_ENUMS_ID(BETTER_ENUMS_TYPE( \ - BETTER_ENUMS_CXX11_UNDERLYING_TYPE, \ - BETTER_ENUMS_DEFAULT_SWITCH_TYPE, \ - BETTER_ENUMS_DEFAULT_SWITCH_TYPE_GENERATE, \ - BETTER_ENUMS_DEFAULT_TRIM_STRINGS_ARRAYS, \ - BETTER_ENUMS_DEFAULT_TO_STRING_KEYWORD, \ - BETTER_ENUMS_DEFAULT_DECLARE_INITIALIZE, \ - BETTER_ENUMS_DEFAULT_DEFINE_INITIALIZE, \ - BETTER_ENUMS_DEFAULT_CALL_INITIALIZE, \ - Enum, Underlying, __VA_ARGS__)) - -#define SLOW_ENUM(Enum, Underlying, ...) \ - BETTER_ENUMS_ID(BETTER_ENUMS_TYPE( \ - BETTER_ENUMS_CXX11_UNDERLYING_TYPE, \ - BETTER_ENUMS_DEFAULT_SWITCH_TYPE, \ - BETTER_ENUMS_DEFAULT_SWITCH_TYPE_GENERATE, \ - BETTER_ENUMS_CXX11_FULL_CONSTEXPR_TRIM_STRINGS_ARRAYS, \ - BETTER_ENUMS_CONSTEXPR_TO_STRING_KEYWORD, \ - BETTER_ENUMS_DECLARE_EMPTY_INITIALIZE, \ - BETTER_ENUMS_DO_NOT_DEFINE_INITIALIZE, \ - BETTER_ENUMS_DO_NOT_CALL_INITIALIZE, \ - Enum, Underlying, __VA_ARGS__)) - -#else - -#define BETTER_ENUM(Enum, Underlying, ...) \ - BETTER_ENUMS_ID(BETTER_ENUMS_TYPE( \ - BETTER_ENUMS_LEGACY_UNDERLYING_TYPE, \ - BETTER_ENUMS_DEFAULT_SWITCH_TYPE, \ - BETTER_ENUMS_DEFAULT_SWITCH_TYPE_GENERATE, \ - BETTER_ENUMS_CXX98_TRIM_STRINGS_ARRAYS, \ - BETTER_ENUMS_NO_CONSTEXPR_TO_STRING_KEYWORD, \ - BETTER_ENUMS_DO_DECLARE_INITIALIZE, \ - BETTER_ENUMS_DO_DEFINE_INITIALIZE, \ - BETTER_ENUMS_DO_CALL_INITIALIZE, \ - Enum, Underlying, __VA_ARGS__)) - -#endif - - - -namespace better_enums { - -// Maps. - -template -struct map_compare { - BETTER_ENUMS_CONSTEXPR_ static bool less(const T& a, const T& b) - { return a < b; } -}; - -template <> -struct map_compare { - BETTER_ENUMS_CONSTEXPR_ static bool less(const char *a, const char *b) - { return less_loop(a, b); } - - private: - BETTER_ENUMS_CONSTEXPR_ static bool - less_loop(const char *a, const char *b, size_t index = 0) - { - return - a[index] != b[index] ? a[index] < b[index] : - a[index] == '\0' ? false : - less_loop(a, b, index + 1); - } -}; - -template <> -struct map_compare { - BETTER_ENUMS_CONSTEXPR_ static bool less(const wchar_t *a, const wchar_t *b) - { return less_loop(a, b); } - - private: - BETTER_ENUMS_CONSTEXPR_ static bool - less_loop(const wchar_t *a, const wchar_t *b, size_t index = 0) - { - return - a[index] != b[index] ? a[index] < b[index] : - a[index] == L'\0' ? false : - less_loop(a, b, index + 1); - } -}; - -template > -struct map { - typedef T (*function)(Enum); - - BETTER_ENUMS_CONSTEXPR_ explicit map(function f) : _f(f) { } - - BETTER_ENUMS_CONSTEXPR_ T from_enum(Enum value) const { return _f(value); } - BETTER_ENUMS_CONSTEXPR_ T operator [](Enum value) const - { return _f(value); } - - BETTER_ENUMS_CONSTEXPR_ Enum to_enum(T value) const - { - return - _or_throw(to_enum_nothrow(value), "map::to_enum: invalid argument"); - } - - BETTER_ENUMS_CONSTEXPR_ optional - to_enum_nothrow(T value, size_t index = 0) const - { - return - index >= Enum::_size() ? optional() : - Compare::less(_f(Enum::_values()[index]), value) || - Compare::less(value, _f(Enum::_values()[index])) ? - to_enum_nothrow(value, index + 1) : - Enum::_values()[index]; - } - - private: - const function _f; -}; - -template -BETTER_ENUMS_CONSTEXPR_ map make_map(T (*f)(Enum)) -{ - return map(f); -} - -} - -#define BETTER_ENUMS_DECLARE_STD_HASH(type) \ - namespace std { \ - template <> struct hash \ - { \ - size_t operator()(const type &x) const \ - { \ - return std::hash()(x._to_integral()); \ - } \ - }; \ - } - -#endif // #ifndef BETTER_ENUMS_ENUM_H diff --git a/ariles/cpput/include/cpput/config.h.in b/ariles/cpput/include/cpput/config.h.in deleted file mode 100644 index b00bb219..00000000 --- a/ariles/cpput/include/cpput/config.h.in +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef H_@CPPUT_ID@_CPPUT_CONFIG -#define H_@CPPUT_ID@_CPPUT_CONFIG -// __func__ ? -#cmakedefine CMAKEUT_COMPILER_SUPPORTS_FUNC_ -// __FUNCTION__ ? -#cmakedefine CMAKEUT_COMPILER_SUPPORTS_FUNCTION_ -#endif diff --git a/ariles/cpput/include/cpput/deprecation.h.in b/ariles/cpput/include/cpput/deprecation.h.in deleted file mode 100644 index 55023812..00000000 --- a/ariles/cpput/include/cpput/deprecation.h.in +++ /dev/null @@ -1,24 +0,0 @@ -/** - @file - @author Alexander Sherikov - - @copyright 2019 Alexander Sherikov, Licensed under the Apache License, Version 2.0. - (see @ref LICENSE or http://www.apache.org/licenses/LICENSE-2.0) - - @brief Deprecation macro -*/ - -#ifndef H_@CPPUT_ID@_DEPRECATION -#define H_@CPPUT_ID@_DEPRECATION - -#ifdef __GNUC__ - -# define @CPPUT_ID@_DEPRECATED __attribute__((deprecated)) - -#else - -# define @CPPUT_ID@_DEPRECATED - -#endif - -#endif diff --git a/ariles/cpput/include/cpput/exception.h.in b/ariles/cpput/include/cpput/exception.h.in deleted file mode 100644 index 326f2823..00000000 --- a/ariles/cpput/include/cpput/exception.h.in +++ /dev/null @@ -1,43 +0,0 @@ -/** - @file - @author Alexander Sherikov - - @copyright 2019 Alexander Sherikov, Licensed under the Apache License, Version 2.0. - (see @ref LICENSE or http://www.apache.org/licenses/LICENSE-2.0) - - @brief Throw & assert macro -*/ - -#ifndef H_@CPPUT_ID@_EXCEPTION -#define H_@CPPUT_ID@_EXCEPTION - -#include -#include - -#define @CPPUT_ID@_THROW_EXCEPTION(exception_type, message) throw exception_type((message)) - -#ifdef CMAKEUT_COMPILER_SUPPORTS_FUNC_ -# define @CPPUT_ID@_THROW(s) @CPPUT_ID@_THROW_EXCEPTION(std::runtime_error, (std::string("In ") + __func__ + "() // " + (s))) -#else // -# ifdef CMAKEUT_COMPILER_SUPPORTS_FUNCTION_ -# define @CPPUT_ID@_THROW(s) \ - @CPPUT_ID@_THROW_EXCEPTION(std::runtime_error, (std::string("In ") + __FUNCTION__ + "() // " + (s))) -# else // -# define @CPPUT_ID@_THROW(s) @CPPUT_ID@_THROW_EXCEPTION(std::runtime_error, (s)) -# endif // -#endif // - - -#define @CPPUT_ID@_PERSISTENT_ASSERT(condition, message) \ - if (!(condition)) \ - { \ - @CPPUT_ID@_THROW(message); \ - }; - -#ifdef DNDEBUG -# define @CPPUT_ID@_ASSERT(condition, message) -#else -# define @CPPUT_ID@_ASSERT(condition, message) @CPPUT_ID@_PERSISTENT_ASSERT(condition, message) -#endif - -#endif diff --git a/ariles/cpput/include/cpput/flags.h.in b/ariles/cpput/include/cpput/flags.h.in deleted file mode 100644 index acef5f9d..00000000 --- a/ariles/cpput/include/cpput/flags.h.in +++ /dev/null @@ -1,86 +0,0 @@ -/** - @file - @author Alexander Sherikov - - @copyright 2019 Alexander Sherikov, Licensed under the Apache License, Version 2.0. - - @brief -*/ - -#pragma once - -#ifndef H_@CPPUT_ID@_FLAGS -#define H_@CPPUT_ID@_FLAGS - -namespace @CPPUT_ID_LOWER_CASE@ -{ - template - class Flags - { - public: - enum Action - { - DEFAULT = 0, - REPLACE = 1, - SET = 2, - UNSET = 3 - }; - - - public: - t_Integer flags_; - - - public: - void initialize(const t_Integer flags, const Action action_type = REPLACE) - { - switch (action_type) - { - case REPLACE: - replace(flags); - break; - - case SET: - static_cast(this)->setDefaults(); - set(flags); - break; - - case UNSET: - static_cast(this)->setDefaults(); - unset(flags); - break; - - default: - @CPPUT_ID@_THROW("Unknown Flags::Action type."); - } - } - - - void copy(const t_Derived &from, const t_Integer mask) - { - set(from.flags_ & mask); - } - - bool isSet(const t_Integer flags) const - { - return (flags_ & flags); - } - - void replace(const t_Integer flags) - { - flags_ = flags; - } - - void set(const t_Integer flags) - { - flags_ |= flags; - } - - void unset(const t_Integer flags) - { - flags_ &= ~flags; - } - }; -} // namespace @CPPUT_ID_LOWER_CASE@ - -#endif diff --git a/ariles/cpput/include/cpput/floating_point_utils.h.in b/ariles/cpput/include/cpput/floating_point_utils.h.in deleted file mode 100644 index bd9e3cb8..00000000 --- a/ariles/cpput/include/cpput/floating_point_utils.h.in +++ /dev/null @@ -1,53 +0,0 @@ -/** - @file - @author Alexander Sherikov - - @copyright 2019 Alexander Sherikov, Licensed under the Apache License, Version 2.0. - (see @ref LICENSE or http://www.apache.org/licenses/LICENSE-2.0) - - @brief NaN and infinity checks, loosely based on - https://github.com/opencv/opencv/blob/3.0.0/modules/hal/include/opencv2/hal/defs.h -*/ - - -#ifndef H_@CPPUT_ID@_FP_UTILS -#define H_@CPPUT_ID@_FP_UTILS - -#include -#include - -namespace @CPPUT_ID_LOWER_CASE@ -{ - inline bool isNaN(const double value) - { - uint64_t raw; - memcpy(&raw, &value, sizeof(double)); - return (((uint32_t)(raw >> 32) & 0x7fffffff) + ((uint32_t)raw != 0) > 0x7ff00000); - } - - - inline bool isInfinity(const double value) - { - uint64_t raw; - memcpy(&raw, &value, sizeof(double)); - return (((uint32_t)(raw >> 32) & 0x7fffffff) == 0x7ff00000 && (uint32_t)raw == 0); - } - - - inline bool isNaN(const float value) - { - uint32_t raw; - memcpy(&raw, &value, sizeof(float)); - return ((raw & 0x7fffffff) > 0x7f800000); - } - - - inline bool isInfinity(const float value) - { - uint32_t raw; - memcpy(&raw, &value, sizeof(float)); - return ((raw & 0x7fffffff) == 0x7f800000); - } -} // namespace @CPPUT_ID_LOWER_CASE@ - -#endif diff --git a/ariles/cpput/include/cpput/location.h.in b/ariles/cpput/include/cpput/location.h.in deleted file mode 100644 index bd70ae54..00000000 --- a/ariles/cpput/include/cpput/location.h.in +++ /dev/null @@ -1,124 +0,0 @@ -/** - @file - @author Alexander Sherikov - @copyright 2019 Alexander Sherikov, Licensed under the Apache License, Version 2.0. - (see @ref LICENSE or http://www.apache.org/licenses/LICENSE-2.0) - - @brief -*/ - -#ifndef H_@CPPUT_ID@_LOCATION -#define H_@CPPUT_ID@_LOCATION - -#include - -namespace @CPPUT_ID_LOWER_CASE@ -{ - /** - * @brief Location of a data chunk (offset + length). - */ - class Location - { - public: - std::size_t offset_; - std::size_t length_; - - - public: - /** - * @brief Constructor - */ - Location() - { - set(0, 0); - } - - - /** - * @brief Construct location with given parameters - * - * @param[in] offset offset - * @param[in] length length - */ - Location(const std::size_t offset, const std::size_t length) - { - set(offset, length); - } - - - /** - * @brief Compare two locations - * - * @param[in] another_location some other location - * - * @return true/false - */ - bool operator==(const Location &another_location) const - { - return ((offset_ == another_location.offset_) && (length_ == another_location.length_)); - } - - - /** - * @brief Compare two locations - * - * @param[in] another_location some other location - * - * @return true/false - */ - bool operator!=(const Location &another_location) const - { - return (!(*this == another_location)); - } - - - /** - * @brief Check length of location - * - * @param[in] max_length maximal length - * - * @return true if location is valid - */ - bool checkLength(const std::size_t max_length) const - { - return ((offset_ <= end()) && (end() <= max_length)); - } - - - /** - * @brief Offset of the first element - * - * @return offset of the first element (offset_) - */ - std::size_t front() const - { - return (offset_); - } - - - /** - * @brief Offset of the element following the last element - * - * @return offset of the element following the last element (offset_ + length_) - */ - std::size_t end() const - { - return (offset_ + length_); - } - - - /** - * @brief Set location. - * - * @param[in] offset offset - * @param[in] length length - */ - void set(const std::size_t offset, const std::size_t length) - { - offset_ = offset; - length_ = length; - } - }; -} // namespace humoto - -#endif diff --git a/ariles/cpput/include/cpput/math_utils.h.in b/ariles/cpput/include/cpput/math_utils.h.in deleted file mode 100644 index 43f72938..00000000 --- a/ariles/cpput/include/cpput/math_utils.h.in +++ /dev/null @@ -1,77 +0,0 @@ -/** - @file - @author Alexander Sherikov - @copyright 2019 Alexander Sherikov, Licensed under the Apache License, Version 2.0. - (see @ref LICENSE or http://www.apache.org/licenses/LICENSE-2.0) - - @brief -*/ - -#ifndef H_@CPPUT_ID@_MATH -#define H_@CPPUT_ID@_MATH - -#include - -namespace @CPPUT_ID_LOWER_CASE@ -{ - namespace math - { - //======================================================================== - // Constants - //======================================================================== - /// PI constant - const double g_pi = 3.14159265358979323846; - - - //======================================================================== - // Math - //======================================================================== - - /** - * @brief Returns true if the difference between two given variables is - * below the given tolerance. - * - * @param[in] var1 - * @param[in] var2 - * @param[in] tol - * - * @return true / false - */ - inline bool isApproximatelyEqual(const double var1, const double var2, const double tol) - { - return (std::abs(var1 - var2) < tol); - } - - - //======================================================================== - // Geometry - //======================================================================== - - /** - * @brief Convert degrees to radians - * - * @param[in] degrees degrees - * - * @return radians - */ - inline double convertDegreesToRadians(const double degrees) - { - return (g_pi * degrees / 180); - } - - - /** - * @brief Convert radians to degrees - * - * @param[in] radians - * - * @return degrees - */ - inline double convertRadiansToDegrees(const double radians) - { - return (radians * 180 / g_pi); - } - } // namespace math -} // namespace @CPPUT_ID_LOWER_CASE@ - -#endif diff --git a/ariles/cpput/include/cpput/misc.h.in b/ariles/cpput/include/cpput/misc.h.in deleted file mode 100644 index d183c754..00000000 --- a/ariles/cpput/include/cpput/misc.h.in +++ /dev/null @@ -1,23 +0,0 @@ -/** - @file - @author Alexander Sherikov - - @copyright 2019 Alexander Sherikov, Licensed under the Apache License, Version 2.0. - (see @ref LICENSE or http://www.apache.org/licenses/LICENSE-2.0) - - @brief Various one-liners -*/ - -#ifndef H_@CPPUT_ID@_MISC -#define H_@CPPUT_ID@_MISC - -/** - * Sometimes it is not possible to omit name of an unused parameter, in such - * cases this macro can be used to suppress compiler warnings about unused - * parameters. - */ -#define @CPPUT_ID@_UNUSED_ARG(parameter) (void)parameter; - -#define @CPPUT_ID@_MACRO_SUBSTITUTE(macro) macro - -#endif diff --git a/ariles/cpput/include/cpput/popl.h b/ariles/cpput/include/cpput/popl.h deleted file mode 100644 index 23cbb128..00000000 --- a/ariles/cpput/include/cpput/popl.h +++ /dev/null @@ -1,1257 +0,0 @@ -/*** - ____ __ ____ __ - ( _ \ / \( _ \( ) - ) __/( O )) __// (_/\ - (__) \__/(__) \____/ - version 1.2.0 - https://github.com/badaix/popl - - This file is part of popl (program options parser lib) - Copyright (C) 2015-2018 Johannes Pohl - - This software may be modified and distributed under the terms - of the MIT license. See the LICENSE file for details. -***/ - -/// checked with clang-tidy: -/// run-clang-tidy-3.8.py -header-filter='.*' -checks='*,-misc-definitions-in-headers,-google-readability-braces-around-statements,-readability-braces-around-statements,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-google-build-using-namespace,-google-build-using-namespace' - -#ifndef POPL_HPP -#define POPL_HPP - -#ifndef NOMINMAX -#define NOMINMAX -#endif // NOMINMAX - -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace popl -{ - -#define POPL_VERSION "1.2.0" - - -/// Option's argument type -/** - * Switch has "no" argument - * Value has "required" argument - * Implicit has "optional" argument - */ -enum class Argument -{ - no = 0, // option never takes an argument - required, // option always requires an argument - optional // option may take an argument -}; - - -/// Option's attribute -/** - * inactive: Option is not set and will not be parsed - * hidden: Option is active, but will not show up in the help message - * required: Option must be set on the command line. Otherwise an exception will be thrown - * optional: Option must not be set. Default attribute. - * advanced: Option is advanced and will only show up in the advanced help message - * expoert: Option is expert and will only show up in the expert help message - */ -enum class Attribute -{ - inactive = 0, - hidden = 1, - required = 2, - optional = 3, - advanced = 4, - expert = 5 -}; - - -/// Option name type. Used in invalid_option exception. -/** - * unspecified: not specified - * short_name: The option's short name - * long_name: The option's long name - */ -enum class OptionName -{ - unspecified, - short_name, - long_name -}; - - -/// Abstract Base class for Options -/** - * Base class for Options - * holds just configuration data, no runtime data. - * Option is not bound to a special type "T" - */ -class Option -{ -friend class OptionParser; -public: - /// Construct an Option - /// @param short_name the options's short name. Must be empty or one character. - /// @param long_name the option's long name. Can be empty. - /// @param description the Option's description that will be shown in the help message - Option(const std::string& short_name, const std::string& long_name, std::string description); - - /// Destructor - virtual ~Option() = default; - - /// default copy constructor - Option(const Option&) = default; - - /// default move constructor - Option(Option&&) = default; - - /// default assignement operator - Option& operator=(const Option&) = default; - - /// default move assignement operator - Option& operator=(Option&&) = default; - - /// Get the Option's short name - /// @return character of the options's short name or 0 if no short name is defined - char short_name() const; - - /// Get the Option's long name - /// @return the long name of the Option. Empty string if no long name is defined - std::string long_name() const; - - /// Get the Option's long or short name - /// @param what_name the option's name to return - /// @param what_hyphen preced the returned name with (double-)hypen - /// @return the requested name of the Option. Empty string if not defined. - std::string name(OptionName what_name, bool with_hypen = false) const; - - /// Get the Option's description - /// @return the description - std::string description() const; - - /// Get the Option's default value - /// @param out stream to write the default value to - /// @return true if a default value is available, false if not - virtual bool get_default(std::ostream& out) const = 0; - - /// Set the Option's attribute - /// @param attribute - void set_attribute(const Attribute& attribute); - - /// Get the Option's attribute - /// @return the Options's attribute - Attribute attribute() const; - - /// Get the Option's argument type - /// @return argument type (no, required, optional) - virtual Argument argument_type() const = 0; - - /// Check how often the Option is set on command line - /// @return the Option's count on command line - virtual size_t count() const = 0; - - /// Check if the Option is set - /// @return true if set at least once - virtual bool is_set() const = 0; - -protected: - /// Parse the command line option and fill the internal data structure - /// @param what_name short or long option name - /// @param value the value as given on command line - virtual void parse(OptionName what_name, const char* value) = 0; - - /// Clear the internal data structure - virtual void clear() = 0; - - std::string short_name_; - std::string long_name_; - std::string description_; - Attribute attribute_; -}; - - - - -/// Value option with optional default value -/** - * Value option with optional default value - * If set, it requires an argument - */ -template -class Value : public Option -{ -public: - /// Construct an Value Option - /// @param short_name the option's short name. Must be empty or one character. - /// @param long_name the option's long name. Can be empty. - /// @param description the Option's description that will be shown in the help message - Value(const std::string& short_name, const std::string& long_name, const std::string& description); - - /// Construct an Value Option - /// @param short_name the option's short name. Must be empty or one character. - /// @param long_name the option's long name. Can be empty. - /// @param description the Option's description that will be shown in the help message - /// @param default_val the Option's default value - /// @param assign_to pointer to a variable to assign the parsed command line value to - Value(const std::string& short_name, const std::string& long_name, const std::string& description, const T& default_val, T* assign_to = nullptr); - - size_t count() const override; - bool is_set() const override; - - /// Assign the last parsed command line value to "var" - /// @param var pointer to the variable where is value is written to - void assign_to(T* var); - - /// Manually set the Option's value. Deletes current value(s) - /// @param value the new value of the option - void set_value(const T& value); - - /// Get the Option's value. Will throw if option at index idx is not available - /// @param idx the zero based index of the value (if set multiple times) - /// @return the Option's value at index "idx" - T value(size_t idx = 0) const; - - /// Set the Option's default value - /// @param value the default value if not specified on command line - void set_default(const T& value); - - /// Check if the Option has a default value - /// @return true if the Option has a default value - bool has_default() const; - - /// Get the Option's default value. Will throw if no default is set. - /// @return the Option's default value - T get_default() const; - bool get_default(std::ostream& out) const override; - - Argument argument_type() const override; - -protected: - void parse(OptionName what_name, const char* value) override; - std::unique_ptr default_; - - virtual void update_reference(); - virtual void add_value(const T& value); - void clear() override; - - T* assign_to_; - std::vector values_; -}; - - - - -/// Value option with implicit default value -/** - * Value option with implicit default value - * If set, an argument is optional - * -without argument it carries the implicit default value - * -with argument it carries the explicit value - */ -template -class Implicit : public Value -{ -public: - Implicit(const std::string& short_name, const std::string& long_name, const std::string& description, const T& implicit_val, T* assign_to = nullptr); - - Argument argument_type() const override; - -protected: - void parse(OptionName what_name, const char* value) override; -}; - - - - -/// Value option without value -/** - * Value option without value - * Does not require an argument - * Can be either set or not set - */ -class Switch : public Value -{ -public: - Switch(const std::string& short_name, const std::string& long_name, const std::string& description, bool* assign_to = nullptr); - - void set_default(const bool& value) = delete; - Argument argument_type() const override; - -protected: - void parse(OptionName what_name, const char* value) override; -}; - - - - -using Option_ptr = std::shared_ptr