summaryrefslogtreecommitdiffstats
path: root/src/hooks.cpp
blob: 215ecfd1d7618cf9a56fbb1c2f81805d2d12d4c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// hooks.cpp — vtable hook installation and teardown bookkeeping.
#include "hl2h.h"

#include <mutex>
#include <vector>

namespace {

struct Installed {
  void *iface;
  void **old_vt;
};

std::mutex g_hook_mu;
std::vector<Installed> g_installed;

} // namespace

bool hooks_install_vtable(void *iface, size_t slots, const VtablePatch *patches,
                          int count) {
  if (!iface || !patches || count <= 0)
    return false;
  void **old = *(void ***)iface;
  if (!old)
    return false;
  for (int i = 0; i < count; i++) {
    if (patches[i].slot < 0 || (size_t)patches[i].slot >= slots) {
      logf("hooks: slot %d out of range (table has %u)", patches[i].slot,
           (unsigned)slots);
      return false;
    }
  }

  void **clone = vtable_clone(iface, slots);
  if (!clone)
    return false;
  for (int i = 0; i < count; i++) {
    if (patches[i].original)
      *patches[i].original = old[patches[i].slot];
    clone[patches[i].slot] = patches[i].replacement;
  }

  std::lock_guard<std::mutex> lock(g_hook_mu);
  *(void ***)iface = clone;
  g_installed.push_back({iface, old});
  return true;
}

void hooks_restore_all() {
  std::lock_guard<std::mutex> lock(g_hook_mu);
  for (auto it = g_installed.rbegin(); it != g_installed.rend(); ++it)
    *(void ***)it->iface = it->old_vt;
  g_installed.clear();
}

int hooks_installed_count() {
  std::lock_guard<std::mutex> lock(g_hook_mu);
  return (int)g_installed.size();
}