Compare commits

..

2 Commits

Author SHA1 Message Date
2a63f1ff52 Finish Improving Performance 2024-08-02 00:56:22 -04:00
199eecda97 WIP 2024-08-01 21:57:31 -04:00
9 changed files with 201 additions and 214 deletions

View File

@ -1,32 +0,0 @@
#include "function.h"
// Virtual Function Information
template <typename T>
__VirtualFunctionInfo<T>::__VirtualFunctionInfo(T *const addr_, void *const parent_):
addr(addr_),
parent(parent_) {}
template <typename T>
bool __VirtualFunctionInfo<T>::can_overwrite() const {
return ((void *) *addr) != parent;
}
// Function Information
template <typename Ret, typename... Args>
__Function<Ret(Args...)>::__Function(const char *const name_, const __Function<Ret(Args...)>::ptr_type func_, const __Function<Ret(Args...)>::ptr_type thunk_):
is_virtual(false),
func(func_),
enabled(true),
name(name_),
backup(func_),
thunk(thunk_) {}
template <typename Ret, typename... Args>
__Function<Ret(Args...)>::__Function(const char *const name_, __Function<Ret(Args...)>::ptr_type *const func_, void *const parent, const __Function<Ret(Args...)>::ptr_type thunk_):
is_virtual(true),
func(__VirtualFunctionInfo(func_, parent)),
enabled(std::get<__VirtualFunctionInfo<ptr_type>>(func).can_overwrite()),
name(name_),
backup(*get_vtable_addr()),
thunk(thunk_) {}
// Thunks
thunk_enabler_t thunk_enabler;

View File

@ -1,110 +0,0 @@
#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);
extern thunk_enabler_t thunk_enabler;
// 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;
}
// Enable Thunk
enable_thunk();
// Overwrite
type original = get_thunk_target();
thunk_target = [original, target](Args... args) {
return target(original, std::forward<Args>(args)...);
};
return true;
}
// Getters
[[nodiscard]] ptr_type get(bool result_will_be_stored) {
if (!enabled) {
return nullptr;
} else {
if (result_will_be_stored) {
enable_thunk();
}
if (is_virtual) {
return *get_vtable_addr();
} else {
return std::get<ptr_type>(func);
}
}
}
[[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 {
return backup;
}
}
private:
// Current Function
const bool is_virtual;
std::variant<ptr_type, __VirtualFunctionInfo<ptr_type>> func;
public:
// State
const bool enabled;
const char *const name;
// Backup Of Original Function Pointer
const ptr_type backup;
private:
// Thunk
const ptr_type thunk;
type thunk_target;
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;
}
}
};

View File

@ -1,15 +1,10 @@
#define LEAN_SYMBOLS_HEADER
#include "{{ headerPath }}" #include "{{ headerPath }}"
#include "{{ data }}/function.cpp"
// Thunks // Thunk Template
template <typename T> template <auto *const *func>
struct __Thunk; decltype(auto) __thunk(auto... args) {
template <typename Ret, typename... Args> return (*func)->get_thunk_target()(std::forward<decltype(args)>(args)...);
struct __Thunk<Ret(Args...)> { }
template <__Function<Ret(Args...)> *const *func>
static Ret call(Args... args) {
return (*func)->get_thunk_target()(std::forward<Args>(args)...);
}
};
{{ main }} {{ main }}

View File

@ -6,7 +6,8 @@
#endif #endif
// Headers // Headers
#include "{{ data }}/function.h" #include <variant>
#include <functional>
#include <cstddef> #include <cstddef>
#include <string> #include <string>
#include <vector> #include <vector>
@ -14,6 +15,123 @@
#include <type_traits> #include <type_traits>
#include <cstring> #include <cstring>
// Virtual Function Information
template <typename T>
class __Function;
template <typename T>
class __VirtualFunctionInfo {
__VirtualFunctionInfo(T *const addr_, void *const parent_):
addr(addr_),
parent(parent_) {}
[[nodiscard]] bool can_overwrite() const {
return ((void *) *addr) != parent;
}
T *const addr;
void *const parent;
friend class __Function<std::remove_pointer_t<T>>;
};
// Thunks
typedef void *(*thunk_enabler_t)(void *target, void *thunk);
extern thunk_enabler_t thunk_enabler;
// 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 *const name_, const ptr_type func_, const ptr_type thunk_):
func(func_),
enabled(true),
name(name_),
backup(func_),
thunk(thunk_) {}
// Virtual Function
__Function(const char *const name_, ptr_type *const func_, void *const parent, const ptr_type thunk_):
func(__VirtualFunctionInfo(func_, parent)),
enabled(std::get<__VirtualFunctionInfo<ptr_type>>(func).can_overwrite()),
name(name_),
backup(*get_vtable_addr()),
thunk(thunk_) {}
// Overwrite Function
[[nodiscard]] bool overwrite(overwrite_type target) {
// Check If Enabled
if (!enabled) {
return false;
}
// Enable Thunk
enable_thunk();
// Overwrite
type original = get_thunk_target();
thunk_target = [original, target](Args... args) {
return target(original, std::forward<Args>(args)...);
};
return true;
}
// Getters
[[nodiscard]] ptr_type get(bool result_will_be_stored) {
if (!enabled) {
return nullptr;
} else {
if (result_will_be_stored) {
enable_thunk();
}
if (is_virtual()) {
return *get_vtable_addr();
} else {
return std::get<ptr_type>(func);
}
}
}
[[nodiscard]] ptr_type *get_vtable_addr() const {
return std::get<__VirtualFunctionInfo<ptr_type>>(func).addr;
}
[[nodiscard]] type get_thunk_target() const {
if (thunk_target) {
return thunk_target;
} else {
return backup;
}
}
private:
// Current Function
std::variant<ptr_type, __VirtualFunctionInfo<ptr_type>> func;
[[nodiscard]] bool is_virtual() const {
return func.index() == 1;
}
public:
// State
const bool enabled;
const char *const name;
// Backup Of Original Function Pointer
const ptr_type backup;
private:
// Thunk
const ptr_type thunk;
type thunk_target;
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;
}
}
};
// Shortcuts // Shortcuts
typedef unsigned char uchar; typedef unsigned char uchar;
typedef unsigned short ushort; typedef unsigned short ushort;

View File

@ -105,3 +105,4 @@ export function preventConstruction(self: string) {
out += `${INDENT}${self} &operator=(const ${self} &) = delete;\n`; out += `${INDENT}${self} &operator=(const ${self} &) = delete;\n`;
return out; return out;
} }
export const LEAN_HEADER_GUARD = '#ifndef LEAN_SYMBOLS_HEADER\n';

View File

@ -1,4 +1,5 @@
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import * as path from 'node:path';
import { STRUCTURE_FILES, EXTENSION, formatFile, getDataDir } from './common'; import { STRUCTURE_FILES, EXTENSION, formatFile, getDataDir } from './common';
import { getStructure } from './map'; import { getStructure } from './map';
import { Struct } from './struct'; import { Struct } from './struct';
@ -14,9 +15,8 @@ function invalidFileType(file: string) {
throw new Error(`Invalid File Type: ${file}`); throw new Error(`Invalid File Type: ${file}`);
} }
const sourceOutput = process.argv.shift()!; const sourceOutput = process.argv.shift()!;
if (!sourceOutput.endsWith('.cpp')) { fs.rmSync(sourceOutput, {force: true, recursive: true});
invalidFileType(sourceOutput); fs.mkdirSync(sourceOutput, {recursive: true});
}
const headerOutput = process.argv.shift()!; const headerOutput = process.argv.shift()!;
if (!headerOutput.endsWith('.h')) { if (!headerOutput.endsWith('.h')) {
invalidFileType(headerOutput); invalidFileType(headerOutput);
@ -151,28 +151,38 @@ function makeMainHeader(output: string) {
makeMainHeader(headerOutput); makeMainHeader(headerOutput);
// Generate Compiled Code // Generate Compiled Code
function makeCompiledCode(output: string) { function makeCompiledCode(outputDir: string) {
// Load Symbols // Load Symbols
const structureObjects = loadSymbols(); const structureObjects = loadSymbols();
// Generate // Generate
let declarations = ''; let first = true;
for (const structure of structureObjects) { for (const structure of structureObjects) {
// Thunks
let declarations = '';
if (first) {
first = false;
declarations += '// Thunk Enabler\n';
declarations += 'thunk_enabler_t thunk_enabler;\n\n';
}
// Structure
const name = structure.getName(); const name = structure.getName();
declarations += `// ${name}\n`; declarations += `// ${name}\n`;
try { try {
declarations += structure.generateCode(); declarations += structure.generateCode().trim();
} catch (e) { } catch (e) {
console.log(`Error Generating Code: ${name}: ${e instanceof Error ? e.stack : e}`); console.log(`Error Generating Code: ${name}: ${e instanceof Error ? e.stack : e}`);
process.exit(1); process.exit(1);
} }
declarations += '\n'; declarations += '\n';
}
// Write // Write
const headerPath = fs.realpathSync(headerOutput); const headerPath = fs.realpathSync(headerOutput);
const main = declarations.trim(); const main = declarations.trim();
const result = formatFile('out.cpp', {headerPath, main, data: getDataDir()}); const result = formatFile('out.cpp', {headerPath, main, data: getDataDir()});
const output = path.join(outputDir, name + '.cpp');
fs.writeFileSync(output, result); fs.writeFileSync(output, result);
}
} }
makeCompiledCode(sourceOutput); makeCompiledCode(sourceOutput);

View File

@ -27,24 +27,22 @@ export class Method {
getType() { getType() {
return this.getName() + '_t'; return this.getName() + '_t';
} }
getProperty(hasWrapper: boolean) { #getRawType() {
let out = INDENT; return INTERNAL + 'raw_' + this.getType();
if (hasWrapper) {
out += `${this.getWrapperType()}::ptr_type ${this.shortName}`;
} else {
out += `${formatType(this.returnType.trim())}(*${this.shortName})${this.args.trim()}`;
} }
out += ';\n'; getProperty() {
return out; return `${INDENT}${this.#getRawType()} *${this.shortName};\n`;
}
getWrapperType() {
return `std::remove_pointer_t<decltype(${this.getName()})>`;
}
#getSignature() {
return this.returnType.trim() + this.args.trim();
} }
#getFullType() { #getFullType() {
return `${INTERNAL}Function<${this.#getSignature()}>`; return `${INTERNAL}Function<${this.#getRawType()}>`;
}
// Typedefs
generateTypedefs() {
let out = '';
out += `typedef ${formatType(this.returnType.trim())}${this.#getRawType()}${this.args.trim()};\n`;
out += `typedef std::function<${this.#getRawType()}> ${this.getType()};\n`;
return out;
} }
// Overwrite Helper // Overwrite Helper
@ -53,9 +51,7 @@ export class Method {
} }
generate(code: boolean, isVirtual: boolean, parentSelf?: string) { generate(code: boolean, isVirtual: boolean, parentSelf?: string) {
let out = ''; let out = '';
if (!code) {
out += 'extern '; out += 'extern ';
}
const type = this.#getFullType(); const type = this.#getFullType();
out += `${type} *const ${this.getName()}`; out += `${type} *const ${this.getName()}`;
if (code) { if (code) {
@ -64,14 +60,11 @@ export class Method {
const parentMethod = parentSelf ? `(void *) ${this.#getVirtualCall(parentSelf)}` : 'nullptr'; const parentMethod = parentSelf ? `(void *) ${this.#getVirtualCall(parentSelf)}` : 'nullptr';
out += `&${this.#getVirtualCall()}, ${parentMethod}`; out += `&${this.#getVirtualCall()}, ${parentMethod}`;
} else { } else {
out += `${this.getWrapperType()}::ptr_type(${toHex(this.address)})`; out += `(${this.#getRawType()} *) ${toHex(this.address)}`;
} }
out += `, ${INTERNAL}Thunk<${this.#getSignature()}>::call<&${this.getName()}>)`; out += `, ${INTERNAL}thunk<&${this.getName()}>)`;
} }
out += ';\n'; out += ';\n';
if (!code) {
out += `typedef ${this.getWrapperType()}::type ${this.getType()};\n`;
}
return out; return out;
} }
} }

View File

@ -1,4 +1,4 @@
import { INDENT, STRUCTURE_FILES, toHex, assertSize, INTERNAL, preventConstruction } from './common'; import { INDENT, STRUCTURE_FILES, toHex, assertSize, INTERNAL, preventConstruction, LEAN_HEADER_GUARD } from './common';
import { Method } from './method'; import { Method } from './method';
import { Property, StaticProperty } from './property'; import { Property, StaticProperty } from './property';
import { VTable } from './vtable'; import { VTable } from './vtable';
@ -139,32 +139,29 @@ export class Struct {
// Generate C++ Method Shortcuts // Generate C++ Method Shortcuts
#generateMethod(method: Method, isVirtual: boolean) { #generateMethod(method: Method, isVirtual: boolean) {
// Generate Method Call
let call = '';
if (isVirtual) {
call += `this->vtable->${method.shortName}`;
} else {
call += `${method.getName()}->get(false)`;
}
call += '(';
if (!method.isStatic) {
call += `(${method.self} *) this, `;
}
call += 'std::forward<Args>(args)...)';
// Generate Shortcut
let out = ''; let out = '';
out += `${INDENT}template <typename... Args>\n`;
out += INDENT; out += INDENT;
if (method.isStatic) { if (method.isStatic) {
out += 'static '; out += 'static ';
} }
out += `auto ${method.shortName}(Args&&... args) -> decltype(${call}) {\n`; out += `decltype(auto) ${method.shortName}(auto&&... args) {\n`;
out += `${INDENT}${INDENT}return ${call};\n`; out += `${INDENT}${INDENT}return `;
if (isVirtual) {
out += `this->vtable->${method.shortName}`;
} else {
out += `${method.getName()}->get(false)`;
}
out += '(';
if (!method.isStatic) {
out += `(${method.self} *) this, `;
}
out += 'std::forward<decltype(args)>(args)...);\n';
out += `${INDENT}}\n`; out += `${INDENT}}\n`;
return out; return out;
} }
#generateMethods() { #generateMethods() {
let out = ''; let out = '';
out += LEAN_HEADER_GUARD;
// Normal Methods // Normal Methods
for (const method of this.#methods) { for (const method of this.#methods) {
out += this.#generateMethod(method, false); out += this.#generateMethod(method, false);
@ -179,6 +176,7 @@ export class Struct {
} }
} }
// Return // Return
out += '#endif\n';
return out; return out;
} }
@ -202,11 +200,18 @@ export class Struct {
} }
// Method Wrappers // Method Wrappers
let typedefs = '';
let methodsOut = '';
for (const method of this.#methods) { for (const method of this.#methods) {
if (!method.isInherited) { if (!method.isInherited) {
out += method.generate(false, false); typedefs += method.generateTypedefs();
methodsOut += method.generate(false, false);
} }
} }
out += typedefs;
out += LEAN_HEADER_GUARD;
out += methodsOut;
out += '#endif\n';
// Structure // Structure
out += `struct ${this.#name} {\n`; out += `struct ${this.#name} {\n`;

View File

@ -1,4 +1,4 @@
import { INDENT, POINTER_SIZE, assertSize, getSelfArg, preventConstruction, toHex } from './common'; import { INDENT, LEAN_HEADER_GUARD, POINTER_SIZE, assertSize, getSelfArg, preventConstruction, toHex } from './common';
import { Method } from './method'; import { Method } from './method';
import { Property } from './property'; import { Property } from './property';
@ -116,13 +116,20 @@ export class VTable {
// Wrappers // Wrappers
const methods = this.getMethods(); const methods = this.getMethods();
if (this.canGenerateWrappers()) { let typedefs = '';
let methodsOut = '';
for (const info of methods) { for (const info of methods) {
if (info) { if (info) {
out += info.generate(false, true); typedefs += info.generateTypedefs();
if (this.canGenerateWrappers()) {
methodsOut += info.generate(false, true);
} }
} }
} }
out += typedefs;
out += LEAN_HEADER_GUARD;
out += methodsOut;
out += '#endif\n';
// Structure // Structure
out += `typedef struct ${this.#getName()} ${this.#getName()};\n`; out += `typedef struct ${this.#getName()} ${this.#getName()};\n`;
@ -130,7 +137,7 @@ export class VTable {
for (let i = 0; i < methods.length; i++) { for (let i = 0; i < methods.length; i++) {
const info = methods[i]; const info = methods[i];
if (info) { if (info) {
out += info.getProperty(this.canGenerateWrappers()); out += info.getProperty();
} else { } else {
out += `${INDENT}void *unknown${i};\n`; out += `${INDENT}void *unknown${i};\n`;
} }