symbol-processor/data/function.h

110 lines
2.8 KiB
C
Raw Normal View History

2024-07-17 07:47:32 +00:00
#pragma once
#include <variant>
#include <functional>
#include <type_traits>
// Virtual Function Information
template <typename T>
class __Function;
template <typename T>
class __VirtualFunctionInfo {
__VirtualFunctionInfo(T *addr_, void *parent_);
[[nodiscard]] bool can_overwrite() const;
T *const addr;
void *const parent;
friend class __Function<std::remove_pointer_t<T>>;
};
// Thunks
typedef void *(*thunk_enabler_t)(void *target, void *thunk);
2024-07-17 10:40:04 +00:00
extern thunk_enabler_t thunk_enabler;
2024-07-17 07:47:32 +00:00
// Function Information
template <typename Ret, typename... Args>
class __Function<Ret(Args...)> {
public:
// Types
using ptr_type = Ret (*)(Args...);
using type = std::function<Ret(Args...)>;
using overwrite_type = std::function<Ret(type, Args...)>;
// Normal Function
__Function(const char *name_, ptr_type func_, ptr_type thunk_);
// Virtual Function
__Function(const char *name_, ptr_type *func_, void *parent, ptr_type thunk_);
// Overwrite Function
[[nodiscard]] bool overwrite(overwrite_type target) {
// Check If Enabled
if (!enabled) {
return false;
}
2024-07-17 10:40:04 +00:00
// Enable Thunk
enable_thunk();
2024-07-17 07:47:32 +00:00
// Overwrite
type original = get_thunk_target();
thunk_target = [original, target](Args... args) {
2024-07-17 10:40:04 +00:00
return target(original, std::forward<Args>(args)...);
2024-07-17 07:47:32 +00:00
};
return true;
}
// Getters
2024-07-17 10:40:04 +00:00
[[nodiscard]] ptr_type get(bool result_will_be_stored) {
2024-07-17 07:47:32 +00:00
if (!enabled) {
return nullptr;
} else {
2024-07-17 10:40:04 +00:00
if (result_will_be_stored) {
enable_thunk();
}
if (is_virtual) {
return *get_vtable_addr();
} else {
return std::get<ptr_type>(func);
}
2024-07-17 07:47:32 +00:00
}
}
[[nodiscard]] ptr_type *get_vtable_addr() const {
if (is_virtual) {
return std::get<__VirtualFunctionInfo<ptr_type>>(func).addr;
} else {
return nullptr;
}
}
[[nodiscard]] type get_thunk_target() const {
if (thunk_target) {
return thunk_target;
} else {
2024-07-17 10:40:04 +00:00
return backup;
2024-07-17 07:47:32 +00:00
}
}
private:
// Current Function
const bool is_virtual;
std::variant<ptr_type, __VirtualFunctionInfo<ptr_type>> func;
2024-07-17 10:40:04 +00:00
public:
2024-07-17 07:47:32 +00:00
// State
const bool enabled;
const char *const name;
// Backup Of Original Function Pointer
const ptr_type backup;
2024-07-17 10:40:04 +00:00
private:
2024-07-17 07:47:32 +00:00
// Thunk
const ptr_type thunk;
type thunk_target;
2024-07-17 10:40:04 +00:00
bool thunk_enabled = false;
void enable_thunk() {
if (!thunk_enabled && enabled) {
ptr_type real_thunk = (ptr_type) thunk_enabler((void *) backup, (void *) thunk);
if (!is_virtual) {
func = real_thunk;
}
thunk_enabled = true;
}
}
2024-07-17 07:47:32 +00:00
};