Debian Codegraph @

src/util/dvtablehook.cpp

raw
1 // SPDX-FileCopyrightText: 2019 - 2022 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4
5 #include "dvtablehook.h"
6
7 #include <QFileInfo>
8 #include <algorithm>
9 #ifdef Q_OS_LINUX
10 #include <sys/mman.h>
11 #include <unistd.h>
12 #include <dlfcn.h>
13
14 QT_BEGIN_NAMESPACE
15 QFunctionPointer qt_linux_find_symbol_sys(const char *symbol);
16 QT_END_NAMESPACE
17
18 #endif
19
20 DCORE_BEGIN_NAMESPACE
21
22 QMap<quintptr**, quintptr*> DVtableHook::objToOriginalVfptr;
23 QMap<const void*, quintptr*> DVtableHook::objToGhostVfptr;
24 QMap<const void*, quintptr> DVtableHook::objDestructFun;
25
26 bool DVtableHook::copyVtable(quintptr **obj)
27 {
28 int vtable_size = getVtableSize(obj);
29
30 if (vtable_size == 0)
31 return false;
32
33 // 多开辟一个元素, 新的虚表结构如下:
34 // 假设原虚表内存布局如下(考虑多继承):
35 // C Vtable (7 entities)
36 // +--------------------+
37 // struct C | offset_to_top (0) |
38 // object +--------------------+
39 // 0 - struct A (primary base) | RTTI for C |
40 // 0 - vptr_A -----------------------------> +--------------------+
41 // 8 - int ax | C::f0() |
42 // 16 - struct B +--------------------+
43 // 16 - vptr_B ----------------------+ | C::f1() |
44 // 24 - int bx | +--------------------+
45 // 28 - int cx | | offset_to_top (-16)|
46 // sizeof(C): 32 align: 8 | +--------------------+
47 // | | RTTI for C |
48 // +------> +--------------------+
49 // | Thunk C::f1() |
50 // +--------------------+
51 // 则新的表结构为:
52 // C Vtable (7 entities) C hooked Vtable (7 entities)
53 // +--------------------+ +--------------------+
54 // struct C | offset_to_top (0) | | offset_to_top (0) |
55 // object +--------------------+ +--------------------+
56 // 0 - struct A (primary base) | RTTI for C | | RTTI for C |
57 // 0 - vptr_A -----------------------------// +--------------------+ //------> +--------------------+
58 // 8 - int ax | C::f0() |\ | C::f0() | (or override custom function pointer)
59 // 16 - struct B +--------------------+ \ +--------------------+
60 // 16 - vptr_B ----------------------+ | C::f1() | \ | C::f1() | (or override custom function pointer)
61 // 24 - int bx | +--------------------+ \ +--------------------+
62 // 28 - int cx | | offset_to_top (-16)| \ | offset_to_top (-16)|
63 // sizeof(C): 32 align: 8 | +--------------------+ \ +--------------------+
64 // | | RTTI for C | + | RTTI for C |
65 // +------> +--------------------+ | +--------------------+
66 // | Thunk C::f1() | | | Thunk C::f1() |
67 // +--------------------+ | +--------------------+
68 // | | 0 |
69 // | +--------------------+
70 // +----| original entry |
71 // +--------------------+
72 quintptr *new_vtable = new quintptr[vtable_size + 2]; // store 0 and oringinal entry
73
74 memcpy(new_vtable, adjustToTop(*obj), vtable_size * sizeof(quintptr));
75 new_vtable[vtable_size] = 0;
76
77 //! save original vfptr
78 objToOriginalVfptr[obj] = *obj;
79 // 存储对象原虚表入口地址
80 new_vtable[vtable_size + 1] = quintptr(*obj);
81
82 *obj = adjustToEntry(new_vtable);
83 //! save ghost vfptr
84 objToGhostVfptr[obj] = new_vtable;
85
86 return true;
87 }
88
89 bool DVtableHook::clearGhostVtable(const void *obj)
90 {
91 if (!objToOriginalVfptr.remove((quintptr **)obj)) // Uninitialized memory may have values, for resetVtable
92 return false;
93 objDestructFun.remove(obj);
94
95 quintptr *vtable = objToGhostVfptr.take(obj);
96
97 if (vtable) {
98 delete[] vtable;
99
100 return true;
101 }
102
103 return false;
104 }
105
106 /**
107 \brief 通过遍历尝试找到析构函数在虚表中的位置
108 \a obj
109 \a destoryObjFun
110 \return
111 */
112 int DVtableHook::getDestructFunIndex(quintptr **obj, std::function<void(void)> destoryObjFun)
113 {
114 class _DestoryProbe
115 {
116 public:
117 static quintptr probe(quintptr obj) {
118 static quintptr _obj = 0;
119
120 if (obj == 0) {
121 obj = _obj;
122 _obj = 0;
123 } else {
124 _obj = obj;
125 }
126
127 return obj;
128 }
129
130 static void nothing() {
131
132 }
133 };
134
135 quintptr *vtable = *obj;
136 int vtable_size = getVtableSize(obj);
137
138 if (vtable_size == 0)
139 return -1;
140
141 quintptr *new_vtable = new quintptr[vtable_size];
142 std::fill(adjustToEntry(new_vtable), new_vtable + vtable_size, quintptr(&_DestoryProbe::nothing));
143
144 // 给对象设置新的虚表
145 *obj = adjustToEntry(new_vtable);
146
147 int index = -1;
148
149 for (int i = adjustToEntry(0); i < vtable_size; ++i) {
150 new_vtable[i] = quintptr(&_DestoryProbe::probe);
151
152 // 尝试销毁此对象, 且观察_DestoryProbe::probe是否被调用
153 // 如果被调用, 则证明覆盖此虚函数能达到监控对象被销毁的目的
154 destoryObjFun();
155
156 if (_DestoryProbe::probe(0) == quintptr(obj)) {
157 index = adjustToTop(i);
158 break;
159 }
160 }
161
162 // 恢复旧的虚表
163 *obj = vtable;
164 // 销毁临时虚表
165 delete[] new_vtable;
166
167 return index;
168 }
169
170 void DVtableHook::autoCleanVtable(const void *obj)
171 {
172 quintptr fun = objDestructFun.value(obj);
173
174 if (!fun)
175 return;
176
177 if (hasVtable(obj)) {// 需要判断一下,有可能在执行析构函数时虚表已经被删除
178 // clean
179 clearGhostVtable(obj);
180 }
181
182 typedef void(*Destruct)(const void*);
183 Destruct destruct = reinterpret_cast<Destruct>(fun);
184 // call origin destruct function
185 destruct(obj);
186 }
187
188 bool DVtableHook::ensureVtable(const void *obj, std::function<void ()> destoryObjFun)
189 {
190 quintptr **_obj = (quintptr**)(obj);
191
192 if (objToOriginalVfptr.contains(_obj)) {
193 // 不知道什么原因, 此时obj对象的虚表已经被还原
194 if (objToGhostVfptr.value((void *)obj) != adjustToTop(*_obj)) {
195 clearGhostVtable((void*)obj);
196 } else {
197 return true;
198 }
199 }
200
201 if (!copyVtable(_obj))
202 return false;
203
204 // 查找对象的析构函数
205 int index = getDestructFunIndex(_obj, destoryObjFun);
206
207 // 虚析构函数查找失败
208 if (index < 0) {
209 qCWarning(vtableHook) << "Failed do override destruct function: " << obj;
210 abort();
211 }
212
213 quintptr *new_vtable = *_obj;
214 // 保存对象真实的析构函数
215 objDestructFun[(void*)obj] = new_vtable[index];
216
217 // 覆盖析构函数, 用于在对象析构时自动清理虚表
218 new_vtable[index] = reinterpret_cast<quintptr>(&autoCleanVtable);
219
220 return true;
221 }
222
223 /*!
224 \brief DVtableHook::hasVtable 对象的虚表已经被覆盖时返回true,否则返回false
225 \a obj
226 \return
227 */
228 bool DVtableHook::hasVtable(const void *obj)
229 {
230 quintptr **_obj = (quintptr**)(obj);
231
232 return objToGhostVfptr.contains(_obj);
233 }
234
235 void DVtableHook::resetVtable(const void *obj)
236 {
237 quintptr **_obj = (quintptr**)obj;
238 int vtable_size = getVtableSize(_obj);
239 // 获取obj对象原本虚表的入口
240 auto vtableHead = adjustToTop(*_obj);
241 quintptr *vfptr_t2 = (quintptr*)vtableHead[vtable_size + 1]; // _obj - 2 + vtable_size + 1
242
243 if (!vfptr_t2)
244 return;
245
246 if (!clearGhostVtable(obj))
247 return;
248
249 // 还原虚表
250 *_obj = vfptr_t2;
251 }
252
253 /*!
254 \brief 将偏移量为\a functionOffset 的虚函数还原到原本的实现
255 \a obj
256 \a functionOffset
257 \return 如果成功, 返回还原之前obj对象虚表中存储的函数指针, 否则返回0
258 */
259 quintptr DVtableHook::resetVfptrFun(const void *obj, quintptr functionOffset)
260 {
261 quintptr *vfptr_t1 = *(quintptr **)obj;
262 quintptr current_fun = *(vfptr_t1 + functionOffset / sizeof(quintptr));
263 quintptr origin_fun = originalFun(obj, functionOffset);
264
265 if (!origin_fun) {
266 return 0;
267 }
268
269 // reset to original fun
270 *(vfptr_t1 + functionOffset / sizeof(quintptr)) = origin_fun;
271
272 return current_fun;
273 }
274
275 /*!
276 \brief 获取 \a obj 对象偏移量为 \a functionOffset 的虚函数原本的函数指针
277 \return 如果obj对象虚表没有被覆盖, 或者函数偏移量正确, 将返回0
278 */
279 quintptr DVtableHook::originalFun(const void *obj, quintptr functionOffset)
280 {
281 quintptr **_obj = (quintptr **)obj;
282 if (!hasVtable(obj)) {
283 qCWarning(vtableHook) << "Not override the object virtual table: " << obj;
284 return 0;
285 }
286
287 int vtable_size = getVtableSize(_obj);
288 // 获取obj对象原本虚表的入口
289 quintptr *vfptr_t2 = (quintptr*)(*_obj)[vtable_size - 1];
290
291 if (functionOffset > UINT_LEAST16_MAX) {
292 qCWarning(vtableHook, "Is not a virtual function, function address: 0X%llx", functionOffset);
293 return 0;
294 }
295
296 return *(vfptr_t2 + functionOffset / sizeof(quintptr));
297 }
298
299 #if DTK_VERSION < DTK_VERSION_CHECK(6, 0, 0, 0)
300 bool DVtableHook::isFinalClass(quintptr *obj)
301 {
302 Q_UNUSED(obj);
303 return true;
304 }
305
306 quintptr **DVtableHook::adjustThis(quintptr *obj)
307 {
308 Q_UNUSED(obj);
309 return nullptr;
310 }
311 #endif
312
313 #if defined(Q_OS_LINUX)
314 static int readProtFromPsm(quintptr adr, size_t length)
315 {
316 int prot = PROT_NONE;
317 QString fname = "/proc/self/maps";
318 QFile f(fname);
319 if (!f.open(QIODevice::ReadOnly)) {
320 qFatal("%s", f.errorString().toStdString().data());
321 //return prot; // never be executed
322 }
323
324 QByteArray data = f.readAll();
325 bool ok = false;
326 quintptr startAddr = 0, endAddr = 0;
327 QTextStream ts(data);
328 while (Q_UNLIKELY(!ts.atEnd())) {
329 const QString line = ts.readLine();
330 const QStringList &maps = line.split(' ');
331 if (Q_UNLIKELY(maps.size() < 3)) {
332 data = f.readLine();
333 continue;
334 }
335
336 //"00400000-00431000" "r--p"
337 const QStringList addrs = maps.value(0).split('-');
338 startAddr = addrs.value(0).toULongLong(&ok, 16);
339 Q_ASSERT(ok);
340 endAddr = addrs.value(1).toULongLong(&ok, 16);
341 Q_ASSERT(ok);
342 if (Q_LIKELY(adr >= endAddr)) {
343 continue;
344 }
345 if (adr >= startAddr && adr + length <= endAddr) {
346 QString ps = maps.value(1);
347 //qDebug() << maps.value(0) << maps.value(1);
348 for (QChar c : ps) {
349 switch (c.toLatin1()) {
350 case 'r':
351 prot |= PROT_READ;
352 break;
353 case 'w':
354 prot |= PROT_WRITE;
355 break;
356 case 'x':
357 prot |= PROT_EXEC;
358 break;
359 default:
360 break; // '-' 'p' don't care
361 }
362 }
363 break;
364 } else if (adr < startAddr) {
365 qFatal("%p not found in proc maps", reinterpret_cast<void *>(adr));
366 //break; // 超出了地址不需要再去检查了
367 }
368 }
369
370 return prot;
371 }
372 #endif
373
374 bool DVtableHook::forceWriteMemory(void *adr, const void *data, size_t length)
375 {
376 #ifdef Q_OS_LINUX
377 int page_size = sysconf(_SC_PAGESIZE);
378 quintptr x = reinterpret_cast<quintptr>(adr);
379 // 不减去一个pagesize防止跨越两个数据区域(对应/proc/self/maps两行数据)
380 void *new_adr = reinterpret_cast<void *>((x /*- page_size - 1*/) & ~(page_size - 1));
381 size_t override_data_length = length + x - reinterpret_cast<quintptr>(new_adr);
382
383 int oldProt = readProtFromPsm(quintptr(new_adr), override_data_length);
384 bool writeable = oldProt & PROT_WRITE;
385 // 增加判断是否已经可写,不能写才调用。
386 // 失败时直接放弃
387 if (!writeable && mprotect(new_adr, override_data_length, PROT_READ | PROT_WRITE)) {
388 qCWarning(vtableHook, "mprotect(change) failed: %s", strerror(errno));
389 return false;
390 }
391 #endif
392 // 复制数据
393 memcpy(adr, data, length);
394 #ifdef Q_OS_LINUX
395 // 恢复内存标志位
396 if (!writeable && mprotect(new_adr, override_data_length, oldProt)) {
397 qCWarning(vtableHook, "mprotect(restore) failed: %s", strerror(errno));
398 return false;
399 }
400 #endif
401
402 return true;
403 }
404
405 QFunctionPointer DVtableHook::resolve(const char *symbol)
406 {
407 #ifdef Q_OS_LINUX
408 /**
409 !!不要使用qt_linux_find_symbol_sys函数去获取符号
410
411 在龙芯平台上,qt_linux_find_symbol_sys 无法获取部分已加载动态库的符号,
412 可能的原因是这个函数对 dlsym 的调用是在 libQt5Core 动态库中,这个库加载的比较早,
413 有可能是因此导致无法获取比这个库加载更晚的库中的符号(仅为猜测)
414 */
415 return QFunctionPointer(dlsym(RTLD_DEFAULT, symbol));
416 #else
417 // TODO
418 return nullptr;
419 #endif
420 }
421
422 DCORE_END_NAMESPACE