microsoft / Detours

Detours is a software package for monitoring and instrumenting API calls on Windows. It is distributed in source code form.
MIT License
5.18k stars 1.01k forks source link

Add type-checking version of DetourAttach? #176

Closed virtuald closed 3 years ago

virtuald commented 3 years ago

Idea: add a DetourAttachSafe (or better name since it's not really safer... ) to make it easier to determine if your detour attach is incorrect. Because of the void* casts often needed, we've sometimes gotten tripped up by not using the correct pointers.

Would require C++11, but you could surround the function with an #ifdef to not interfere with C compilers or older C++ compilers.

Here's an example of the type-checking in action (note: I haven't actually used this in conjunction with detours yet, was played around with it on Godbolt).

#include <type_traits>

template <typename T>
void DetourAttachSafe(T** v, T* f) {
    static_assert(std::is_function<T>::value == true, "must be a function pointer");
    // TODO: call DetourAttach(v, f)
}

typedef void (* TestFnType)(int);

TestFnType t;
TestFnType *tp;

void testFn(int) {}

void doMain() {
    int x;
    int *xp;
    //DetourAttachSafe(&xp, &x);
    DetourAttachSafe(&t, &testFn);
    //DetourAttachSafe(&tp, &t);
}

If this would be accepted, I can make a PR at some point and actually try it out.

sylveon commented 3 years ago

This is what I have:

template<typename T>
concept function_pointer = std::is_pointer_v<T> && std::is_function_v<std::remove_pointer_t<T>>;

template<function_pointer T>
LONG attach(T &function, std::type_identity_t<T> detour) noexcept
{
    return DetourAttach(reinterpret_cast<void **>(&function), reinterpret_cast<void *>(detour));
}
virtuald commented 3 years ago

Do you have a pre-C++20 version of that?

bgianfo commented 3 years ago

@virtuald sounds reasonable to me, we would appreciate that contribution. As you mentioned, having it be under an appropriate c++ version check would be important.

sylveon commented 3 years ago

See #178

virtuald commented 3 years ago

178 looks good to me, as long as it's ported to C++11 instead of C++14

sylveon commented 3 years ago

180 backported it to C++11