From 10f2042bee77c057cbfe19492ab83ed41a9f1f27 Mon Sep 17 00:00:00 2001 From: Tau Date: Sun, 23 May 2021 11:39:33 -0400 Subject: [PATCH] Add DLL binding helper --- util/dll-bind.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ util/dll-bind.h | 33 +++++++++++++++++++++++++++++++++ util/meson.build | 2 ++ 3 files changed, 82 insertions(+) create mode 100644 util/dll-bind.c create mode 100644 util/dll-bind.h diff --git a/util/dll-bind.c b/util/dll-bind.c new file mode 100644 index 0000000..9568d33 --- /dev/null +++ b/util/dll-bind.c @@ -0,0 +1,47 @@ +#include + +#include +#include + +#include "util/dll-bind.h" +#include "util/dprintf.h" + +HRESULT dll_bind( + void *dest, + HINSTANCE src, + const struct dll_bind_sym **syms_pos, + size_t syms_count) +{ + HRESULT hr; + void *src_result; + void **dest_field; + const struct dll_bind_sym *current_sym; + size_t i; + + assert(dest != NULL); + assert(src != NULL); + assert(syms_pos != NULL); + + hr = S_OK; + current_sym = *syms_pos; + + assert(current_sym != NULL); + + for (i = 0; i < syms_count; i++) { + src_result = GetProcAddress(src, current_sym->sym); + + if (src_result == NULL) { + hr = E_NOTIMPL; + + break; + } + + dest_field = (void **)(((uint8_t *)dest) + current_sym->off); + *dest_field = src_result; + current_sym++; + } + + *syms_pos = current_sym; + + return hr; +} diff --git a/util/dll-bind.h b/util/dll-bind.h new file mode 100644 index 0000000..08e647b --- /dev/null +++ b/util/dll-bind.h @@ -0,0 +1,33 @@ +#pragma once + +#include + +#include + +struct dll_bind_sym { + /* Symbol name to locate in the source DLL */ + const char *sym; + + /* Offset where the symbol pointer should be written in the target + structure */ + ptrdiff_t off; +}; + +/* + Bind a list of DLL symbols into a structure that contains function + pointers. + + - dest: Pointer to destination structure. + - src: Handle to source DLL. + - syms_pos: Pointer to a (mutable) pointer which points to the start of an + (immutable) table of symbols and structure offsets. This mutable + pointer is advanced until either a symbol fails to bind, in which case + an error is returned, or the end of the table is reached, in which + case success is returned. + - syms_count: Number of entries in the symbol table. +*/ +HRESULT dll_bind( + void *dest, + HINSTANCE src, + const struct dll_bind_sym **syms_pos, + size_t syms_count); diff --git a/util/meson.build b/util/meson.build index 0b76284..c3c07f9 100644 --- a/util/meson.build +++ b/util/meson.build @@ -11,6 +11,8 @@ util_lib = static_library( 'async.h', 'crc.c', 'crc.h', + 'dll-bind.c', + 'dll-bind.h', 'dprintf.c', 'dprintf.h', 'dump.c',