Zeex/subhook

Fail to install hook with subhook::Hook.Install() in normal function call

Closed this issue · 3 comments

Now we can use subhook to change the function implementation in a single-thread application. However, we found that if we create another thread to install the hook, the function object in the main thread will not change.

Here is the simple program to reproduce the issue.

#include <iostream>
#include <thread>
#include <subhook.h>

using namespace std;

int add_func(int a, int b) {
    cout << "Call simple add" << endl;
    return a + b;
}

int minus_func(int a, int b) {
    cout << "Call new add func" << endl;
    return a + b + b;
}

void change_add_func() {
    subhook::Hook foo_hook((void*)add_func,
                        (void*)minus_func,
                        subhook::HookFlag64BitOffset);

    // Output simple add
    add_func(1,2);

    if (!foo_hook.Install()) {
      std::cout << "Install failed" << std::endl;
      return;
    }

    // Output new add
    add_func(1,2);
}


int main() {
  std::thread thread1(change_add_func);
  thread1.join();

  // Still output simple add
  add_func(1,2);
}

Is there anyway to support this in multi-thread application?

It seems not related to the multi-thread problem. It won't work if we pass the function address to the new normal function to subhook.Install().

We have fixed by using subhook_new and subhook_install instead of subhook::Hook.Install().

Zeex commented

Yep, you need to uninstall the hook first before calling Install(...) on it...

I'm going to update the method to make it auto-remove an existing hook if present and not fail because of it.

Thanks @Zeex and it would be better to add introduction in README if we still need to uninstall manually.