From 2754701dffaaa59d04bf944eb011bd08f69e3ded Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alf-Andr=C3=A9=20Walla?= Date: Fri, 2 Aug 2024 17:33:19 +0200 Subject: [PATCH] Add static function to retrieve public non-runtime functions from a binary --- src/sandbox.hpp | 1 + src/sandbox_functions.cpp | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/sandbox.hpp b/src/sandbox.hpp index 22380eb8..55c000ef 100644 --- a/src/sandbox.hpp +++ b/src/sandbox.hpp @@ -38,6 +38,7 @@ class Sandbox : public Node void set_program(Ref program); Ref get_program(); PackedStringArray get_functions() const; + static PackedStringArray get_functions_from_binary(const PackedByteArray& binary); // Make a function call to a function in the guest by its name. Variant vmcall(const Variant **args, GDExtensionInt arg_count, GDExtensionCallError &error); Variant vmcall_address(gaddr_t address, const Variant **args, GDExtensionInt arg_count, GDExtensionCallError &error); diff --git a/src/sandbox_functions.cpp b/src/sandbox_functions.cpp index a5ef8368..1c7c02ff 100644 --- a/src/sandbox_functions.cpp +++ b/src/sandbox_functions.cpp @@ -16,3 +16,22 @@ PackedStringArray Sandbox::get_functions() const { } return array; } + +PackedStringArray Sandbox::get_functions_from_binary(const PackedByteArray &binary) { + const auto binary_view = std::string_view{ (const char *)binary.ptr(), static_cast(binary.size()) }; + PackedStringArray array; + + // Instantiate Machine without loading the ELF + machine_t machine{ binary_view, riscv::MachineOptions{ + .load_program = false, // Do not load the ELF program. + } }; + + // Get all unmangled public functions from the guest program. + for (auto &functions : machine.memory.all_unmangled_function_symbols()) { + // Exclude functions that belong to the C/C++ runtime, as well as compiler-generated functions. + if (exclude_functions.count(functions) == 0) { + array.append(String(std::string(functions).c_str())); + } + } + return array; +} \ No newline at end of file