diff --git a/.circleci/config.yml b/.circleci/config.yml index b0f5da4..afe3303 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -17,47 +17,44 @@ jobs: name: "Update packages" command: sudo pacman -Syu --noconfirm - run: - name: "Install git" - command: sudo pacman -S --noconfirm git + name: "Install Git and SSH" + command: sudo pacman -S --noconfirm git openssh - checkout - run: name: "Install development packages" command: | - sudo pacman -S --noconfirm cmake gcc make base-devel curl libprocps - sudo pacman -Ss procps + sudo pacman -S --noconfirm cmake gcc make base-devel curl - run: name: "Build library" command: | - curl https://raw.githubusercontent.com/Autorevision/autorevision/master/autorevision.sh -o autorevision - git branch - echo "======== RUNNING AUTOREVISION ====" - chmod 777 autorevision + curl -fsSL https://raw.githubusercontent.com/Autorevision/autorevision/master/autorevision.sh -o autorevision + chmod +x autorevision ./autorevision -t h > autorevision.h cmake -B build - make -C build + cmake --build build --parallel + cmake --build build --target test build-debian-linux: docker: - - image: debian:bullseye + - image: debian:trixie steps: - run: name: "Update packages" command: | - apt update - apt-get -y upgrade + apt-get update - run: name: "Install packages" - command: apt-get -y install libprocps-dev gcc cmake make build-essential git curl + command: apt-get install -y --no-install-recommends ca-certificates openssh-client gcc cmake make build-essential git curl - checkout - run: name: "Build library" command: | - curl https://raw.githubusercontent.com/Autorevision/autorevision/master/autorevision.sh -o autorevision - git branch - chmod 777 autorevision + curl -fsSL https://raw.githubusercontent.com/Autorevision/autorevision/master/autorevision.sh -o autorevision + chmod +x autorevision ./autorevision -t h > autorevision.h cmake -B build - make -C build + cmake --build build --parallel + cmake --build build --target test # Invoke jobs via workflows # See: https://circleci.com/docs/2.0/configuration-reference/#workflows @@ -65,4 +62,4 @@ workflows: build-workflow: jobs: - build-manjaro-linux - - build-debian-linux \ No newline at end of file + - build-debian-linux diff --git a/.github/workflows/build_ubuntu.yml b/.github/workflows/build_ubuntu.yml index 19f9558..4cf80fd 100644 --- a/.github/workflows/build_ubuntu.yml +++ b/.github/workflows/build_ubuntu.yml @@ -1,37 +1,45 @@ -name: ubuntults +name: Build (Ubuntu) -on: [push, pull_request] +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: build-ubuntu-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: build: + name: ${{ matrix.systems }} runs-on: ${{ matrix.systems }} + timeout-minutes: 15 strategy: + fail-fast: false matrix: - systems: [ubuntu-20.04,ubuntu-22.04] + systems: [ubuntu-22.04,ubuntu-24.04] steps: - - uses: actions/checkout@v3 - - name: Configure CMake - run: cmake -G "Unix Makefiles" -B build + - uses: actions/checkout@v6 + with: + fetch-depth: 0 - - name: Generate revision information - shell: bash + - name: Install build dependencies run: | - sudo apt-get -y install autorevision - autorevision -t h > autorevision.h + sudo apt-get update + sudo apt-get install -y autorevision - - name: Build libhack - run: | - sudo apt-get install libprocps-dev - make - working-directory: build + - name: Generate revision information + run: autorevision -t h > autorevision.h - - name: Configure CMake (examples) - run: | - cp ../../../build/*.so libhack.so - cmake -G "Unix Makefiles" -B build - working-directory: src/examples/linux + - name: Configure CMake + run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DLIBHACK_BUILD_EXAMPLES=ON + + - name: Build library and examples + run: cmake --build build --parallel - - name: Build examples - run: make - working-directory: src/examples/linux/build + - name: Run tests + run: cmake --build build --target test diff --git a/.github/workflows/build_windows.yml b/.github/workflows/build_windows.yml index 67a208a..0491e85 100644 --- a/.github/workflows/build_windows.yml +++ b/.github/workflows/build_windows.yml @@ -1,36 +1,44 @@ -name: windows +name: Build (Windows) -on: [push, pull_request] +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: build-windows-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: build: + name: ${{ matrix.systems }} runs-on: ${{ matrix.systems }} + timeout-minutes: 15 strategy: + fail-fast: false matrix: - systems: [windows-latest,windows-2019] + systems: [windows-2022,windows-2025] steps: - - uses: actions/checkout@v3 - - name: Configure CMake - run: cmake -G "MinGW Makefiles" -B build + - uses: actions/checkout@v6 + with: + fetch-depth: 0 - name: Generate revision information shell: bash run: | - curl https://raw.githubusercontent.com/Autorevision/autorevision/master/autorevision.sh -o autorevision + curl -fsSL https://raw.githubusercontent.com/Autorevision/autorevision/master/autorevision.sh -o autorevision + chmod +x autorevision ./autorevision -t h > autorevision.h - - name: Build libhack - run: make - working-directory: build + - name: Configure CMake + run: cmake -G "MinGW Makefiles" -S . -B build -DCMAKE_BUILD_TYPE=Release -DLIBHACK_BUILD_EXAMPLES=ON - - name: Configure CMake (examples) - run: | - cp ../../../build/*.dll libhack.dll - cp ../../../build/*.a libhack.a - cmake -G "MinGW Makefiles" -B build - working-directory: src/examples/windows - - - name: Build examples - run: make - working-directory: src/examples/windows/build + - name: Build library and examples + run: cmake --build build --parallel + + - name: Run tests + run: cmake --build build --target test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4a5bef5..b067e50 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,19 +5,103 @@ on: tags: - "v*" +permissions: + contents: read + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + jobs: - release: - runs-on: "ubuntu-latest" + package: + name: Package (${{ matrix.platform }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + - platform: linux-x86_64 + os: ubuntu-22.04 + - platform: windows-x86_64 + os: windows-2025 + steps: - - uses: actions/checkout@v2 + - name: Checkout source + uses: actions/checkout@v6 with: fetch-depth: 0 - - name: Get Date - id: date - run: echo "::set-output name=date::$(date +'%m-%d-%Y-%H-%M')" - - name: Make release - uses: "marvinpinto/action-automatic-releases@latest" + - name: Install Linux dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y autorevision + + - name: Generate revision information (Linux) + if: runner.os == 'Linux' + run: autorevision -t h > autorevision.h + + - name: Generate revision information (Windows) + if: runner.os == 'Windows' + shell: bash + run: | + curl -fsSL https://raw.githubusercontent.com/Autorevision/autorevision/master/autorevision.sh -o autorevision + chmod +x autorevision + ./autorevision -t h > autorevision.h + + - name: Configure CMake (Linux) + if: runner.os == 'Linux' + run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release + + - name: Configure CMake (Windows) + if: runner.os == 'Windows' + run: cmake -G "MinGW Makefiles" -S . -B build -DCMAKE_BUILD_TYPE=Release + + - name: Build library + run: cmake --build build --parallel + + - name: Run tests + run: cmake --build build --target test + + - name: Install package + run: cmake --install build --prefix package + + - name: Create Linux archive + if: runner.os == 'Linux' + run: tar -czf "libhack-${{ github.ref_name }}-${{ matrix.platform }}.tar.gz" -C package . + + - name: Create Windows archive + if: runner.os == 'Windows' + shell: pwsh + run: Compress-Archive -Path package\* -DestinationPath "libhack-${{ github.ref_name }}-${{ matrix.platform }}.zip" + + - name: Upload package + uses: actions/upload-artifact@v7 with: - repo_token: "${{ secrets.GITHUB_TOKEN }}" - prerelease: false + name: libhack-${{ matrix.platform }} + path: libhack-${{ github.ref_name }}-${{ matrix.platform }}.* + if-no-files-found: error + + publish: + name: Publish GitHub release + needs: package + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: write + steps: + - name: Download packages + uses: actions/download-artifact@v8 + with: + path: release-assets + merge-multiple: true + + - name: Generate checksums + run: sha256sum release-assets/* | tee release-assets/SHA256SUMS + + - name: Publish release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: gh release create "${{ github.ref_name }}" release-assets/* --repo "${{ github.repository }}" --verify-tag --generate-notes diff --git a/.github/workflows/sonarcloud_linux.yml b/.github/workflows/sonarcloud_linux.yml index a7d6e1e..16d58c6 100644 --- a/.github/workflows/sonarcloud_linux.yml +++ b/.github/workflows/sonarcloud_linux.yml @@ -1,4 +1,5 @@ name: SonarQube Cloud + on: push: branches: @@ -6,38 +7,48 @@ on: - dev pull_request: types: [opened, synchronize, reopened] + +permissions: + contents: read + +concurrency: + group: sonar-linux-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: build: name: Build and analyze (Linux) - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 + timeout-minutes: 20 env: BUILD_WRAPPER_OUT_DIR: build_wrapper_output_directory # Directory where build-wrapper output will be placed steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - name: Install sonar-scanner and build-wrapper - uses: SonarSource/sonarcloud-github-c-cpp@v3 + - name: Install Build Wrapper + uses: SonarSource/sonarqube-scan-action/install-build-wrapper@v8.1.0 - name: Setup build environment run: | - cmake -S . -B build - sudo apt-get -y install autorevision + sudo apt-get update + sudo apt-get install -y autorevision autorevision -t h > autorevision.h - sudo apt-get install libprocps-dev + cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DLIBHACK_ENABLE_COVERAGE=ON - name: Run build-wrapper run: | - build-wrapper-linux-x86-64 --out-dir ${{ env.BUILD_WRAPPER_OUT_DIR }} cmake --build build/ --config Release + build-wrapper-linux-x86-64 --out-dir ${{ env.BUILD_WRAPPER_OUT_DIR }} cmake --build build/ --config Debug - name: Run tests to generate coverage statistics run: | - ./build/unit_test + cmake --build build --target test - - name: Run sonar-scanner + - name: SonarQube Scan env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: | - sonar-scanner --define sonar.cfamily.compile-commands="${{ env.BUILD_WRAPPER_OUT_DIR }}/compile_commands.json" + uses: SonarSource/sonarqube-scan-action@v8.1.0 + with: + args: > + --define "sonar.cfamily.compile-commands=${{ env.BUILD_WRAPPER_OUT_DIR }}/compile_commands.json" diff --git a/.github/workflows/sonarcloud_windows.yml b/.github/workflows/sonarcloud_windows.yml index 456bba4..1f8b697 100644 --- a/.github/workflows/sonarcloud_windows.yml +++ b/.github/workflows/sonarcloud_windows.yml @@ -1,4 +1,5 @@ name: SonarQube Cloud + on: push: branches: @@ -6,34 +7,48 @@ on: - dev pull_request: types: [opened, synchronize, reopened] + +permissions: + contents: read + +concurrency: + group: sonar-windows-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: build: name: Build and analyze (Windows) - runs-on: windows-latest + runs-on: windows-2025 + timeout-minutes: 20 env: BUILD_WRAPPER_OUT_DIR: build_wrapper_output_directory # Directory where build-wrapper output will be placed steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - name: Install sonar-scanner and build-wrapper - uses: SonarSource/sonarcloud-github-c-cpp@v3 + - name: Install Build Wrapper + uses: SonarSource/sonarqube-scan-action/install-build-wrapper@v8.1.0 - name: Setup build environment shell: bash run: | - cmake -G "MinGW Makefiles" -B build - curl https://raw.githubusercontent.com/Autorevision/autorevision/master/autorevision.sh -o autorevision + curl -fsSL https://raw.githubusercontent.com/Autorevision/autorevision/master/autorevision.sh -o autorevision + chmod +x autorevision ./autorevision -t h > autorevision.h + cmake -G "MinGW Makefiles" -S . -B build -DCMAKE_BUILD_TYPE=Release - name: Run build-wrapper run: | - build-wrapper-win-x86-64 --out-dir ${{ env.BUILD_WRAPPER_OUT_DIR }} make -C build + build-wrapper-win-x86-64 --out-dir ${{ env.BUILD_WRAPPER_OUT_DIR }} cmake --build build --config Release - - name: Run sonar-scanner + - name: Run tests + run: cmake --build build --target test + + - name: SonarQube Scan env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: | - sonar-scanner --define sonar.cfamily.compile-commands="${{ env.BUILD_WRAPPER_OUT_DIR }}/compile_commands.json" + uses: SonarSource/sonarqube-scan-action@v8.1.0 + with: + args: > + --define "sonar.cfamily.compile-commands=${{ env.BUILD_WRAPPER_OUT_DIR }}/compile_commands.json" diff --git a/CMakeLists.txt b/CMakeLists.txt index c060bdb..5ba939e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,56 +1,131 @@ -cmake_minimum_required(VERSION 3.10) - -# set the project name -project(libhack) - -# add source files to build shared library -add_library(hack SHARED - src/main.c - src/process.c - src/init.c - src/process.h - src/consts.h - src/init.h - src/logger.c - src/logger.h - src/types.c - src/types.h -) - -add_executable(unit_test - src/unit_test.c - src/main.c - src/process.c - src/init.c - src/process.h - src/logger.c - src/types.c -) - -set(CMAKE_C_STANDARD 17) - -if (CMAKE_COMPILER_IS_GNUCC) - target_compile_options(hack PRIVATE -Wall -Wextra) - target_compile_options(unit_test PRIVATE --coverage -fprofile-arcs -ftest-coverage) - target_link_libraries(unit_test gcov) -endif() - -# configure target properties -set_target_properties(hack - PROPERTIES ARCHIVE_OUTPUT_NAME hack -) - -# configure dll exporting -add_definitions(-DDLL_EXPORT -DDEBUG) - -if(WIN32) - message(STATUS "generating makefile for windows target") - target_link_libraries(hack psapi shlwapi) - target_link_libraries(unit_test psapi shlwapi) -elseif(UNIX) - message(STATUS "generating makefile for unix target") - target_link_libraries(hack procps) - target_link_libraries(unit_test procps) -endif() - - +cmake_minimum_required(VERSION 3.15) + +project(libhack VERSION 0.4.2 LANGUAGES C) + +include(CTest) +include(GNUInstallDirs) + +option(LIBHACK_BUILD_EXAMPLES "Build the platform-specific examples" OFF) +option(LIBHACK_ENABLE_COVERAGE "Enable compiler coverage instrumentation" OFF) +option(LIBHACK_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF) + +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +if(LIBHACK_BUILD_EXAMPLES AND WIN32) + enable_language(CXX) +endif() + +set(LIBHACK_SOURCES + src/init.c + src/logger.c + src/process.c + src/status_codes.c + src/types.c +) + +set(LIBHACK_HEADERS + src/consts.h + src/init.h + src/logger.h + src/mingw_aliases.h + src/platform.h + src/process.h + src/status_codes.h + src/types.h + autorevision.h +) + +add_library(hack SHARED ${LIBHACK_SOURCES} ${LIBHACK_HEADERS}) +add_library(libhack::hack ALIAS hack) + +target_compile_features(hack PUBLIC c_std_17) +set_target_properties(hack PROPERTIES + C_EXTENSIONS OFF + C_STANDARD_REQUIRED ON + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} + OUTPUT_NAME hack +) + +target_include_directories(hack + PUBLIC + $ + $ +) + +target_compile_definitions(hack PRIVATE DLL_EXPORT) + +if(MSVC) + target_compile_options(hack PRIVATE /W4) +elseif(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(hack PRIVATE -Wall -Wextra -Wpedantic) +endif() + +if(LIBHACK_WARNINGS_AS_ERRORS) + if(MSVC) + target_compile_options(hack PRIVATE /WX) + else() + target_compile_options(hack PRIVATE -Werror) + endif() +endif() + +if(WIN32) + message(STATUS "Configuring libhack for Windows") + target_link_libraries(hack PRIVATE psapi shlwapi) +elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(STATUS "Configuring libhack for Linux") + + find_package(Threads REQUIRED) + target_link_libraries(hack PRIVATE Threads::Threads) +else() + message(FATAL_ERROR "Unsupported platform: ${CMAKE_SYSTEM_NAME}") +endif() + +if(LIBHACK_ENABLE_COVERAGE) + if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(hack PRIVATE --coverage) + target_link_options(hack PRIVATE --coverage) + else() + message(FATAL_ERROR "LIBHACK_ENABLE_COVERAGE requires GCC or Clang") + endif() +endif() + +if(BUILD_TESTING) + add_executable(unit_test src/unit_test.c) + target_compile_features(unit_test PRIVATE c_std_17) + set_target_properties(unit_test PROPERTIES + C_EXTENSIONS OFF + C_STANDARD_REQUIRED ON + ) + target_link_libraries(unit_test PRIVATE libhack::hack) + target_include_directories(unit_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + + if(LIBHACK_ENABLE_COVERAGE) + target_compile_options(unit_test PRIVATE --coverage) + target_link_options(unit_test PRIVATE --coverage) + endif() + + add_test(NAME libhack.unit_test COMMAND unit_test) +endif() + +if(LIBHACK_BUILD_EXAMPLES) + add_subdirectory(src/examples) +endif() + +install(TARGETS hack + EXPORT libhackTargets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libhack +) + +install(FILES ${LIBHACK_HEADERS} + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libhack +) + +install(EXPORT libhackTargets + FILE libhackTargets.cmake + NAMESPACE libhack:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/libhack +) diff --git a/README.md b/README.md index 9891f57..442f202 100644 --- a/README.md +++ b/README.md @@ -108,65 +108,59 @@ To get a local copy up and running follow these simple steps. This is an example of how to list things you need to use the software and how to install them. -* MinGW (Msys2) - - Download and install MinGW - - https://www.msys2.org/wiki/MSYS2-installation/ - -* CMake - - https://cmake.org/download/ - -### Building +* GCC (Linux) +* MinGW (Windows) + - Download and install MinGW through MSYS2 + - https://www.msys2.org/wiki/MSYS2-installation/ + +* CMake + - https://cmake.org/download/ + +### Building
-1. Clone the libhack -```sh -git clone https://github.com/lucas-engen/libhack.git -``` +1. Clone the libhack +```sh +git clone https://github.com/lucas-engen/libhack.git +``` 2. Go to project folder ```sh cd libhack ``` -3. Generate Makefiles -```sh -cmake -G -B build . -``` - -* Note: type `cmake --help` to list generators available in your system - -4. Go to build directory -```sh -cd build -``` - -5. Build source code -```sh -make -``` +3. Configure the project +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release +``` + +4. Build the library +```sh +cmake --build build --parallel +``` + +5. Run the tests +```sh +cmake --build build --target test +``` + +To install the library and headers locally, run: +```sh +cmake --install build --prefix "$HOME/.local" +``` ### Building examples
-1. Go to examples folder -```sh -cd src/examples -``` - -2. Generate makefiles -```sh -cmake -G -B build . -``` - -3. Go to build directory -```sh -cd build -``` - -4. Build examples -```sh -make -``` +1. Configure the project with examples enabled +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DLIBHACK_BUILD_EXAMPLES=ON +``` + +2. Build the examples +```sh +cmake --build build --parallel +```
@@ -201,8 +195,8 @@ In order to build the project **foo**, you just need to run gcc foo.c main.c -L. -lhack ``` -At this point the **foo** program will be statically linked to libhack, and will need **libhack.dll** or **libhack.so** to be opened -correcly. +At this point the **foo** program will be dynamically linked to libhack, and will need **libhack.dll** or **libhack.so** to be opened +correctly. _For more examples, please refer to examples below_ diff --git a/sonar-project.properties b/sonar-project.properties index d2d9c4b..999c4b7 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -8,5 +8,11 @@ sonar.projectVersion=0.3 # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. sonar.sources=src +# The test executable is kept under the same source root as the library. +# Keep it in test scope so it does not count as production code in the quality gate. +sonar.tests=src +sonar.test.inclusions=src/unit_test.c +sonar.exclusions=src/unit_test.c + # Encoding of the source code. Default is default system encoding -#sonar.sourceEncoding=UTF-8 \ No newline at end of file +#sonar.sourceEncoding=UTF-8 diff --git a/src/examples/CMakeLists.txt b/src/examples/CMakeLists.txt new file mode 100644 index 0000000..6a6c657 --- /dev/null +++ b/src/examples/CMakeLists.txt @@ -0,0 +1,5 @@ +if(WIN32) + add_subdirectory(windows) +elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_subdirectory(linux) +endif() diff --git a/src/examples/linux/CMakeLists.txt b/src/examples/linux/CMakeLists.txt index ff005d2..f619f4a 100644 --- a/src/examples/linux/CMakeLists.txt +++ b/src/examples/linux/CMakeLists.txt @@ -1,18 +1,5 @@ -cmake_minimum_required(VERSION 3.10) - -project(linux) - -# Executable settings add_executable(write_addr write_addr.c) -add_definitions(-DDEBUG) - -# Add link directories -link_directories(${CMAKE_SOURCE_DIR}) - -# Add link libraries -find_library(LIBHACK hack ${CMAKE_SOURCE_DIR}) -target_link_libraries(write_addr ${LIBHACK}) - -# Set language standard -set_property(TARGET write_addr PROPERTY C_STANDARD 17) +target_compile_features(write_addr PRIVATE c_std_17) +target_include_directories(write_addr PRIVATE ${PROJECT_SOURCE_DIR}/src) +target_link_libraries(write_addr PRIVATE libhack::hack) diff --git a/src/examples/linux/write_addr.c b/src/examples/linux/write_addr.c index 222c2c3..095ffbf 100644 --- a/src/examples/linux/write_addr.c +++ b/src/examples/linux/write_addr.c @@ -23,7 +23,7 @@ int main() { } printf("process id of %s: %d %d\n",lh->process_name, s, lh->pid); - printf("writing address %lx\n", addr); + printf("writing address %llx\n", addr); long status = libhack_write_int_to_addr64(lh, addr, 40000); if(status == LIBHACK_OK) { diff --git a/src/examples/windows/CMakeLists.txt b/src/examples/windows/CMakeLists.txt new file mode 100644 index 0000000..d6b35bc --- /dev/null +++ b/src/examples/windows/CMakeLists.txt @@ -0,0 +1,30 @@ +add_executable(pid pid.c) +add_executable(read_addr read_addr.c) +add_executable(write_addr write_addr.c) +add_executable(dll_inject dll_inject.c) +add_executable(version_info version_info.cpp) +add_executable(submodule_addr get_submodule_addr.c) +add_library(hello SHARED hello.c) + +set(LIBHACK_WINDOWS_EXAMPLES + pid + read_addr + write_addr + dll_inject + version_info + submodule_addr +) + +foreach(example IN LISTS LIBHACK_WINDOWS_EXAMPLES) + target_include_directories(${example} PRIVATE ${PROJECT_SOURCE_DIR}/src) + target_link_libraries(${example} PRIVATE libhack::hack) +endforeach() + +target_compile_features(pid PRIVATE c_std_11) +target_compile_features(read_addr PRIVATE c_std_11) +target_compile_features(write_addr PRIVATE c_std_11) +target_compile_features(dll_inject PRIVATE c_std_11) +target_compile_features(submodule_addr PRIVATE c_std_11) +target_compile_features(version_info PRIVATE cxx_std_11) + +target_link_libraries(hello PRIVATE user32) diff --git a/src/examples/windows/CMakelists.txt b/src/examples/windows/CMakelists.txt deleted file mode 100644 index be44728..0000000 --- a/src/examples/windows/CMakelists.txt +++ /dev/null @@ -1,33 +0,0 @@ -cmake_minimum_required(VERSION 3.10) - -project(examples) - -# Executable settings -add_executable(pid pid.c) -add_executable(read_addr read_addr.c) -add_executable(write_addr write_addr.c) -add_executable(dll_inject dll_inject.c) -add_executable(version_info version_info.cpp) -add_executable(submodule_addr get_submodule_addr.c) -add_library(hello SHARED hello.c) - -# Add link directories -link_directories(${CMAKE_SOURCE_DIR}) - -# Add link libraries -find_library(LIBHACK hack ${CMAKE_SOURCE_DIR}) -target_link_libraries(pid ${LIBHACK}) -target_link_libraries(read_addr ${LIBHACK}) -target_link_libraries(write_addr ${LIBHACK}) -target_link_libraries(dll_inject ${LIBHACK}) -target_link_libraries(version_info ${LIBHACK}) -target_link_libraries(submodule_addr ${LIBHACK}) - -# Set language standard -set_property(TARGET pid PROPERTY C_STANDARD 11) -set_property(TARGET read_addr PROPERTY C_STANDARD 11) -set_property(TARGET write_addr PROPERTY C_STANDARD 11) -set_property(TARGET dll_inject PROPERTY C_STANDARD 11) -set_property(TARGET version_info PROPERTY C_STANDARD 11) -set_property(TARGET submodule_addr PROPERTY C_STANDARD 11) - diff --git a/src/init.c b/src/init.c index a428eed..9093d9a 100644 --- a/src/init.c +++ b/src/init.c @@ -149,8 +149,9 @@ struct libhack_handle *libhack_init(const char *process_name) memset(lh->process_name, 0, sizeof(lh->process_name)); - // Copy process name to struct - strncpy(lh->process_name, process_name, MIN(strlen(process_name), arraySize(lh->process_name)) - 1); + // Copy process name to struct, always leaving room for the terminator. + strncpy(lh->process_name, process_name, sizeof(lh->process_name) - 1); + lh->process_name[sizeof(lh->process_name) - 1] = '\0'; // Initializes value for process ID lh->pid = -1; @@ -176,4 +177,4 @@ const char *libhack_getversion() return &version[0]; } -#endif \ No newline at end of file +#endif diff --git a/src/process.c b/src/process.c index a824798..ae7e842 100644 --- a/src/process.c +++ b/src/process.c @@ -9,9 +9,13 @@ * */ -#ifndef __MINGW__ -#include "mingw_aliases.h" -#endif +#ifdef __linux__ +#define _GNU_SOURCE +#endif + +#ifndef __MINGW__ +#include "mingw_aliases.h" +#endif #include "platform.h" #include "status_codes.h" @@ -24,18 +28,19 @@ #include #include -#elif defined(__linux__) -#define _GNU_SOURCE -#define __USE_GNU -#define __USE_POSIX -#include -#include -#include -#include -#include -#include -#include -#include +#elif defined(__linux__) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif @@ -329,18 +334,18 @@ DWORD64 libhack_get_base_addr64(struct libhack_handle *handle) libhack_debug("Module found: %s", moduleName); - // Compare module name - if (strnicmp(moduleName, handle->process_name, - strlen(handle->process_name)) == 0) - { - DWORD64 modAddr = modules[i]; - - // Free memory - free(modules); - - handle->hModule = modAddr; - return (DWORD64)modAddr; - } + // Compare module name + if (strnicmp(moduleName, handle->process_name, + strlen(handle->process_name)) == 0) + { + HMODULE modAddr = modules[i]; + + // Free memory + free(modules); + + handle->hModule = modAddr; + return (DWORD64)(ULONG_PTR)modAddr; + } } } else @@ -881,50 +886,88 @@ bool libhack_is64bit_process(struct libhack_handle *handle, DWORD *error) return !bWow64; } -#elif defined(__linux__) - -pid_t libhack_get_process_id(struct libhack_handle *handle) -{ - PROCTAB *proc = NULL; - proc_t proc_info; - - // Sanity check - libhack_assert_or_return(handle != NULL, -1); - - if (handle->pid == -1) - { - proc = openproc(PROC_FILLMEM | PROC_FILLSTAT | PROC_FILLSTATUS); - - if (!proc) - { - libhack_err("Failed to list processes: %d", errno); - return -1; - } - - // Allocates memory - memset(&proc_info, 0, sizeof(proc_info)); - - // Iterates through process list - libhack_notice("reading process list ..."); - - while (readproc(proc, &proc_info) != NULL) - { - if (strncmp(proc_info.cmd, handle->process_name, strlen(proc_info.cmd)) == - 0) - { - handle->pid = proc_info.tid; - libhack_notice("pid of %s: %hi", proc_info.cmd, handle->pid); - libhack_debug("start code, end code, start stack: %#lx, %#lx, %#lx", - proc_info.start_code, proc_info.end_code, - proc_info.start_stack); - break; - } - } - - libhack_notice("cleaning up resources"); - - closeproc(proc); - } +#elif defined(__linux__) + +static bool libhack_read_process_name(const char *pid_name, + char *process_name, + size_t process_name_size) +{ + char comm_path[BUFLEN]; + ssize_t bytes_read; + int comm_fd; + + if (!pid_name || !process_name || process_name_size < 2) + return false; + + if (snprintf(comm_path, sizeof(comm_path), "/proc/%s/comm", pid_name) < 0) + return false; + + comm_fd = open(comm_path, O_RDONLY | O_CLOEXEC); + if (comm_fd == -1) + return false; + + bytes_read = read(comm_fd, process_name, process_name_size - 1); + close(comm_fd); + + if (bytes_read <= 0) + return false; + + process_name[bytes_read] = '\0'; + process_name[strcspn(process_name, "\r\n")] = '\0'; + + return process_name[0] != '\0'; +} + +pid_t libhack_get_process_id(struct libhack_handle *handle) +{ + DIR *proc_dir; + struct dirent *entry; + char process_name[BUFLEN]; + + // Sanity check + libhack_assert_or_return(handle != NULL, -1); + + if (handle->pid == -1) + { + proc_dir = opendir("/proc"); + if (!proc_dir) + { + libhack_err("Failed to list processes: %d", errno); + return -1; + } + + // Iterates through process list + libhack_notice("reading process list ..."); + + while ((entry = readdir(proc_dir)) != NULL) + { + char *pid_end; + long pid_value; + + if (!isdigit((unsigned char)entry->d_name[0])) + continue; + + errno = 0; + pid_end = NULL; + pid_value = strtol(entry->d_name, &pid_end, 10); + if (errno != 0 || pid_end == entry->d_name || *pid_end != '\0' || + pid_value <= 0 || pid_value > INT_MAX) + continue; + + if (libhack_read_process_name(entry->d_name, process_name, + sizeof(process_name)) && + strcmp(process_name, handle->process_name) == 0) + { + handle->pid = (pid_t)pid_value; + libhack_notice("pid of %s: %d", process_name, (int)handle->pid); + break; + } + } + + libhack_notice("cleaning up resources"); + + closedir(proc_dir); + } return handle->pid; } @@ -1046,7 +1089,7 @@ long libhack_read_int_from_addr64(const struct libhack_handle *handle, local.iov_base = value; local.iov_len = sizeof(int); - remote.iov_base = &addr; + remote.iov_base = (void *)(uintptr_t)addr; remote.iov_len = sizeof(int); ssize_t readed = process_vm_readv(handle->pid, &local, 1, &remote, 1, 0); @@ -1077,7 +1120,7 @@ long libhack_write_int_to_addr64(const struct libhack_handle *handle, local.iov_base = &value; local.iov_len = sizeof(value); - remote.iov_base = &addr; + remote.iov_base = (void *)(uintptr_t)addr; remote.iov_len = sizeof(value); libhack_notice("writing address %lx on %d", addr, handle->pid); @@ -1137,9 +1180,9 @@ int libhack_write_string_to_addr64(const struct libhack_handle *handle, // Sanity check libhack_assert_or_return(handle != NULL, -1); - local.iov_base = &string; + local.iov_base = (void *)string; local.iov_len = string_len; - remote.iov_base = &addr; + remote.iov_base = (void *)(uintptr_t)addr; remote.iov_len = string_len; libhack_notice("writing address %lx on %d", addr, handle->pid); @@ -1164,7 +1207,7 @@ __int64_t libhack_read_int64_from_addr64(const struct libhack_handle *handle, local.iov_base = &local_value; local.iov_len = sizeof(__int64_t); - remote.iov_base = &addr; + remote.iov_base = (void *)(uintptr_t)addr; remote.iov_len = sizeof(__int64_t); if (process_vm_readv(handle->pid, &local, 1, &remote, 1, 0) != diff --git a/src/status_codes.c b/src/status_codes.c index 7bb773f..16e3639 100644 --- a/src/status_codes.c +++ b/src/status_codes.c @@ -4,64 +4,36 @@ #ifdef __linux__ #include -#include -#elif __windows__ -#include #endif -#ifdef __linux__ -static pthread_mutex_t mux; -static pthread_once_t pot = PTHREAD_ONCE_INIT; -#endif - -int32_t last_error = LIBHACK_OK; +static int32_t last_error = LIBHACK_OK; -static void init_mux() { #ifdef __linux__ - if(pthread_mutex_init(&mux, NULL) != 0) { - libhack_err("get last error and set last error should not be used in multiple threads"); - return; - } -#elif __windows__ - +static pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER; #endif -} -static void initialize_error_system() { -#ifdef __linux__ - pthread_once(pot, init_mux); -#elif __windows - -#endif -} - -__int32_t libhack_get_last_error() +int32_t libhack_get_last_error(void) { int32_t err; - initialize_error_system(); - #ifdef __linux__ pthread_mutex_lock(&mux); err = last_error; pthread_mutex_unlock(&mux); -#elif __windows__ - +#else + err = last_error; #endif return err; } -void libhack_set_last_error(__int32_t err) +void libhack_set_last_error(int32_t err) { - initialize_error_system(); - #ifdef __linux__ pthread_mutex_lock(&mux); last_error = err; pthread_mutex_unlock(&mux); -#elif __windows__ - +#else + last_error = err; #endif } - diff --git a/src/status_codes.h b/src/status_codes.h index 03359d9..b74fe30 100644 --- a/src/status_codes.h +++ b/src/status_codes.h @@ -2,21 +2,24 @@ #define LIBHACK_STATUS_CODES_H #include "platform.h" - -#ifdef __windows__ #include -#elif __linux__ + +#ifdef __linux__ #include #endif #define LIBHACK_OK 0 -#ifdef __windows__ -typedef int32_t __int32_t; +#ifndef LIBHACK_API +#if defined(__windows__) && defined(DLL_EXPORT) +#define LIBHACK_API __declspec(dllexport) +#else +#define LIBHACK_API +#endif #endif -__int32_t libhack_get_last_error(); -void libhack_set_last_error(__int32_t err); +LIBHACK_API int32_t libhack_get_last_error(void); +LIBHACK_API void libhack_set_last_error(int32_t err); #endif diff --git a/src/unit_test.c b/src/unit_test.c index 88cd063..a8c2707 100644 --- a/src/unit_test.c +++ b/src/unit_test.c @@ -1,16 +1,223 @@ +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ +#include +#endif + #include "init.h" +#include "process.h" +#include "status_codes.h" +#include "types.h" + +static unsigned tests_run; +static unsigned tests_failed; + +#define EXPECT(condition) \ + do \ + { \ + tests_run++; \ + if (!(condition)) \ + { \ + fprintf(stderr, "FAIL: %s:%d: %s\n", __FILE__, __LINE__, \ + #condition); \ + tests_failed++; \ + } \ + } while (0) + +static void test_status_codes(void) +{ + EXPECT(libhack_get_last_error() == LIBHACK_OK); + + libhack_set_last_error(42); + EXPECT(libhack_get_last_error() == 42); + + libhack_set_last_error(-7); + EXPECT(libhack_get_last_error() == -7); + + libhack_set_last_error(LIBHACK_OK); +} + +static void test_string_lowercase(void) +{ +#ifndef __windows__ + char text[] = "LiBhAcK 123!"; + + EXPECT(strcmp(strlwr(text), "libhack 123!") == 0); + EXPECT(strlwr(text) == text); +#endif +} -int main() +static void test_initialization(void) { - struct libhack_handle *lh = libhack_init("test.exe"); + struct libhack_handle *handle; + + EXPECT(libhack_init(NULL) == NULL); + + handle = libhack_init("example-process"); + EXPECT(handle != NULL); + + if (handle == NULL) + return; + +#ifdef __linux__ + EXPECT(strcmp(handle->process_name, "example-process") == 0); + EXPECT(handle->pid == -1); + EXPECT(handle->base_addr == -1); +#else + EXPECT(strcmp(handle->process_name, "example-process") == 0); + EXPECT(handle->pid == 0); + EXPECT(handle->bProcessIsOpen == FALSE); +#endif + + libhack_free(handle); + libhack_free(NULL); +} + +static void test_version(void) +{ + const char *version = libhack_getversion(); + + EXPECT(version != NULL); + EXPECT(version[0] != '\0'); + EXPECT(strstr(version, "build") != NULL); +} + +#ifdef __linux__ +static bool read_current_process_name(char *name, size_t name_size) +{ + FILE *comm_file; + + if (name == NULL || name_size < 2) + return false; + + comm_file = fopen("/proc/self/comm", "r"); + if (comm_file == NULL) + return false; - if(lh == NULL) { - printf("libhack init failed\n"); - return 1; + if (fgets(name, (int)name_size, comm_file) == NULL) + { + fclose(comm_file); + return false; } - printf("test passed\n"); + fclose(comm_file); + name[strcspn(name, "\r\n")] = '\0'; + return name[0] != '\0'; +} + +static void test_process_lookup_and_state(void) +{ + char process_name[BUFLEN] = {0}; + struct libhack_handle *handle; + pid_t pid; + + EXPECT(read_current_process_name(process_name, sizeof(process_name))); + if (process_name[0] == '\0') + return; + + handle = libhack_init(process_name); + EXPECT(handle != NULL); + if (handle == NULL) + return; + + EXPECT(libhack_get_process_id(NULL) == -1); + pid = libhack_get_process_id(handle); + EXPECT(pid == getpid()); + EXPECT(handle->pid == getpid()); + EXPECT(libhack_get_process_id(handle) == getpid()); + EXPECT(libhack_process_is_running(handle)); + + libhack_free(handle); +} + +static void test_process_memory(void) +{ + char process_name[BUFLEN] = {0}; + char target_string[32] = "before"; + const char replacement[] = "after"; + int target_int = 1234; + int read_int = 0; + int64_t target_int64 = INT64_C(0x1020304050607080); + struct libhack_handle *handle; + long base_address; + long read_result; + + EXPECT(read_current_process_name(process_name, sizeof(process_name))); + if (process_name[0] == '\0') + return; + + handle = libhack_init(process_name); + EXPECT(handle != NULL); + if (handle == NULL) + return; + + EXPECT(libhack_read_int_from_addr64(NULL, 0, &read_int) == -1); + EXPECT(libhack_read_int_from_addr64(handle, 0, NULL) == -1); + EXPECT(libhack_write_int_to_addr64(NULL, 0, 1) == -1); + EXPECT(libhack_write_string_to_addr64(NULL, 0, replacement, + sizeof(replacement)) == -1); + EXPECT(libhack_read_int64_from_addr64(NULL, 0) == -1); + EXPECT(libhack_get_process_id(handle) == getpid()); + + read_result = libhack_read_int_from_addr64( + handle, (DWORD64)(uintptr_t)&target_int, &read_int); + if (read_result == EPERM || read_result == EACCES || read_result == ENOSYS) + { + printf("Operações process_vm_readv/process_vm_writev ignoradas: %s.\n", + strerror((int)read_result)); + libhack_free(handle); + return; + } + + EXPECT(read_result == LIBHACK_OK); + EXPECT(read_int == target_int); + + base_address = libhack_get_base_addr(handle); + EXPECT(base_address > 0); + EXPECT(handle->base_addr == base_address); + EXPECT(libhack_get_base_addr64(handle) == base_address); + + EXPECT(libhack_write_int_to_addr64( + handle, (DWORD64)(uintptr_t)&target_int, 5678) == + LIBHACK_OK); + EXPECT(target_int == 5678); + + EXPECT(libhack_write_string_to_addr64( + handle, (DWORD64)(uintptr_t)target_string, replacement, + sizeof(replacement)) == LIBHACK_OK); + EXPECT(strcmp(target_string, replacement) == 0); + + EXPECT(libhack_read_int64_from_addr64( + handle, (DWORD64)(uintptr_t)&target_int64) == target_int64); + + libhack_free(handle); +} +#endif + +int main(void) +{ + test_status_codes(); + test_string_lowercase(); + test_initialization(); + test_version(); + +#ifdef __linux__ + test_process_lookup_and_state(); + test_process_memory(); +#endif + + if (tests_failed != 0) + { + fprintf(stderr, "%u de %u verificações falharam.\n", tests_failed, + tests_run); + return EXIT_FAILURE; + } - libhack_free(lh); - return 0; + printf("%u verificações passaram.\n", tests_run); + return EXIT_SUCCESS; }