mirror of
https://github.com/orange-cpp/omath.git
synced 2026-04-19 12:03:26 +00:00
Compare commits
3 Commits
29f3e2565d
...
feature/ph
| Author | SHA1 | Date | |
|---|---|---|---|
| 69e9735063 | |||
| 35b8510cf4 | |||
| ba662e44e2 |
@@ -34,6 +34,8 @@ option(OMATH_ENABLE_FORCE_INLINE
|
||||
|
||||
option(OMATH_ENABLE_LUA
|
||||
"omath bindings for lua" OFF)
|
||||
option(OMATH_ENABLE_PHYSX
|
||||
"PhysX-backed collider implementations" OFF)
|
||||
if(VCPKG_MANIFEST_FEATURES)
|
||||
foreach(omath_feature IN LISTS VCPKG_MANIFEST_FEATURES)
|
||||
if(omath_feature STREQUAL "imgui")
|
||||
@@ -48,6 +50,8 @@ if(VCPKG_MANIFEST_FEATURES)
|
||||
set(OMATH_BUILD_EXAMPLES ON)
|
||||
elseif(omath_feature STREQUAL "lua")
|
||||
set(OMATH_ENABLE_LUA ON)
|
||||
elseif(omath_feature STREQUAL "physx")
|
||||
set(OMATH_ENABLE_PHYSX ON)
|
||||
endif()
|
||||
|
||||
endforeach()
|
||||
@@ -78,6 +82,7 @@ if(${PROJECT_IS_TOP_LEVEL})
|
||||
message(STATUS "[${PROJECT_NAME}]: Coverage feature status ${OMATH_ENABLE_COVERAGE}")
|
||||
message(STATUS "[${PROJECT_NAME}]: Valgrind feature status ${OMATH_ENABLE_VALGRIND}")
|
||||
message(STATUS "[${PROJECT_NAME}]: Lua feature status ${OMATH_ENABLE_LUA}")
|
||||
message(STATUS "[${PROJECT_NAME}]: PhysX feature status ${OMATH_ENABLE_PHYSX}")
|
||||
endif()
|
||||
|
||||
file(GLOB_RECURSE OMATH_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/source/*.cpp")
|
||||
@@ -100,6 +105,13 @@ if (OMATH_ENABLE_LUA)
|
||||
target_include_directories(${PROJECT_NAME} PRIVATE ${SOL2_INCLUDE_DIRS})
|
||||
endif ()
|
||||
|
||||
if (OMATH_ENABLE_PHYSX)
|
||||
target_compile_definitions(${PROJECT_NAME} PUBLIC OMATH_ENABLE_PHYSX)
|
||||
|
||||
find_package(unofficial-omniverse-physx-sdk CONFIG REQUIRED)
|
||||
target_link_libraries(${PROJECT_NAME} PUBLIC unofficial::omniverse-physx-sdk::sdk)
|
||||
endif ()
|
||||
|
||||
add_library(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
|
||||
|
||||
target_compile_definitions(${PROJECT_NAME} PUBLIC OMATH_VERSION="${PROJECT_VERSION}")
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
"hidden": true,
|
||||
"inherits": ["linux-base", "vcpkg-base"],
|
||||
"cacheVariables": {
|
||||
"VCPKG_MANIFEST_FEATURES": "tests;imgui;avx2;lua"
|
||||
"VCPKG_MANIFEST_FEATURES": "tests;imgui;avx2;lua;physx"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
59
include/omath/collision/physx_box_collider.hpp
Normal file
59
include/omath/collision/physx_box_collider.hpp
Normal file
@@ -0,0 +1,59 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include "collider_interface.hpp"
|
||||
#include <PxPhysicsAPI.h>
|
||||
|
||||
namespace omath::collision
|
||||
{
|
||||
/// Axis-aligned box collider backed by PhysX PxBoxGeometry.
|
||||
/// Half-extents are stored in PhysX convention (positive values along each axis).
|
||||
class PhysXBoxCollider final : public ColliderInterface<Vector3<float>>
|
||||
{
|
||||
public:
|
||||
/// @param half_extents Half-widths along X, Y and Z axes (all must be > 0).
|
||||
/// @param origin World-space centre of the box.
|
||||
explicit PhysXBoxCollider(const VectorType& half_extents, const VectorType& origin = {})
|
||||
: m_geometry(physx::PxVec3(half_extents.x, half_extents.y, half_extents.z))
|
||||
, m_origin(origin)
|
||||
{
|
||||
}
|
||||
|
||||
/// Support function: returns the world-space point on the box furthest in @p direction.
|
||||
/// For a box, the furthest point along d is origin + (sign(d.x)*hx, sign(d.y)*hy, sign(d.z)*hz).
|
||||
[[nodiscard]]
|
||||
VectorType find_abs_furthest_vertex_position(const VectorType& direction) const override
|
||||
{
|
||||
const auto& he = m_geometry.halfExtents;
|
||||
return {
|
||||
m_origin.x + (direction.x >= 0.f ? he.x : -he.x),
|
||||
m_origin.y + (direction.y >= 0.f ? he.y : -he.y),
|
||||
m_origin.z + (direction.z >= 0.f ? he.z : -he.z),
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const VectorType& get_origin() const override { return m_origin; }
|
||||
|
||||
void set_origin(const VectorType& new_origin) override { m_origin = new_origin; }
|
||||
|
||||
[[nodiscard]]
|
||||
const physx::PxBoxGeometry& get_geometry() const { return m_geometry; }
|
||||
|
||||
/// Update half-extents at runtime.
|
||||
void set_half_extents(const VectorType& half_extents)
|
||||
{
|
||||
m_geometry = physx::PxBoxGeometry(physx::PxVec3(half_extents.x, half_extents.y, half_extents.z));
|
||||
}
|
||||
|
||||
private:
|
||||
physx::PxBoxGeometry m_geometry;
|
||||
VectorType m_origin;
|
||||
};
|
||||
} // namespace omath::collision
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
137
include/omath/collision/physx_rigid_body.hpp
Normal file
137
include/omath/collision/physx_rigid_body.hpp
Normal file
@@ -0,0 +1,137 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include "collider_interface.hpp"
|
||||
#include "physx_world.hpp"
|
||||
#include <PxPhysicsAPI.h>
|
||||
#include <extensions/PxRigidBodyExt.h>
|
||||
#include <cmath>
|
||||
|
||||
namespace omath::collision
|
||||
{
|
||||
/// Dynamic rigid body backed by a PhysX PxRigidDynamic actor.
|
||||
/// Implements ColliderInterface so it can participate in both omath GJK
|
||||
/// and PhysX simulation-based collision resolution.
|
||||
///
|
||||
/// Ownership: the actor is added to the world's scene on construction
|
||||
/// and removed + released on destruction.
|
||||
class PhysXRigidBody final : public ColliderInterface<Vector3<float>>
|
||||
{
|
||||
public:
|
||||
/// @param world PhysXWorld that owns the scene.
|
||||
/// @param geometry Shape geometry (PxBoxGeometry, PxSphereGeometry, …).
|
||||
/// @param origin Initial world-space position.
|
||||
/// @param density Mass density used to compute mass and inertia.
|
||||
PhysXRigidBody(PhysXWorld& world, const physx::PxGeometry& geometry,
|
||||
const VectorType& origin = {}, float density = 1.f)
|
||||
: m_world(world)
|
||||
, m_geometry(geometry)
|
||||
{
|
||||
const physx::PxTransform pose(physx::PxVec3(origin.x, origin.y, origin.z));
|
||||
m_actor = world.get_physics().createRigidDynamic(pose);
|
||||
|
||||
physx::PxShape* shape = world.get_physics().createShape(
|
||||
geometry, world.get_default_material(), true);
|
||||
m_actor->attachShape(*shape);
|
||||
shape->release();
|
||||
|
||||
physx::PxRigidBodyExt::updateMassAndInertia(*m_actor, density);
|
||||
world.get_scene().addActor(*m_actor);
|
||||
}
|
||||
|
||||
~PhysXRigidBody() override
|
||||
{
|
||||
m_world.get_scene().removeActor(*m_actor);
|
||||
m_actor->release();
|
||||
}
|
||||
|
||||
PhysXRigidBody(const PhysXRigidBody&) = delete;
|
||||
PhysXRigidBody& operator=(const PhysXRigidBody&) = delete;
|
||||
|
||||
// ── ColliderInterface ────────────────────────────────────────────────
|
||||
|
||||
/// Support function — delegates to the stored geometry type so the body
|
||||
/// can be used with omath GJK alongside the non-simulated colliders.
|
||||
[[nodiscard]]
|
||||
VectorType find_abs_furthest_vertex_position(const VectorType& direction) const override
|
||||
{
|
||||
const VectorType o = get_origin();
|
||||
switch (m_geometry.getType())
|
||||
{
|
||||
case physx::PxGeometryType::eBOX:
|
||||
{
|
||||
const auto& he = m_geometry.box().halfExtents;
|
||||
return {
|
||||
o.x + (direction.x >= 0.f ? he.x : -he.x),
|
||||
o.y + (direction.y >= 0.f ? he.y : -he.y),
|
||||
o.z + (direction.z >= 0.f ? he.z : -he.z),
|
||||
};
|
||||
}
|
||||
case physx::PxGeometryType::eSPHERE:
|
||||
{
|
||||
const float r = m_geometry.sphere().radius;
|
||||
const float len = std::sqrt(direction.x * direction.x +
|
||||
direction.y * direction.y +
|
||||
direction.z * direction.z);
|
||||
if (len == 0.f)
|
||||
return o;
|
||||
const float inv = r / len;
|
||||
return { o.x + direction.x * inv,
|
||||
o.y + direction.y * inv,
|
||||
o.z + direction.z * inv };
|
||||
}
|
||||
default:
|
||||
return o; // unsupported geometry — return centre
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const VectorType& get_origin() const override
|
||||
{
|
||||
const auto& p = m_actor->getGlobalPose().p;
|
||||
m_cached_origin = { p.x, p.y, p.z };
|
||||
return m_cached_origin;
|
||||
}
|
||||
|
||||
void set_origin(const VectorType& new_origin) override
|
||||
{
|
||||
physx::PxTransform pose = m_actor->getGlobalPose();
|
||||
pose.p = physx::PxVec3(new_origin.x, new_origin.y, new_origin.z);
|
||||
m_actor->setGlobalPose(pose);
|
||||
}
|
||||
|
||||
// ── PhysX-specific API ───────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] physx::PxRigidDynamic& get_actor() { return *m_actor; }
|
||||
[[nodiscard]] const physx::PxRigidDynamic& get_actor() const { return *m_actor; }
|
||||
|
||||
void set_linear_velocity(const VectorType& v)
|
||||
{
|
||||
m_actor->setLinearVelocity(physx::PxVec3(v.x, v.y, v.z));
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
VectorType get_linear_velocity() const
|
||||
{
|
||||
const auto& v = m_actor->getLinearVelocity();
|
||||
return { v.x, v.y, v.z };
|
||||
}
|
||||
|
||||
void set_kinematic(bool enabled)
|
||||
{
|
||||
m_actor->setRigidBodyFlag(physx::PxRigidBodyFlag::eKINEMATIC, enabled);
|
||||
}
|
||||
|
||||
private:
|
||||
PhysXWorld& m_world;
|
||||
physx::PxGeometryHolder m_geometry;
|
||||
physx::PxRigidDynamic* m_actor{nullptr};
|
||||
mutable VectorType m_cached_origin{};
|
||||
};
|
||||
} // namespace omath::collision
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
64
include/omath/collision/physx_sphere_collider.hpp
Normal file
64
include/omath/collision/physx_sphere_collider.hpp
Normal file
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include "collider_interface.hpp"
|
||||
#include <PxPhysicsAPI.h>
|
||||
#include <cmath>
|
||||
|
||||
namespace omath::collision
|
||||
{
|
||||
/// Sphere collider backed by PhysX PxSphereGeometry.
|
||||
class PhysXSphereCollider final : public ColliderInterface<Vector3<float>>
|
||||
{
|
||||
public:
|
||||
/// @param radius Sphere radius (must be > 0).
|
||||
/// @param origin World-space centre of the sphere.
|
||||
explicit PhysXSphereCollider(float radius, const VectorType& origin = {})
|
||||
: m_geometry(radius)
|
||||
, m_origin(origin)
|
||||
{
|
||||
}
|
||||
|
||||
/// Support function: returns the world-space point on the sphere furthest in @p direction.
|
||||
/// For a sphere that is simply origin + normalize(direction) * radius.
|
||||
[[nodiscard]]
|
||||
VectorType find_abs_furthest_vertex_position(const VectorType& direction) const override
|
||||
{
|
||||
const float len = std::sqrt(direction.x * direction.x +
|
||||
direction.y * direction.y +
|
||||
direction.z * direction.z);
|
||||
if (len == 0.f)
|
||||
return m_origin;
|
||||
|
||||
const float inv = m_geometry.radius / len;
|
||||
return {
|
||||
m_origin.x + direction.x * inv,
|
||||
m_origin.y + direction.y * inv,
|
||||
m_origin.z + direction.z * inv,
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const VectorType& get_origin() const override { return m_origin; }
|
||||
|
||||
void set_origin(const VectorType& new_origin) override { m_origin = new_origin; }
|
||||
|
||||
[[nodiscard]]
|
||||
const physx::PxSphereGeometry& get_geometry() const { return m_geometry; }
|
||||
|
||||
[[nodiscard]]
|
||||
float get_radius() const { return m_geometry.radius; }
|
||||
|
||||
void set_radius(float radius) { m_geometry = physx::PxSphereGeometry(radius); }
|
||||
|
||||
private:
|
||||
physx::PxSphereGeometry m_geometry;
|
||||
VectorType m_origin;
|
||||
};
|
||||
} // namespace omath::collision
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
82
include/omath/collision/physx_world.hpp
Normal file
82
include/omath/collision/physx_world.hpp
Normal file
@@ -0,0 +1,82 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include <PxPhysicsAPI.h>
|
||||
|
||||
namespace omath::collision
|
||||
{
|
||||
/// RAII owner of a PhysX Foundation + Physics + Scene.
|
||||
/// One world per simulation context; not copyable or movable.
|
||||
class PhysXWorld final
|
||||
{
|
||||
public:
|
||||
explicit PhysXWorld(physx::PxVec3 gravity = {0.f, -9.81f, 0.f},
|
||||
physx::PxU32 cpu_threads = 2)
|
||||
{
|
||||
m_foundation = PxCreateFoundation(PX_PHYSICS_VERSION, m_allocator, m_error_callback);
|
||||
|
||||
m_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *m_foundation,
|
||||
physx::PxTolerancesScale{});
|
||||
|
||||
physx::PxSceneDesc desc(m_physics->getTolerancesScale());
|
||||
desc.gravity = gravity;
|
||||
desc.cpuDispatcher = physx::PxDefaultCpuDispatcherCreate(cpu_threads);
|
||||
m_dispatcher = static_cast<physx::PxDefaultCpuDispatcher*>(desc.cpuDispatcher);
|
||||
desc.filterShader = physx::PxDefaultSimulationFilterShader;
|
||||
|
||||
m_scene = m_physics->createScene(desc);
|
||||
|
||||
// Default material: static friction 0.5, dynamic friction 0.5, restitution 0.
|
||||
m_default_material = m_physics->createMaterial(0.5f, 0.5f, 0.f);
|
||||
}
|
||||
|
||||
~PhysXWorld()
|
||||
{
|
||||
m_scene->release();
|
||||
m_dispatcher->release();
|
||||
m_default_material->release();
|
||||
m_physics->release();
|
||||
m_foundation->release();
|
||||
}
|
||||
|
||||
PhysXWorld(const PhysXWorld&) = delete;
|
||||
PhysXWorld& operator=(const PhysXWorld&) = delete;
|
||||
|
||||
/// Advance the simulation by @p dt seconds and block until results are ready.
|
||||
void step(float dt)
|
||||
{
|
||||
m_scene->simulate(dt);
|
||||
m_scene->fetchResults(true);
|
||||
}
|
||||
|
||||
[[nodiscard]] physx::PxPhysics& get_physics() { return *m_physics; }
|
||||
[[nodiscard]] physx::PxScene& get_scene() { return *m_scene; }
|
||||
[[nodiscard]] physx::PxMaterial& get_default_material() { return *m_default_material; }
|
||||
|
||||
/// Add an infinite static ground plane at y = @p y_level facing +Y.
|
||||
physx::PxRigidStatic* add_ground_plane(float y_level = 0.f)
|
||||
{
|
||||
physx::PxRigidStatic* plane = PxCreatePlane(
|
||||
*m_physics,
|
||||
physx::PxPlane(0.f, 1.f, 0.f, -y_level),
|
||||
*m_default_material);
|
||||
m_scene->addActor(*plane);
|
||||
return plane;
|
||||
}
|
||||
|
||||
private:
|
||||
physx::PxDefaultAllocator m_allocator{};
|
||||
physx::PxDefaultErrorCallback m_error_callback{};
|
||||
physx::PxFoundation* m_foundation{nullptr};
|
||||
physx::PxPhysics* m_physics{nullptr};
|
||||
physx::PxDefaultCpuDispatcher* m_dispatcher{nullptr};
|
||||
physx::PxScene* m_scene{nullptr};
|
||||
physx::PxMaterial* m_default_material{nullptr};
|
||||
};
|
||||
} // namespace omath::collision
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
@@ -4,7 +4,7 @@ project(unit_tests)
|
||||
|
||||
include(GoogleTest)
|
||||
|
||||
file(GLOB_RECURSE UNIT_TESTS_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/general/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/engines/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/*.hpp")
|
||||
file(GLOB_RECURSE UNIT_TESTS_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/general/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/engines/*.cpp")
|
||||
add_executable(${PROJECT_NAME} ${UNIT_TESTS_SOURCES} main.cpp)
|
||||
|
||||
set_target_properties(
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
#pragma once
|
||||
// Cross-platform helper for creating binary test "files" without writing to disk where possible.
|
||||
//
|
||||
// Strategy:
|
||||
// - Linux (non-Android, or Android API >= 30): memfd_create → /proc/self/fd/<N> (no disk I/O)
|
||||
// - All other platforms: anonymous temp file via std::tmpfile(), accessed via /proc/self/fd/<N>
|
||||
// on Linux, or a named temp file (cleaned up on destruction) elsewhere.
|
||||
//
|
||||
// Usage:
|
||||
// auto f = MemFdFile::create(myVector);
|
||||
// ASSERT_TRUE(f.valid());
|
||||
// scanner.scan_for_pattern_in_file(f.path(), ...);
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#if defined(__linux__)
|
||||
# include <unistd.h>
|
||||
# include <fcntl.h>
|
||||
# if defined(__ANDROID__)
|
||||
# if __ANDROID_API__ >= 30
|
||||
# include <sys/mman.h>
|
||||
# define OMATH_TEST_USE_MEMFD 1
|
||||
# endif
|
||||
// Android < 30: fall through to tmpfile() path below
|
||||
# else
|
||||
// Desktop Linux: memfd_create available since glibc 2.27 / kernel 3.17
|
||||
# include <sys/mman.h>
|
||||
# define OMATH_TEST_USE_MEMFD 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
class MemFdFile
|
||||
{
|
||||
public:
|
||||
MemFdFile() = default;
|
||||
|
||||
~MemFdFile()
|
||||
{
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
if (m_fd >= 0)
|
||||
::close(m_fd);
|
||||
#else
|
||||
if (!m_temp_path.empty())
|
||||
std::filesystem::remove(m_temp_path);
|
||||
#endif
|
||||
}
|
||||
|
||||
MemFdFile(const MemFdFile&) = delete;
|
||||
MemFdFile& operator=(const MemFdFile&) = delete;
|
||||
|
||||
MemFdFile(MemFdFile&& o) noexcept
|
||||
: m_path(std::move(o.m_path))
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
, m_fd(o.m_fd)
|
||||
#else
|
||||
, m_temp_path(std::move(o.m_temp_path))
|
||||
#endif
|
||||
{
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
o.m_fd = -1;
|
||||
#else
|
||||
o.m_temp_path.clear();
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid() const { return !m_path.empty(); }
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const { return m_path; }
|
||||
|
||||
static MemFdFile create(const std::vector<std::uint8_t>& data)
|
||||
{
|
||||
return create(data.data(), data.size());
|
||||
}
|
||||
|
||||
static MemFdFile create(const std::uint8_t* data, std::size_t size)
|
||||
{
|
||||
MemFdFile f;
|
||||
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
f.m_fd = static_cast<int>(::memfd_create("test_bin", 0));
|
||||
if (f.m_fd < 0)
|
||||
return f;
|
||||
|
||||
if (!write_all(f.m_fd, data, size))
|
||||
{
|
||||
::close(f.m_fd);
|
||||
f.m_fd = -1;
|
||||
return f;
|
||||
}
|
||||
f.m_path = "/proc/self/fd/" + std::to_string(f.m_fd);
|
||||
|
||||
#else
|
||||
// Portable fallback: write to a uniquely-named temp file and delete on destruction
|
||||
const auto tmp_dir = std::filesystem::temp_directory_path();
|
||||
std::mt19937_64 rng(std::random_device{}());
|
||||
const auto unique_name = "omath_test_" + std::to_string(rng()) + ".bin";
|
||||
f.m_temp_path = (tmp_dir / unique_name).string();
|
||||
f.m_path = f.m_temp_path;
|
||||
|
||||
std::ofstream out(f.m_temp_path, std::ios::binary | std::ios::trunc);
|
||||
if (!out.is_open())
|
||||
{
|
||||
f.m_temp_path.clear();
|
||||
f.m_path.clear();
|
||||
return f;
|
||||
}
|
||||
out.write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size));
|
||||
if (!out)
|
||||
{
|
||||
out.close();
|
||||
std::filesystem::remove(f.m_temp_path);
|
||||
f.m_temp_path.clear();
|
||||
f.m_path.clear();
|
||||
}
|
||||
#endif
|
||||
return f;
|
||||
}
|
||||
|
||||
private:
|
||||
std::filesystem::path m_path;
|
||||
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
int m_fd = -1;
|
||||
|
||||
static bool write_all(int fd, const std::uint8_t* data, std::size_t size)
|
||||
{
|
||||
std::size_t written = 0;
|
||||
while (written < size)
|
||||
{
|
||||
const auto n = ::write(fd, data + written, size - written);
|
||||
if (n <= 0)
|
||||
return false;
|
||||
written += static_cast<std::size_t>(n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#else
|
||||
std::string m_temp_path;
|
||||
#endif
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Build a minimal PE binary in-memory with a single .text section.
|
||||
// Layout (all offsets compile-time):
|
||||
// 0x00: DOS header (64 B) 0x40: pad 0x80: NT sig 0x84: FileHeader (20 B)
|
||||
// 0x98: OptionalHeader (0xF0 B) 0x188: SectionHeader (44 B) 0x1B4: section data
|
||||
// ---------------------------------------------------------------------------
|
||||
inline std::vector<std::uint8_t> build_minimal_pe(const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
constexpr std::uint32_t e_lfanew = 0x80u;
|
||||
constexpr std::uint16_t size_opt = 0xF0u;
|
||||
constexpr std::size_t nt_off = e_lfanew;
|
||||
constexpr std::size_t fh_off = nt_off + 4;
|
||||
constexpr std::size_t oh_off = fh_off + 20;
|
||||
constexpr std::size_t sh_off = oh_off + size_opt;
|
||||
constexpr std::size_t data_off = sh_off + 44;
|
||||
|
||||
std::vector<std::uint8_t> buf(data_off + section_bytes.size(), 0u);
|
||||
|
||||
buf[0] = 'M'; buf[1] = 'Z';
|
||||
std::memcpy(buf.data() + 0x3Cu, &e_lfanew, 4);
|
||||
|
||||
buf[nt_off] = 'P'; buf[nt_off + 1] = 'E';
|
||||
|
||||
const std::uint16_t machine = 0x8664u, num_sections = 1u;
|
||||
std::memcpy(buf.data() + fh_off, &machine, 2);
|
||||
std::memcpy(buf.data() + fh_off + 2, &num_sections, 2);
|
||||
std::memcpy(buf.data() + fh_off + 16, &size_opt, 2);
|
||||
|
||||
const std::uint16_t magic = 0x20Bu;
|
||||
std::memcpy(buf.data() + oh_off, &magic, 2);
|
||||
|
||||
const char name[8] = {'.','t','e','x','t',0,0,0};
|
||||
std::memcpy(buf.data() + sh_off, name, 8);
|
||||
|
||||
const auto vsize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
const std::uint32_t vaddr = 0x1000u;
|
||||
const auto ptr_raw = static_cast<std::uint32_t>(data_off);
|
||||
std::memcpy(buf.data() + sh_off + 8, &vsize, 4);
|
||||
std::memcpy(buf.data() + sh_off + 12, &vaddr, 4);
|
||||
std::memcpy(buf.data() + sh_off + 16, &vsize, 4);
|
||||
std::memcpy(buf.data() + sh_off + 20, &ptr_raw, 4);
|
||||
|
||||
std::memcpy(buf.data() + data_off, section_bytes.data(), section_bytes.size());
|
||||
return buf;
|
||||
}
|
||||
@@ -6,8 +6,8 @@
|
||||
#include <omath/utility/macho_pattern_scan.hpp>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include "mem_fd_helper.hpp"
|
||||
|
||||
using namespace omath;
|
||||
|
||||
@@ -16,12 +16,11 @@ namespace
|
||||
// Mach-O magic numbers
|
||||
constexpr std::uint32_t mh_magic_64 = 0xFEEDFACF;
|
||||
constexpr std::uint32_t mh_magic_32 = 0xFEEDFACE;
|
||||
constexpr std::uint32_t lc_segment = 0x1;
|
||||
constexpr std::uint32_t lc_segment = 0x1;
|
||||
constexpr std::uint32_t lc_segment_64 = 0x19;
|
||||
|
||||
constexpr std::string_view segment_name = "__TEXT";
|
||||
constexpr std::string_view section_name = "__text";
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct MachHeader64
|
||||
{
|
||||
@@ -108,174 +107,249 @@ namespace
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
// Build a minimal 64-bit Mach-O binary in-memory with a __text section
|
||||
std::vector<std::uint8_t> build_minimal_macho64(const std::vector<std::uint8_t>& section_bytes)
|
||||
// Helper function to create a minimal 64-bit Mach-O file with a __text section
|
||||
bool write_minimal_macho64_file(const std::string& path, const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
constexpr std::size_t load_cmd_size = sizeof(SegmentCommand64) + sizeof(Section64);
|
||||
const std::size_t section_offset = sizeof(MachHeader64) + load_cmd_size;
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
|
||||
std::vector<std::uint8_t> buf(section_offset + section_bytes.size(), 0u);
|
||||
// Calculate sizes
|
||||
constexpr std::size_t header_size = sizeof(MachHeader64);
|
||||
constexpr std::size_t segment_size = sizeof(SegmentCommand64);
|
||||
constexpr std::size_t section_size = sizeof(Section64);
|
||||
constexpr std::size_t load_cmd_size = segment_size + section_size;
|
||||
// Section data will start after headers
|
||||
const std::size_t section_offset = header_size + load_cmd_size;
|
||||
|
||||
auto* header = reinterpret_cast<MachHeader64*>(buf.data());
|
||||
header->magic = mh_magic_64;
|
||||
header->cputype = 0x01000007; // CPU_TYPE_X86_64
|
||||
header->cpusubtype = 0x3;
|
||||
header->filetype = 0x2; // MH_EXECUTE
|
||||
header->ncmds = 1;
|
||||
header->sizeofcmds = static_cast<std::uint32_t>(load_cmd_size);
|
||||
// Create Mach-O header
|
||||
MachHeader64 header{};
|
||||
header.magic = mh_magic_64;
|
||||
header.cputype = 0x01000007; // CPU_TYPE_X86_64
|
||||
header.cpusubtype = 0x3; // CPU_SUBTYPE_X86_64_ALL
|
||||
header.filetype = 0x2; // MH_EXECUTE
|
||||
header.ncmds = 1;
|
||||
header.sizeofcmds = static_cast<std::uint32_t>(load_cmd_size);
|
||||
header.flags = 0;
|
||||
header.reserved = 0;
|
||||
|
||||
auto* segment = reinterpret_cast<SegmentCommand64*>(buf.data() + sizeof(MachHeader64));
|
||||
segment->cmd = lc_segment_64;
|
||||
segment->cmdsize = static_cast<std::uint32_t>(load_cmd_size);
|
||||
std::ranges::copy(segment_name, segment->segname);
|
||||
segment->vmaddr = 0x100000000;
|
||||
segment->vmsize = section_bytes.size();
|
||||
segment->fileoff = section_offset;
|
||||
segment->filesize = section_bytes.size();
|
||||
segment->maxprot = 7;
|
||||
segment->initprot = 5;
|
||||
segment->nsects = 1;
|
||||
f.write(reinterpret_cast<const char*>(&header), sizeof(header));
|
||||
|
||||
auto* section = reinterpret_cast<Section64*>(buf.data() + sizeof(MachHeader64) + sizeof(SegmentCommand64));
|
||||
std::ranges::copy(section_name, section->sectname);
|
||||
std::ranges::copy(segment_name, section->segname);
|
||||
section->addr = 0x100000000;
|
||||
section->size = section_bytes.size();
|
||||
section->offset = static_cast<std::uint32_t>(section_offset);
|
||||
// Create segment command
|
||||
SegmentCommand64 segment{};
|
||||
segment.cmd = lc_segment_64;
|
||||
segment.cmdsize = static_cast<std::uint32_t>(load_cmd_size);
|
||||
std::ranges::copy(segment_name, segment.segname);
|
||||
segment.vmaddr = 0x100000000;
|
||||
segment.vmsize = section_bytes.size();
|
||||
segment.fileoff = section_offset;
|
||||
segment.filesize = section_bytes.size();
|
||||
segment.maxprot = 7; // VM_PROT_ALL
|
||||
segment.initprot = 5; // VM_PROT_READ | VM_PROT_EXECUTE
|
||||
segment.nsects = 1;
|
||||
segment.flags = 0;
|
||||
|
||||
std::memcpy(buf.data() + section_offset, section_bytes.data(), section_bytes.size());
|
||||
return buf;
|
||||
f.write(reinterpret_cast<const char*>(&segment), sizeof(segment));
|
||||
|
||||
// Create section
|
||||
Section64 section{};
|
||||
std::ranges::copy(section_name, section.sectname);
|
||||
std::ranges::copy(segment_name, segment.segname);
|
||||
section.addr = 0x100000000;
|
||||
section.size = section_bytes.size();
|
||||
section.offset = static_cast<std::uint32_t>(section_offset);
|
||||
section.align = 0;
|
||||
section.reloff = 0;
|
||||
section.nreloc = 0;
|
||||
section.flags = 0;
|
||||
section.reserved1 = 0;
|
||||
section.reserved2 = 0;
|
||||
section.reserved3 = 0;
|
||||
|
||||
f.write(reinterpret_cast<const char*>(§ion), sizeof(section));
|
||||
|
||||
// Write section data
|
||||
f.write(reinterpret_cast<const char*>(section_bytes.data()), static_cast<std::streamsize>(section_bytes.size()));
|
||||
|
||||
f.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Build a minimal 32-bit Mach-O binary in-memory with a __text section
|
||||
std::vector<std::uint8_t> build_minimal_macho32(const std::vector<std::uint8_t>& section_bytes)
|
||||
// Helper function to create a minimal 32-bit Mach-O file with a __text section
|
||||
bool write_minimal_macho32_file(const std::string& path, const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
constexpr std::size_t load_cmd_size = sizeof(SegmentCommand32) + sizeof(Section32);
|
||||
constexpr std::size_t section_offset = sizeof(MachHeader32) + load_cmd_size;
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
|
||||
std::vector<std::uint8_t> buf(section_offset + section_bytes.size(), 0u);
|
||||
// Calculate sizes
|
||||
constexpr std::size_t header_size = sizeof(MachHeader32);
|
||||
constexpr std::size_t segment_size = sizeof(SegmentCommand32);
|
||||
constexpr std::size_t section_size = sizeof(Section32);
|
||||
constexpr std::size_t load_cmd_size = segment_size + section_size;
|
||||
|
||||
auto* header = reinterpret_cast<MachHeader32*>(buf.data());
|
||||
header->magic = mh_magic_32;
|
||||
header->cputype = 0x7;
|
||||
header->cpusubtype = 0x3;
|
||||
header->filetype = 0x2;
|
||||
header->ncmds = 1;
|
||||
header->sizeofcmds = static_cast<std::uint32_t>(load_cmd_size);
|
||||
// Section data will start after headers
|
||||
constexpr std::size_t section_offset = header_size + load_cmd_size;
|
||||
|
||||
auto* segment = reinterpret_cast<SegmentCommand32*>(buf.data() + sizeof(MachHeader32));
|
||||
segment->cmd = lc_segment;
|
||||
segment->cmdsize = static_cast<std::uint32_t>(load_cmd_size);
|
||||
std::ranges::copy(segment_name, segment->segname);
|
||||
segment->vmaddr = 0x1000;
|
||||
segment->vmsize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
segment->fileoff = static_cast<std::uint32_t>(section_offset);
|
||||
segment->filesize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
segment->maxprot = 7;
|
||||
segment->initprot = 5;
|
||||
segment->nsects = 1;
|
||||
// Create Mach-O header
|
||||
MachHeader32 header{};
|
||||
header.magic = mh_magic_32;
|
||||
header.cputype = 0x7; // CPU_TYPE_X86
|
||||
header.cpusubtype = 0x3; // CPU_SUBTYPE_X86_ALL
|
||||
header.filetype = 0x2; // MH_EXECUTE
|
||||
header.ncmds = 1;
|
||||
header.sizeofcmds = static_cast<std::uint32_t>(load_cmd_size);
|
||||
header.flags = 0;
|
||||
|
||||
auto* section = reinterpret_cast<Section32*>(buf.data() + sizeof(MachHeader32) + sizeof(SegmentCommand32));
|
||||
std::ranges::copy(section_name, section->sectname);
|
||||
std::ranges::copy(segment_name, section->segname);
|
||||
section->addr = 0x1000;
|
||||
section->size = static_cast<std::uint32_t>(section_bytes.size());
|
||||
section->offset = static_cast<std::uint32_t>(section_offset);
|
||||
f.write(reinterpret_cast<const char*>(&header), sizeof(header));
|
||||
|
||||
std::memcpy(buf.data() + section_offset, section_bytes.data(), section_bytes.size());
|
||||
return buf;
|
||||
// Create segment command
|
||||
SegmentCommand32 segment{};
|
||||
segment.cmd = lc_segment;
|
||||
segment.cmdsize = static_cast<std::uint32_t>(load_cmd_size);
|
||||
std::ranges::copy(segment_name, segment.segname);
|
||||
segment.vmaddr = 0x1000;
|
||||
segment.vmsize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
segment.fileoff = static_cast<std::uint32_t>(section_offset);
|
||||
segment.filesize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
segment.maxprot = 7; // VM_PROT_ALL
|
||||
segment.initprot = 5; // VM_PROT_READ | VM_PROT_EXECUTE
|
||||
segment.nsects = 1;
|
||||
segment.flags = 0;
|
||||
|
||||
f.write(reinterpret_cast<const char*>(&segment), sizeof(segment));
|
||||
|
||||
// Create section
|
||||
Section32 section{};
|
||||
std::ranges::copy(section_name, section.sectname);
|
||||
std::ranges::copy(segment_name, segment.segname);
|
||||
section.addr = 0x1000;
|
||||
section.size = static_cast<std::uint32_t>(section_bytes.size());
|
||||
section.offset = static_cast<std::uint32_t>(section_offset);
|
||||
section.align = 0;
|
||||
section.reloff = 0;
|
||||
section.nreloc = 0;
|
||||
section.flags = 0;
|
||||
section.reserved1 = 0;
|
||||
section.reserved2 = 0;
|
||||
|
||||
f.write(reinterpret_cast<const char*>(§ion), sizeof(section));
|
||||
|
||||
// Write section data
|
||||
f.write(reinterpret_cast<const char*>(section_bytes.data()), static_cast<std::streamsize>(section_bytes.size()));
|
||||
|
||||
f.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Test scanning for a pattern that exists in a 64-bit Mach-O file
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanFindsPattern64)
|
||||
{
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x48, 0x89, 0xE5, 0x90, 0x90};
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
constexpr std::string_view path = "./test_minimal_macho64.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x48, 0x89, 0xE5, 0x90, 0x90}; // push rbp; mov rbp, rsp; nop; nop
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 48 89 E5", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 48 89 E5", "__text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
if (res.has_value())
|
||||
{
|
||||
EXPECT_EQ(res->target_offset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Test scanning for a pattern that exists in a 32-bit Mach-O file
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanFindsPattern32)
|
||||
{
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x89, 0xE5, 0x90, 0x90};
|
||||
const auto f = MemFdFile::create(build_minimal_macho32(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
constexpr std::string_view path = "./test_minimal_macho32.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x89, 0xE5, 0x90, 0x90}; // push ebp; mov ebp, esp; nop; nop
|
||||
ASSERT_TRUE(write_minimal_macho32_file(path.data(), bytes));
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 89 E5", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 89 E5", "__text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
if (res.has_value())
|
||||
{
|
||||
EXPECT_EQ(res->target_offset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Test scanning for a pattern that does not exist
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanMissingPattern)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_macho_missing.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x00, 0x01, 0x02, 0x03};
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "FF EE DD", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "FF EE DD", "__text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning for a pattern at a non-zero offset
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanPatternAtOffset)
|
||||
{
|
||||
const std::vector<std::uint8_t> bytes = {0x90, 0x90, 0x90, 0x55, 0x48, 0x89, 0xE5};
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
constexpr std::string_view path = "./test_minimal_macho_offset.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x90, 0x90, 0x90, 0x55, 0x48, 0x89, 0xE5}; // nops then pattern
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 48 89 E5", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 48 89 E5", "__text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
if (res.has_value())
|
||||
{
|
||||
EXPECT_EQ(res->target_offset, 3);
|
||||
}
|
||||
}
|
||||
|
||||
// Test scanning with wildcards
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanWithWildcard)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_macho_wildcard.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x48, 0x89, 0xE5, 0x90};
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 ? 89 E5", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 ? 89 E5", "__text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning a non-existent file
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanNonExistentFile)
|
||||
{
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file("/non/existent/file.bin", "55 48", "__text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning an invalid (non-Mach-O) file
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanInvalidFile)
|
||||
{
|
||||
constexpr std::string_view path = "./test_invalid_macho.bin";
|
||||
std::ofstream f(path.data(), std::ios::binary);
|
||||
const std::vector<std::uint8_t> garbage = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
|
||||
const auto f = MemFdFile::create(garbage);
|
||||
ASSERT_TRUE(f.valid());
|
||||
f.write(reinterpret_cast<const char*>(garbage.data()), static_cast<std::streamsize>(garbage.size()));
|
||||
f.close();
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 48", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 48", "__text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning for a non-existent section
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanNonExistentSection)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_macho_nosect.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x48, 0x89, 0xE5};
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 48", "__nonexistent");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 48", "__nonexistent");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning with null module base address
|
||||
TEST(unit_test_macho_pattern_scan_loaded, ScanNullModule)
|
||||
{
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_loaded_module(nullptr, "55 48", "__text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning in loaded module with invalid magic
|
||||
TEST(unit_test_macho_pattern_scan_loaded, ScanInvalidMagic)
|
||||
{
|
||||
std::vector<std::uint8_t> invalid_data(256, 0x00);
|
||||
|
||||
@@ -1,28 +1,114 @@
|
||||
// Unit test for PePatternScanner::scan_for_pattern_in_file using a synthetic PE-like file
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/utility/pe_pattern_scan.hpp>
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include "mem_fd_helper.hpp"
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
using namespace omath;
|
||||
|
||||
// Helper: write a trivial PE-like file with DOS header and a single section named .text
|
||||
static bool write_minimal_pe_file(const std::string& path, const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open()) return false;
|
||||
|
||||
// Write DOS header (e_magic = 0x5A4D, e_lfanew at offset 0x3C)
|
||||
std::vector<std::uint8_t> dos(64, 0);
|
||||
dos[0] = 'M'; dos[1] = 'Z';
|
||||
// e_lfanew -> place NT headers right after DOS (offset 0x80)
|
||||
std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(dos.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
f.write(reinterpret_cast<const char*>(dos.data()), dos.size());
|
||||
|
||||
// Pad up to e_lfanew
|
||||
if (f.tellp() < static_cast<std::streampos>(e_lfanew))
|
||||
{
|
||||
std::vector<char> pad(e_lfanew - static_cast<std::uint32_t>(f.tellp()), 0);
|
||||
f.write(pad.data(), pad.size());
|
||||
}
|
||||
|
||||
// NT headers signature 'PE\0\0'
|
||||
f.put('P'); f.put('E'); f.put('\0'); f.put('\0');
|
||||
|
||||
// FileHeader: machine, num_sections
|
||||
std::uint16_t machine = 0x8664; // x64
|
||||
std::uint16_t num_sections = 1;
|
||||
std::uint32_t dummy32 = 0;
|
||||
std::uint32_t dummy32b = 0;
|
||||
std::uint16_t size_optional = 0xF0; // reasonable
|
||||
std::uint16_t characteristics = 0;
|
||||
f.write(reinterpret_cast<const char*>(&machine), sizeof(machine));
|
||||
f.write(reinterpret_cast<const char*>(&num_sections), sizeof(num_sections));
|
||||
f.write(reinterpret_cast<const char*>(&dummy32), sizeof(dummy32));
|
||||
f.write(reinterpret_cast<const char*>(&dummy32b), sizeof(dummy32b));
|
||||
std::uint32_t num_symbols = 0;
|
||||
f.write(reinterpret_cast<const char*>(&num_symbols), sizeof(num_symbols));
|
||||
f.write(reinterpret_cast<const char*>(&size_optional), sizeof(size_optional));
|
||||
f.write(reinterpret_cast<const char*>(&characteristics), sizeof(characteristics));
|
||||
|
||||
// OptionalHeader (x64) minimal: magic 0x20b, image_base, size_of_code, size_of_headers
|
||||
std::uint16_t magic = 0x20b;
|
||||
f.write(reinterpret_cast<const char*>(&magic), sizeof(magic));
|
||||
// filler for rest of optional header up to size_optional
|
||||
std::vector<std::uint8_t> opt(size_optional - sizeof(magic), 0);
|
||||
// set size_code near end
|
||||
// we'll set image_base and size_code fields in reasonable positions for extractor
|
||||
// For simplicity, leave zeros; extractor primarily uses optional_header.image_base and size_code later,
|
||||
// but we will craft a SectionHeader that points to raw data we append below.
|
||||
f.write(reinterpret_cast<const char*>(opt.data()), opt.size());
|
||||
|
||||
// Section header (name 8 bytes, then remaining 36 bytes)
|
||||
char name[8] = {'.','t','e','x','t',0,0,0};
|
||||
f.write(name, 8);
|
||||
|
||||
// Write placeholder bytes for the rest of the section header and remember its start
|
||||
constexpr std::uint32_t section_header_rest = 36u;
|
||||
const std::streampos header_rest_pos = f.tellp();
|
||||
std::vector<char> placeholder(section_header_rest, 0);
|
||||
f.write(placeholder.data(), placeholder.size());
|
||||
|
||||
// Now write section raw data and remember its file offset
|
||||
const std::streampos data_pos = f.tellp();
|
||||
f.write(reinterpret_cast<const char*>(section_bytes.data()), static_cast<std::streamsize>(section_bytes.size()));
|
||||
|
||||
// Patch section header fields: virtual_size, virtual_address, size_raw_data, ptr_raw_data
|
||||
const std::uint32_t virtual_size = static_cast<std::uint32_t>(section_bytes.size());
|
||||
constexpr std::uint32_t virtual_address = 0x1000u;
|
||||
const std::uint32_t size_raw_data = static_cast<std::uint32_t>(section_bytes.size());
|
||||
const std::uint32_t ptr_raw_data = static_cast<std::uint32_t>(data_pos);
|
||||
|
||||
// Seek back to the header_rest_pos and write fields in order
|
||||
f.seekp(header_rest_pos, std::ios::beg);
|
||||
f.write(reinterpret_cast<const char*>(&virtual_size), sizeof(virtual_size));
|
||||
f.write(reinterpret_cast<const char*>(&virtual_address), sizeof(virtual_address));
|
||||
f.write(reinterpret_cast<const char*>(&size_raw_data), sizeof(size_raw_data));
|
||||
f.write(reinterpret_cast<const char*>(&ptr_raw_data), sizeof(ptr_raw_data));
|
||||
|
||||
// Seek back to end for consistency
|
||||
f.seekp(0, std::ios::end);
|
||||
|
||||
f.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_file, ScanFindsPattern)
|
||||
{
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x8B, 0xEC, 0x90, 0x90};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
constexpr std::string_view path = "./test_minimal_pe.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x8B, 0xEC, 0x90, 0x90}; // pattern at offset 0
|
||||
ASSERT_TRUE(write_minimal_pe_file(path.data(), bytes));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "55 8B EC", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "55 8B EC", ".text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_file, ScanMissingPattern)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_pe_2.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x00, 0x01, 0x02, 0x03};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_minimal_pe_file(path.data(), bytes));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "FF EE DD", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "FF EE DD", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
@@ -1,89 +1,120 @@
|
||||
// Additional tests for PePatternScanner to exercise edge cases and loaded-module scanning
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/utility/pe_pattern_scan.hpp>
|
||||
#include <vector>
|
||||
#include "mem_fd_helper.hpp"
|
||||
|
||||
using namespace omath;
|
||||
|
||||
static bool write_bytes(const std::string& path, const std::vector<std::uint8_t>& data)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
f.write(reinterpret_cast<const char*>(data.data()), data.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more, InvalidDosHeader)
|
||||
{
|
||||
constexpr std::string_view path = "./test_bad_dos.bin";
|
||||
std::vector<std::uint8_t> data(128, 0);
|
||||
// write wrong magic
|
||||
data[0] = 'N';
|
||||
data[1] = 'Z';
|
||||
const auto f = MemFdFile::create(data);
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_bytes(path.data(), data));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "55 8B EC", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "55 8B EC", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more, InvalidNtSignature)
|
||||
{
|
||||
constexpr std::string_view path = "./test_bad_nt.bin";
|
||||
std::vector<std::uint8_t> data(256, 0);
|
||||
// valid DOS header
|
||||
data[0] = 'M';
|
||||
data[1] = 'Z';
|
||||
// point e_lfanew to 0x80
|
||||
constexpr std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(data.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
// write garbage at e_lfanew (not 'PE\0\0')
|
||||
data[e_lfanew + 0] = 'X';
|
||||
data[e_lfanew + 1] = 'Y';
|
||||
data[e_lfanew + 2] = 'Z';
|
||||
data[e_lfanew + 3] = 'W';
|
||||
const auto f = MemFdFile::create(data);
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_bytes(path.data(), data));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "55 8B EC", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "55 8B EC", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more, SectionNotFound)
|
||||
{
|
||||
// Minimal PE with a .data section; scanning for .text should fail
|
||||
constexpr std::uint32_t e_lfanew = 0x80u;
|
||||
constexpr std::uint16_t size_opt = 0xF0u;
|
||||
constexpr std::size_t nt_off = e_lfanew;
|
||||
constexpr std::size_t fh_off = nt_off + 4;
|
||||
constexpr std::size_t oh_off = fh_off + 20;
|
||||
constexpr std::size_t sh_off = oh_off + size_opt;
|
||||
constexpr std::size_t data_off = sh_off + 44;
|
||||
// reuse minimal writer but with section named .data and search .text
|
||||
constexpr std::string_view path = "./test_section_not_found.bin";
|
||||
std::ofstream f(path.data(), std::ios::binary);
|
||||
ASSERT_TRUE(f.is_open());
|
||||
// DOS
|
||||
std::vector<std::uint8_t> dos(64, 0);
|
||||
dos[0] = 'M';
|
||||
dos[1] = 'Z';
|
||||
std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(dos.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
f.write(reinterpret_cast<char*>(dos.data()), dos.size());
|
||||
// pad
|
||||
std::vector<char> pad(e_lfanew - static_cast<std::uint32_t>(f.tellp()), 0);
|
||||
f.write(pad.data(), pad.size());
|
||||
// NT sig
|
||||
f.put('P');
|
||||
f.put('E');
|
||||
f.put('\0');
|
||||
f.put('\0');
|
||||
// FileHeader minimal
|
||||
std::uint16_t machine = 0x8664;
|
||||
std::uint16_t num_sections = 1;
|
||||
std::uint32_t z = 0;
|
||||
std::uint32_t z2 = 0;
|
||||
std::uint32_t numsym = 0;
|
||||
std::uint16_t size_opt = 0xF0;
|
||||
std::uint16_t ch = 0;
|
||||
f.write(reinterpret_cast<char*>(&machine), sizeof(machine));
|
||||
f.write(reinterpret_cast<char*>(&num_sections), sizeof(num_sections));
|
||||
f.write(reinterpret_cast<char*>(&z), sizeof(z));
|
||||
f.write(reinterpret_cast<char*>(&z2), sizeof(z2));
|
||||
f.write(reinterpret_cast<char*>(&numsym), sizeof(numsym));
|
||||
f.write(reinterpret_cast<char*>(&size_opt), sizeof(size_opt));
|
||||
f.write(reinterpret_cast<char*>(&ch), sizeof(ch));
|
||||
// Optional header magic
|
||||
std::uint16_t magic = 0x20b;
|
||||
f.write(reinterpret_cast<char*>(&magic), sizeof(magic));
|
||||
std::vector<std::uint8_t> opt(size_opt - sizeof(magic), 0);
|
||||
f.write(reinterpret_cast<char*>(opt.data()), opt.size());
|
||||
// Section header named .data
|
||||
char name[8] = {'.', 'd', 'a', 't', 'a', 0, 0, 0};
|
||||
f.write(name, 8);
|
||||
std::uint32_t vs = 4, va = 0x1000, srd = 4, prd = 0x200;
|
||||
f.write(reinterpret_cast<char*>(&vs), 4);
|
||||
f.write(reinterpret_cast<char*>(&va), 4);
|
||||
f.write(reinterpret_cast<char*>(&srd), 4);
|
||||
f.write(reinterpret_cast<char*>(&prd), 4);
|
||||
std::vector<char> rest(16, 0);
|
||||
f.write(rest.data(), rest.size());
|
||||
// section bytes
|
||||
std::vector<std::uint8_t> sec = {0x00, 0x01, 0x02, 0x03};
|
||||
f.write(reinterpret_cast<char*>(sec.data()), sec.size());
|
||||
f.close();
|
||||
|
||||
const std::vector<std::uint8_t> sec_data = {0x00, 0x01, 0x02, 0x03};
|
||||
std::vector<std::uint8_t> buf(data_off + sec_data.size(), 0u);
|
||||
|
||||
buf[0] = 'M'; buf[1] = 'Z';
|
||||
std::memcpy(buf.data() + 0x3C, &e_lfanew, 4);
|
||||
buf[nt_off] = 'P'; buf[nt_off + 1] = 'E';
|
||||
|
||||
const std::uint16_t machine = 0x8664u, num_sections = 1u;
|
||||
std::memcpy(buf.data() + fh_off, &machine, 2);
|
||||
std::memcpy(buf.data() + fh_off + 2, &num_sections, 2);
|
||||
std::memcpy(buf.data() + fh_off + 16, &size_opt, 2);
|
||||
|
||||
const std::uint16_t magic = 0x20Bu;
|
||||
std::memcpy(buf.data() + oh_off, &magic, 2);
|
||||
|
||||
const char name[8] = {'.','d','a','t','a',0,0,0};
|
||||
std::memcpy(buf.data() + sh_off, name, 8);
|
||||
|
||||
const std::uint32_t vs = 4u, va = 0x1000u, srd = 4u, prd = static_cast<std::uint32_t>(data_off);
|
||||
std::memcpy(buf.data() + sh_off + 8, &vs, 4);
|
||||
std::memcpy(buf.data() + sh_off + 12, &va, 4);
|
||||
std::memcpy(buf.data() + sh_off + 16, &srd, 4);
|
||||
std::memcpy(buf.data() + sh_off + 20, &prd, 4);
|
||||
std::memcpy(buf.data() + data_off, sec_data.data(), sec_data.size());
|
||||
|
||||
const auto f = MemFdFile::create(buf);
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "00 01", ".text");
|
||||
auto res = PePatternScanner::scan_for_pattern_in_file(path, "00 01", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more, LoadedModuleScanFinds)
|
||||
{
|
||||
// Create an in-memory buffer that mimics loaded module layout
|
||||
// Define local header structs matching those in source
|
||||
struct DosHeader
|
||||
{
|
||||
std::uint16_t e_magic;
|
||||
@@ -127,9 +158,9 @@ TEST(unit_test_pe_pattern_scan_more, LoadedModuleScanFinds)
|
||||
std::uint32_t base_of_code;
|
||||
std::uint64_t image_base;
|
||||
std::uint32_t section_alignment;
|
||||
std::uint32_t file_alignment;
|
||||
std::uint32_t file_alignment; /* rest omitted */
|
||||
std::uint32_t size_image;
|
||||
std::uint32_t size_headers;
|
||||
std::uint32_t size_headers; /* keep space */
|
||||
std::uint8_t pad[200];
|
||||
};
|
||||
struct SectionHeader
|
||||
@@ -157,38 +188,44 @@ TEST(unit_test_pe_pattern_scan_more, LoadedModuleScanFinds)
|
||||
};
|
||||
|
||||
const std::vector<std::uint8_t> pattern_bytes = {0xDE, 0xAD, 0xBE, 0xEF, 0x90};
|
||||
constexpr std::uint32_t base_of_code = 0x200;
|
||||
constexpr std::uint32_t base_of_code = 0x200; // will place bytes at offset 0x200
|
||||
const std::uint32_t size_code = static_cast<std::uint32_t>(pattern_bytes.size());
|
||||
|
||||
const std::uint32_t bufsize = 0x400 + size_code;
|
||||
std::vector<std::uint8_t> buf(bufsize, 0);
|
||||
|
||||
// DOS header
|
||||
const auto dos = reinterpret_cast<DosHeader*>(buf.data());
|
||||
dos->e_magic = 0x5A4D;
|
||||
dos->e_magic = 0x5A4D;
|
||||
dos->e_lfanew = 0x80;
|
||||
|
||||
// NT headers
|
||||
const auto nt = reinterpret_cast<ImageNtHeadersX64*>(buf.data() + dos->e_lfanew);
|
||||
nt->signature = 0x4550;
|
||||
nt->file_header.machine = 0x8664;
|
||||
nt->file_header.num_sections = 1;
|
||||
nt->file_header.size_optional_header = static_cast<std::uint16_t>(sizeof(OptionalHeaderX64));
|
||||
nt->optional_header.magic = 0x020B;
|
||||
nt->optional_header.base_of_code = base_of_code;
|
||||
nt->optional_header.size_code = size_code;
|
||||
nt->signature = 0x4550; // 'PE\0\0'
|
||||
nt->file_header.machine = 0x8664;
|
||||
nt->file_header.num_sections = 1;
|
||||
nt->file_header.size_optional_header = static_cast<std::uint16_t>(sizeof(OptionalHeaderX64));
|
||||
|
||||
nt->optional_header.magic = 0x020B; // x64
|
||||
nt->optional_header.base_of_code = base_of_code;
|
||||
nt->optional_header.size_code = size_code;
|
||||
|
||||
// Compute section table offset: e_lfanew + 4 (sig) + FileHeader + OptionalHeader
|
||||
const std::size_t section_table_off =
|
||||
static_cast<std::size_t>(dos->e_lfanew) + 4 + sizeof(FileHeader) + sizeof(OptionalHeaderX64);
|
||||
nt->optional_header.size_headers = static_cast<std::uint32_t>(section_table_off + sizeof(SectionHeader));
|
||||
|
||||
// Section header (.text)
|
||||
const auto sect = reinterpret_cast<SectionHeader*>(buf.data() + section_table_off);
|
||||
std::memset(sect, 0, sizeof(SectionHeader));
|
||||
std::memcpy(sect->name, ".text", 5);
|
||||
sect->virtual_size = size_code;
|
||||
sect->virtual_size = size_code;
|
||||
sect->virtual_address = base_of_code;
|
||||
sect->size_raw_data = size_code;
|
||||
sect->ptr_raw_data = base_of_code;
|
||||
sect->characteristics = 0x60000020;
|
||||
sect->size_raw_data = size_code;
|
||||
sect->ptr_raw_data = base_of_code;
|
||||
sect->characteristics = 0x60000020; // code | execute | read
|
||||
|
||||
// place code at base_of_code
|
||||
std::memcpy(buf.data() + base_of_code, pattern_bytes.data(), pattern_bytes.size());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_loaded_module(buf.data(), "DE AD BE EF", ".text");
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/utility/pe_pattern_scan.hpp>
|
||||
#include <vector>
|
||||
#include "mem_fd_helper.hpp"
|
||||
|
||||
using namespace omath;
|
||||
|
||||
@@ -20,6 +19,95 @@ struct TestFileHeader
|
||||
std::uint16_t characteristics;
|
||||
};
|
||||
|
||||
static bool write_bytes(const std::string& path, const std::vector<std::uint8_t>& data)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
f.write(reinterpret_cast<const char*>(data.data()), data.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
// Helper: write a trivial PE-like file with DOS header and a single section named .text
|
||||
static bool write_minimal_pe_file(const std::string& path, const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
|
||||
// Write DOS header (e_magic = 0x5A4D, e_lfanew at offset 0x3C)
|
||||
std::vector<std::uint8_t> dos(64, 0);
|
||||
dos[0] = 'M';
|
||||
dos[1] = 'Z';
|
||||
std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(dos.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
f.write(reinterpret_cast<const char*>(dos.data()), dos.size());
|
||||
|
||||
// Pad up to e_lfanew
|
||||
if (f.tellp() < static_cast<std::streampos>(e_lfanew))
|
||||
{
|
||||
std::vector<char> pad(e_lfanew - static_cast<std::uint32_t>(f.tellp()), 0);
|
||||
f.write(pad.data(), pad.size());
|
||||
}
|
||||
|
||||
// NT headers signature 'PE\0\0'
|
||||
f.put('P');
|
||||
f.put('E');
|
||||
f.put('\0');
|
||||
f.put('\0');
|
||||
|
||||
// FileHeader minimal
|
||||
std::uint16_t machine = 0x8664; // x64
|
||||
std::uint16_t num_sections = 1;
|
||||
std::uint32_t dummy32 = 0;
|
||||
std::uint32_t dummy32b = 0;
|
||||
std::uint16_t size_optional = 0xF0;
|
||||
std::uint16_t characteristics = 0;
|
||||
f.write(reinterpret_cast<const char*>(&machine), sizeof(machine));
|
||||
f.write(reinterpret_cast<const char*>(&num_sections), sizeof(num_sections));
|
||||
f.write(reinterpret_cast<const char*>(&dummy32), sizeof(dummy32));
|
||||
f.write(reinterpret_cast<const char*>(&dummy32b), sizeof(dummy32b));
|
||||
std::uint32_t num_symbols = 0;
|
||||
f.write(reinterpret_cast<const char*>(&num_symbols), sizeof(num_symbols));
|
||||
f.write(reinterpret_cast<const char*>(&size_optional), sizeof(size_optional));
|
||||
f.write(reinterpret_cast<const char*>(&characteristics), sizeof(characteristics));
|
||||
|
||||
// OptionalHeader minimal filler
|
||||
std::uint16_t magic = 0x20b;
|
||||
f.write(reinterpret_cast<const char*>(&magic), sizeof(magic));
|
||||
std::vector<std::uint8_t> opt(size_optional - sizeof(magic), 0);
|
||||
f.write(reinterpret_cast<const char*>(opt.data()), opt.size());
|
||||
|
||||
// Section header (name 8 bytes, then remaining 36 bytes)
|
||||
char name[8] = {'.', 't', 'e', 'x', 't', 0, 0, 0};
|
||||
f.write(name, 8);
|
||||
|
||||
constexpr std::uint32_t section_header_rest = 36u;
|
||||
const std::streampos header_rest_pos = f.tellp();
|
||||
std::vector<char> placeholder(section_header_rest, 0);
|
||||
f.write(placeholder.data(), placeholder.size());
|
||||
|
||||
// Now write section raw data and remember its file offset
|
||||
const std::streampos data_pos = f.tellp();
|
||||
f.write(reinterpret_cast<const char*>(section_bytes.data()), static_cast<std::streamsize>(section_bytes.size()));
|
||||
|
||||
// Patch section header fields
|
||||
const std::uint32_t virtual_size = static_cast<std::uint32_t>(section_bytes.size());
|
||||
constexpr std::uint32_t virtual_address = 0x1000u;
|
||||
const std::uint32_t size_raw_data = static_cast<std::uint32_t>(section_bytes.size());
|
||||
const std::uint32_t ptr_raw_data = static_cast<std::uint32_t>(data_pos);
|
||||
|
||||
f.seekp(header_rest_pos, std::ios::beg);
|
||||
f.write(reinterpret_cast<const char*>(&virtual_size), sizeof(virtual_size));
|
||||
f.write(reinterpret_cast<const char*>(&virtual_address), sizeof(virtual_address));
|
||||
f.write(reinterpret_cast<const char*>(&size_raw_data), sizeof(size_raw_data));
|
||||
f.write(reinterpret_cast<const char*>(&ptr_raw_data), sizeof(ptr_raw_data));
|
||||
f.seekp(0, std::ios::end);
|
||||
|
||||
f.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more2, LoadedModuleNullBaseReturnsNull)
|
||||
{
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_loaded_module(nullptr, "DE AD");
|
||||
@@ -28,6 +116,7 @@ TEST(unit_test_pe_pattern_scan_more2, LoadedModuleNullBaseReturnsNull)
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more2, LoadedModuleInvalidOptionalHeaderReturnsNull)
|
||||
{
|
||||
// Construct in-memory buffer with DOS header but invalid optional header magic
|
||||
std::vector<std::uint8_t> buf(0x200, 0);
|
||||
struct DosHeader
|
||||
{
|
||||
@@ -39,11 +128,19 @@ TEST(unit_test_pe_pattern_scan_more2, LoadedModuleInvalidOptionalHeaderReturnsNu
|
||||
dos->e_magic = 0x5A4D;
|
||||
dos->e_lfanew = 0x80;
|
||||
|
||||
// Place an NT header with wrong optional magic at e_lfanew
|
||||
const auto nt_ptr = buf.data() + dos->e_lfanew;
|
||||
nt_ptr[0] = 'P'; nt_ptr[1] = 'E'; nt_ptr[2] = 0; nt_ptr[3] = 0;
|
||||
|
||||
// write signature
|
||||
nt_ptr[0] = 'P';
|
||||
nt_ptr[1] = 'E';
|
||||
nt_ptr[2] = 0;
|
||||
nt_ptr[3] = 0;
|
||||
// craft FileHeader with size_optional_header large enough
|
||||
constexpr std::uint16_t size_opt = 0xE0;
|
||||
std::memcpy(nt_ptr + 4 + 12, &size_opt, sizeof(size_opt));
|
||||
// file header starts at offset 4
|
||||
std::memcpy(nt_ptr + 4 + 12, &size_opt,
|
||||
sizeof(size_opt)); // size_optional_header located after 12 bytes into FileHeader
|
||||
// write optional header magic to be invalid value
|
||||
constexpr std::uint16_t bad_magic = 0x9999;
|
||||
std::memcpy(nt_ptr + 4 + sizeof(std::uint32_t) + sizeof(std::uint16_t) + sizeof(std::uint16_t), &bad_magic,
|
||||
sizeof(bad_magic));
|
||||
@@ -54,11 +151,13 @@ TEST(unit_test_pe_pattern_scan_more2, LoadedModuleInvalidOptionalHeaderReturnsNu
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more2, FileX86OptionalHeaderScanFindsPattern)
|
||||
{
|
||||
constexpr std::string_view path = "./test_pe_x86.bin";
|
||||
const std::vector<std::uint8_t> pattern = {0xDE, 0xAD, 0xBE, 0xEF};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(pattern));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "DE AD BE EF", ".text");
|
||||
// Use helper from this file to write a consistent minimal PE file with .text section
|
||||
ASSERT_TRUE(write_minimal_pe_file(path.data(), pattern));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "DE AD BE EF", ".text");
|
||||
ASSERT_TRUE(res.has_value());
|
||||
EXPECT_GE(res->virtual_base_addr, 0u);
|
||||
EXPECT_GE(res->raw_base_addr, 0u);
|
||||
@@ -67,73 +166,97 @@ TEST(unit_test_pe_pattern_scan_more2, FileX86OptionalHeaderScanFindsPattern)
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more2, FilePatternNotFoundReturnsNull)
|
||||
{
|
||||
const std::string path = "./test_pe_no_pattern.bin";
|
||||
std::vector<std::uint8_t> data(512, 0);
|
||||
data[0] = 'M'; data[1] = 'Z';
|
||||
// minimal DOS/NT headers to make extract_section fail earlier or return empty data
|
||||
data[0] = 'M';
|
||||
data[1] = 'Z';
|
||||
constexpr std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(data.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
data[e_lfanew + 0] = 'P'; data[e_lfanew + 1] = 'E';
|
||||
|
||||
// NT signature
|
||||
data[e_lfanew + 0] = 'P';
|
||||
data[e_lfanew + 1] = 'E';
|
||||
data[e_lfanew + 2] = 0;
|
||||
data[e_lfanew + 3] = 0;
|
||||
// FileHeader: one section, size_optional_header set low
|
||||
constexpr std::uint16_t num_sections = 1;
|
||||
constexpr std::uint16_t size_optional_header = 0xE0;
|
||||
std::memcpy(data.data() + e_lfanew + 6, &num_sections, sizeof(num_sections));
|
||||
std::memcpy(data.data() + e_lfanew + 4 + 12, &size_optional_header, sizeof(size_optional_header));
|
||||
|
||||
// Optional header magic x64
|
||||
constexpr std::uint16_t magic = 0x020B;
|
||||
std::memcpy(data.data() + e_lfanew + 4 + sizeof(TestFileHeader), &magic, sizeof(magic));
|
||||
|
||||
// Section header .text with small data that does not contain the pattern
|
||||
constexpr std::size_t offset_to_segment_table = e_lfanew + 4 + sizeof(TestFileHeader) + size_optional_header;
|
||||
constexpr char name[8] = {'.', 't', 'e', 'x', 't', 0, 0, 0};
|
||||
std::memcpy(data.data() + offset_to_segment_table, name, 8);
|
||||
std::uint32_t vs = 4, va = 0x1000, srd = 4, prd = 0x200;
|
||||
std::memcpy(data.data() + offset_to_segment_table + 8, &vs, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 12, &va, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 8, &vs, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 12, &va, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 16, &srd, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 20, &prd, 4);
|
||||
// write file
|
||||
ASSERT_TRUE(write_bytes(path, data));
|
||||
|
||||
const auto f = MemFdFile::create(data);
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "AA BB CC", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "AA BB CC", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
// Extra tests for pe_pattern_scan edge cases (on-disk API)
|
||||
|
||||
TEST(PePatternScanMore2, PatternAtStartFound)
|
||||
{
|
||||
const std::string path = "./test_pe_more_start.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x90, 0x01, 0x02, 0x03, 0x04};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "90 01 02", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "90 01 02", ".text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(PePatternScanMore2, PatternAtEndFound)
|
||||
{
|
||||
const std::vector<std::uint8_t> bytes = {0x00, 0x11, 0x22, 0x33, 0x44};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
const std::string path = "./test_pe_more_end.bin";
|
||||
std::vector<std::uint8_t> bytes = {0x00, 0x11, 0x22, 0x33, 0x44};
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "22 33 44", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "22 33 44", ".text");
|
||||
if (!res.has_value())
|
||||
{
|
||||
// Debug: inspect section header via the memfd path
|
||||
std::ifstream in(f.path(), std::ios::binary);
|
||||
if (in.is_open())
|
||||
// Try to locate the section header and print the raw section bytes the scanner would read
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
ASSERT_TRUE(in.is_open());
|
||||
// search for ".text" name
|
||||
in.seekg(0, std::ios::beg);
|
||||
std::vector<char> filebuf((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
const auto it = std::search(filebuf.begin(), filebuf.end(), std::begin(".text"), std::end(".text") - 1);
|
||||
if (it != filebuf.end())
|
||||
{
|
||||
std::vector<char> filebuf((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
const auto it = std::search(filebuf.begin(), filebuf.end(), std::begin(".text"), std::end(".text") - 1);
|
||||
if (it != filebuf.end())
|
||||
const size_t pos = std::distance(filebuf.begin(), it);
|
||||
// after name, next fields: virtual_size (4), virtual_address(4), size_raw_data(4), ptr_raw_data(4)
|
||||
const size_t meta_off = pos + 8;
|
||||
uint32_t virtual_size{};
|
||||
uint32_t virtual_address{};
|
||||
uint32_t size_raw_data{};
|
||||
uint32_t ptr_raw_data{};
|
||||
std::memcpy(&virtual_size, filebuf.data() + meta_off, sizeof(virtual_size));
|
||||
std::memcpy(&virtual_address, filebuf.data() + meta_off + 4, sizeof(virtual_address));
|
||||
std::memcpy(&size_raw_data, filebuf.data() + meta_off + 8, sizeof(size_raw_data));
|
||||
std::memcpy(&ptr_raw_data, filebuf.data() + meta_off + 12, sizeof(ptr_raw_data));
|
||||
|
||||
std::cerr << "Parsed section header: virtual_size=" << virtual_size << " virtual_address=0x" << std::hex
|
||||
<< virtual_address << std::dec << " size_raw_data=" << size_raw_data
|
||||
<< " ptr_raw_data=" << ptr_raw_data << "\n";
|
||||
|
||||
if (ptr_raw_data + size_raw_data <= filebuf.size())
|
||||
{
|
||||
const std::size_t pos = std::distance(filebuf.begin(), it);
|
||||
const std::size_t meta_off = pos + 8;
|
||||
std::uint32_t virtual_size{}, virtual_address{}, size_raw_data{}, ptr_raw_data{};
|
||||
std::memcpy(&virtual_size, filebuf.data() + meta_off, sizeof(virtual_size));
|
||||
std::memcpy(&virtual_address, filebuf.data() + meta_off + 4, sizeof(virtual_address));
|
||||
std::memcpy(&size_raw_data, filebuf.data() + meta_off + 8, sizeof(size_raw_data));
|
||||
std::memcpy(&ptr_raw_data, filebuf.data() + meta_off + 12, sizeof(ptr_raw_data));
|
||||
std::cerr << "Parsed section header: virtual_size=" << virtual_size << " virtual_address=0x"
|
||||
<< std::hex << virtual_address << std::dec << " size_raw_data=" << size_raw_data
|
||||
<< " ptr_raw_data=" << ptr_raw_data << "\n";
|
||||
std::cerr << "Extracted section bytes:\n";
|
||||
for (size_t i = 0; i < size_raw_data; i += 16)
|
||||
{
|
||||
std::fprintf(stderr, "%04zx: ", i);
|
||||
for (size_t j = 0; j < 16 && i + j < size_raw_data; ++j)
|
||||
std::fprintf(stderr, "%02x ", static_cast<uint8_t>(filebuf[ptr_raw_data + i + j]));
|
||||
std::fprintf(stderr, "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,30 +265,30 @@ TEST(PePatternScanMore2, PatternAtEndFound)
|
||||
|
||||
TEST(PePatternScanMore2, WildcardMatches)
|
||||
{
|
||||
const std::string path = "./test_pe_more_wild.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0xDE, 0xAD, 0xBE, 0xEF};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "DE ?? BE", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "DE ?? BE", ".text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(PePatternScanMore2, PatternLongerThanBuffer)
|
||||
{
|
||||
const std::string path = "./test_pe_more_small.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0xAA, 0xBB};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "AA BB CC", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "AA BB CC", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(PePatternScanMore2, InvalidPatternParse)
|
||||
{
|
||||
const std::string path = "./test_pe_more_invalid.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x01, 0x02, 0x03};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "01 GG 03", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "01 GG 03", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
341
tests/general/unit_test_physx_colliders.cpp
Normal file
341
tests/general/unit_test_physx_colliders.cpp
Normal file
@@ -0,0 +1,341 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/collision/gjk_algorithm.hpp>
|
||||
#include <omath/collision/physx_box_collider.hpp>
|
||||
#include <omath/collision/physx_rigid_body.hpp>
|
||||
#include <omath/collision/physx_sphere_collider.hpp>
|
||||
#include <omath/collision/physx_world.hpp>
|
||||
|
||||
using namespace omath::collision;
|
||||
using omath::Vector3;
|
||||
|
||||
// ─── PhysXBoxCollider ────────────────────────────────────────────────────────
|
||||
|
||||
TEST(PhysXBoxCollider, DefaultOriginIsZero)
|
||||
{
|
||||
PhysXBoxCollider box({1.f, 1.f, 1.f});
|
||||
EXPECT_EQ(box.get_origin(), Vector3<float>(0.f, 0.f, 0.f));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, SetAndGetOrigin)
|
||||
{
|
||||
PhysXBoxCollider box({1.f, 1.f, 1.f}, {3.f, 4.f, 5.f});
|
||||
EXPECT_EQ(box.get_origin(), Vector3<float>(3.f, 4.f, 5.f));
|
||||
|
||||
box.set_origin({-1.f, 0.f, 2.f});
|
||||
EXPECT_EQ(box.get_origin(), Vector3<float>(-1.f, 0.f, 2.f));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, FurthestPointPositiveDirection)
|
||||
{
|
||||
// Box centred at origin with half-extents (2, 3, 4).
|
||||
// Direction (+x, +y, +z) → furthest corner is (+2, +3, +4).
|
||||
PhysXBoxCollider box({2.f, 3.f, 4.f});
|
||||
const auto p = box.find_abs_furthest_vertex_position({1.f, 1.f, 1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 2.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 3.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 4.f);
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, FurthestPointNegativeDirection)
|
||||
{
|
||||
// Direction (-x, -y, -z) → furthest corner is (-2, -3, -4).
|
||||
PhysXBoxCollider box({2.f, 3.f, 4.f});
|
||||
const auto p = box.find_abs_furthest_vertex_position({-1.f, -1.f, -1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, -2.f);
|
||||
EXPECT_FLOAT_EQ(p.y, -3.f);
|
||||
EXPECT_FLOAT_EQ(p.z, -4.f);
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, FurthestPointMixedDirection)
|
||||
{
|
||||
// Direction (+x, -y, +z) → furthest corner is (+2, -3, +4).
|
||||
PhysXBoxCollider box({2.f, 3.f, 4.f});
|
||||
const auto p = box.find_abs_furthest_vertex_position({1.f, -1.f, 1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 2.f);
|
||||
EXPECT_FLOAT_EQ(p.y, -3.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 4.f);
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, FurthestPointWithNonZeroOrigin)
|
||||
{
|
||||
// Box at (10, 0, 0), half-extents (1, 1, 1). Direction +x → (11, 1, 1).
|
||||
PhysXBoxCollider box({1.f, 1.f, 1.f}, {10.f, 0.f, 0.f});
|
||||
const auto p = box.find_abs_furthest_vertex_position({1.f, 1.f, 1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 11.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 1.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 1.f);
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, SetHalfExtentsUpdatesGeometry)
|
||||
{
|
||||
PhysXBoxCollider box({1.f, 1.f, 1.f});
|
||||
box.set_half_extents({5.f, 6.f, 7.f});
|
||||
|
||||
const auto& he = box.get_geometry().halfExtents;
|
||||
EXPECT_FLOAT_EQ(he.x, 5.f);
|
||||
EXPECT_FLOAT_EQ(he.y, 6.f);
|
||||
EXPECT_FLOAT_EQ(he.z, 7.f);
|
||||
|
||||
// Furthest vertex must reflect the new extents.
|
||||
const auto p = box.find_abs_furthest_vertex_position({1.f, 1.f, 1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 5.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 6.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 7.f);
|
||||
}
|
||||
|
||||
// ─── PhysXSphereCollider ─────────────────────────────────────────────────────
|
||||
|
||||
TEST(PhysXSphereCollider, DefaultOriginIsZero)
|
||||
{
|
||||
PhysXSphereCollider sphere(1.f);
|
||||
EXPECT_EQ(sphere.get_origin(), Vector3<float>(0.f, 0.f, 0.f));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, SetAndGetOrigin)
|
||||
{
|
||||
PhysXSphereCollider sphere(1.f, {1.f, 2.f, 3.f});
|
||||
EXPECT_EQ(sphere.get_origin(), Vector3<float>(1.f, 2.f, 3.f));
|
||||
|
||||
sphere.set_origin({-5.f, 0.f, 0.f});
|
||||
EXPECT_EQ(sphere.get_origin(), Vector3<float>(-5.f, 0.f, 0.f));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, FurthestPointAlongPureXAxis)
|
||||
{
|
||||
// Direction (1,0,0), radius 3 → furthest point is (3, 0, 0).
|
||||
PhysXSphereCollider sphere(3.f);
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({1.f, 0.f, 0.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 3.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 0.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 0.f);
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, FurthestPointAlongDiagonal)
|
||||
{
|
||||
// Direction (1,1,0), radius 1 → furthest point at distance 1 from origin.
|
||||
PhysXSphereCollider sphere(1.f);
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({1.f, 1.f, 0.f});
|
||||
const float dist = std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
|
||||
EXPECT_NEAR(dist, 1.f, 1e-5f);
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, FurthestPointWithNonZeroOrigin)
|
||||
{
|
||||
// Sphere at (5, 0, 0), radius 2. Direction +x → (7, 0, 0).
|
||||
PhysXSphereCollider sphere(2.f, {5.f, 0.f, 0.f});
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({1.f, 0.f, 0.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 7.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 0.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 0.f);
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, ZeroDirectionReturnsOrigin)
|
||||
{
|
||||
PhysXSphereCollider sphere(5.f, {1.f, 2.f, 3.f});
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({0.f, 0.f, 0.f});
|
||||
EXPECT_EQ(p, sphere.get_origin());
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, SetRadiusUpdatesGeometry)
|
||||
{
|
||||
PhysXSphereCollider sphere(1.f);
|
||||
sphere.set_radius(10.f);
|
||||
EXPECT_FLOAT_EQ(sphere.get_radius(), 10.f);
|
||||
|
||||
// Furthest point along +x should now be at x = 10.
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({1.f, 0.f, 0.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 10.f);
|
||||
}
|
||||
|
||||
// ─── GJK: Box vs Box ─────────────────────────────────────────────────────────
|
||||
|
||||
using GjkBox = omath::collision::GjkAlgorithm<PhysXBoxCollider>;
|
||||
using GjkSphere = omath::collision::GjkAlgorithm<PhysXSphereCollider>;
|
||||
|
||||
TEST(PhysXBoxGjk, CollidingOverlap)
|
||||
{
|
||||
// Two unit boxes: A at origin, B shifted by 0.5 — clearly overlapping.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {0.5f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, NotCollidingTouching)
|
||||
{
|
||||
// Boxes exactly touching on the +X face: A[-1,1] and B[1,3] along X.
|
||||
// GJK treats boundary contact (Minkowski difference passes through origin) as non-collision.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {2.f, 0.f, 0.f});
|
||||
EXPECT_FALSE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, CollidingSlightOverlap)
|
||||
{
|
||||
// Boxes overlapping by 0.1 along X: A[-1,1] and B[0.9,2.9].
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {1.9f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, NotCollidingSeparated)
|
||||
{
|
||||
// Boxes separated by a gap: A[-1,1] and B[3,5] along X.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {4.f, 0.f, 0.f});
|
||||
EXPECT_FALSE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, CollidingSameOrigin)
|
||||
{
|
||||
// Same position — fully overlapping.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f});
|
||||
EXPECT_TRUE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, NotCollidingDiagonalSeparation)
|
||||
{
|
||||
// Boxes separated along a diagonal so no axis-aligned faces overlap.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {3.f, 3.f, 3.f});
|
||||
EXPECT_FALSE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, DifferentSizesColliding)
|
||||
{
|
||||
// Large box vs small box inside it.
|
||||
const PhysXBoxCollider large({5.f, 5.f, 5.f});
|
||||
const PhysXBoxCollider small_box({1.f, 1.f, 1.f}, {2.f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkBox::is_collide(large, small_box));
|
||||
}
|
||||
|
||||
// ─── GJK: Sphere vs Sphere ───────────────────────────────────────────────────
|
||||
|
||||
TEST(PhysXSphereGjk, CollidingOverlap)
|
||||
{
|
||||
// Radii 1 each, centres 1 apart — overlapping.
|
||||
const PhysXSphereCollider a(1.f);
|
||||
const PhysXSphereCollider b(1.f, {1.f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereGjk, CollidingSameOrigin)
|
||||
{
|
||||
const PhysXSphereCollider a(1.f);
|
||||
const PhysXSphereCollider b(1.f);
|
||||
EXPECT_TRUE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereGjk, NotCollidingSeparated)
|
||||
{
|
||||
// Radii 1 each, centres 3 apart — gap of 1.
|
||||
const PhysXSphereCollider a(1.f);
|
||||
const PhysXSphereCollider b(1.f, {3.f, 0.f, 0.f});
|
||||
EXPECT_FALSE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereGjk, DifferentRadiiColliding)
|
||||
{
|
||||
// r=2 and r=1, centres 2.5 apart — still overlapping.
|
||||
const PhysXSphereCollider a(2.f);
|
||||
const PhysXSphereCollider b(1.f, {2.5f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereGjk, DifferentRadiiNotColliding)
|
||||
{
|
||||
// r=1 and r=1, centres 5 apart — separated.
|
||||
const PhysXSphereCollider a(1.f);
|
||||
const PhysXSphereCollider b(1.f, {5.f, 0.f, 0.f});
|
||||
EXPECT_FALSE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
// ─── PhysX simulation-based collision resolution ─────────────────────────────
|
||||
|
||||
// Helper: step the world N times with a fixed dt.
|
||||
static void step_n(omath::collision::PhysXWorld& world, int n, float dt = 1.f / 60.f)
|
||||
{
|
||||
for (int i = 0; i < n; ++i)
|
||||
world.step(dt);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, BoxFallsAndStopsOnGround)
|
||||
{
|
||||
// A box dropped from y=5 should come to rest at y≈0.5 (half-extent) above the ground plane.
|
||||
omath::collision::PhysXWorld world;
|
||||
world.add_ground_plane(0.f);
|
||||
|
||||
omath::collision::PhysXRigidBody box(world, physx::PxBoxGeometry(0.5f, 0.5f, 0.5f),
|
||||
{0.f, 5.f, 0.f});
|
||||
|
||||
step_n(world, 300); // ~5 simulated seconds
|
||||
|
||||
EXPECT_NEAR(box.get_origin().y, 0.5f, 0.05f);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, SphereFallsAndStopsOnGround)
|
||||
{
|
||||
// A sphere of radius 1 dropped from y=5 should rest at y≈1.
|
||||
omath::collision::PhysXWorld world;
|
||||
world.add_ground_plane(0.f);
|
||||
|
||||
omath::collision::PhysXRigidBody sphere(world, physx::PxSphereGeometry(1.f),
|
||||
{0.f, 5.f, 0.f});
|
||||
|
||||
step_n(world, 300);
|
||||
|
||||
EXPECT_NEAR(sphere.get_origin().y, 1.f, 0.05f);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, TwoBoxesCollideSeparate)
|
||||
{
|
||||
// Two boxes launched toward each other — after collision they must be
|
||||
// further apart than their combined half-extents (no overlap).
|
||||
omath::collision::PhysXWorld world({0.f, 0.f, 0.f}); // no gravity
|
||||
|
||||
omath::collision::PhysXRigidBody left (world, physx::PxBoxGeometry(0.5f, 0.5f, 0.5f), {-3.f, 0.f, 0.f});
|
||||
omath::collision::PhysXRigidBody right(world, physx::PxBoxGeometry(0.5f, 0.5f, 0.5f), { 3.f, 0.f, 0.f});
|
||||
|
||||
left.set_linear_velocity({ 5.f, 0.f, 0.f});
|
||||
right.set_linear_velocity({-5.f, 0.f, 0.f});
|
||||
|
||||
step_n(world, 120); // 2 simulated seconds
|
||||
|
||||
const float distance = right.get_origin().x - left.get_origin().x;
|
||||
// Boxes must not be overlapping (combined extents = 1.0).
|
||||
EXPECT_GE(distance, 1.0f);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, BoxGetOriginMatchesSetOrigin)
|
||||
{
|
||||
// Kinematic teleport — set_origin must immediately reflect in get_origin.
|
||||
omath::collision::PhysXWorld world;
|
||||
omath::collision::PhysXRigidBody box(world, physx::PxBoxGeometry(1.f, 1.f, 1.f));
|
||||
box.set_kinematic(true);
|
||||
|
||||
box.set_origin({7.f, 3.f, -2.f});
|
||||
|
||||
EXPECT_NEAR(box.get_origin().x, 7.f, 1e-4f);
|
||||
EXPECT_NEAR(box.get_origin().y, 3.f, 1e-4f);
|
||||
EXPECT_NEAR(box.get_origin().z, -2.f, 1e-4f);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, BoxFallsUnderGravity)
|
||||
{
|
||||
// Without a floor, a box should be lower after simulation than its start.
|
||||
omath::collision::PhysXWorld world; // default gravity -9.81 Y
|
||||
omath::collision::PhysXRigidBody box(world, physx::PxBoxGeometry(0.5f, 0.5f, 0.5f),
|
||||
{0.f, 10.f, 0.f});
|
||||
|
||||
const float y_start = box.get_origin().y;
|
||||
step_n(world, 60); // 1 simulated second
|
||||
|
||||
EXPECT_LT(box.get_origin().y, y_start);
|
||||
}
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"default-registry": {
|
||||
"kind": "git",
|
||||
"baseline": "b1b19307e2d2ec1eefbdb7ea069de7d4bcd31f01",
|
||||
"baseline": "efa4634bd526b87559684607d2cbbdeeec0f07d8",
|
||||
"repository": "https://github.com/microsoft/vcpkg"
|
||||
},
|
||||
"registries": [
|
||||
|
||||
@@ -52,6 +52,13 @@
|
||||
"lua",
|
||||
"sol2"
|
||||
]
|
||||
},
|
||||
"physx": {
|
||||
"description": "PhysX-backed collider implementations",
|
||||
"dependencies": [
|
||||
"physx"
|
||||
],
|
||||
"supports": "(windows & x64 & !mingw & !uwp) | (linux & x64) | (linux & arm64)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user