1+ #pragma once
2+
3+ #include < cstdint>
4+ #include < map>
5+ #include < string>
6+
7+ namespace fakelinker {
8+ class SymbolResolver {
9+ public:
10+ struct SymbolResult {
11+ // 解析的库/地方范围的起始地址
12+ uintptr_t start;
13+ // 解析的库/地方范围的结束地址
14+ uintptr_t end;
15+ // 当前地址相对于 start 的偏移
16+ uintptr_t offset = UINTPTR_MAX;
17+ // 库名称
18+ const char *name;
19+ };
20+
21+ bool AddLibrary (const std::string &name);
22+
23+ bool AddAddressRange (const std::string &name, uintptr_t start, uintptr_t end);
24+
25+ /* *
26+ * @brief 格式化地址如下:
27+ * head 地址 [库名!偏移]
28+ *
29+ * @param address 待格式化地址
30+ * @param default_format 如果不再监控范围内是否格式化为 head 地址
31+ * @param head 添加指定头
32+ * @return std::string
33+ */
34+ std::string FormatAddress (uintptr_t address, bool default_format, const std::string &head = " " );
35+
36+ /* *
37+ * @brief 指定buffer处格式化地址,避免内存拷贝
38+ *
39+ * @param buffer 指定缓冲区
40+ * @param max_length 最大缓冲区大小
41+ * @param address 待格式化的地址
42+ * @param default_format 如果不再监控范围内是否格式化为 head 地址
43+ * @param head 添加指定头
44+ * @return true 在地址范围内
45+ * @return false 不在地址范围内
46+ */
47+ bool FormatAddressFromBuffer (char *&buffer, size_t max_length, uintptr_t address, bool default_format,
48+ const std::string &head = " " );
49+
50+ bool AddAddressRange (const std::string &name, const void *start, const void *end) {
51+ return AddAddressRange (name, reinterpret_cast <uintptr_t >(start), reinterpret_cast <uintptr_t >(end));
52+ }
53+
54+ std::string FormatAddress (const void *address, bool default_format, const std::string &head = " " ) {
55+ return FormatAddress (reinterpret_cast <uintptr_t >(address), default_format, head);
56+ }
57+
58+ bool FormatAddressFromBuffer (char *&buffer, size_t max_length, const void *address, bool default_format,
59+ const std::string &head = " " ) {
60+ return FormatAddressFromBuffer (buffer, max_length, reinterpret_cast <uintptr_t >(address), default_format, head);
61+ }
62+
63+ bool ResolveSymbol (uintptr_t address, SymbolResult &result);
64+ bool ResolveSymbol (const void *address, SymbolResult &result) {
65+ return ResolveSymbol (reinterpret_cast <uintptr_t >(address), result);
66+ }
67+
68+ private:
69+ struct LibraryItem {
70+ uintptr_t start;
71+ uintptr_t end;
72+ std::string name;
73+ };
74+
75+ LibraryItem *FindLibrary (uintptr_t address);
76+
77+
78+ std::map<uintptr_t , LibraryItem> libraries_;
79+ };
80+ } // namespace fakelinker
0 commit comments