upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/rtti_scan.py
diff options
context:
space:
mode:
authorkotorvr <332716892+kotorvr@users.noreply.github.com>2026-11-22 20:13:36 +0000
committerkotorvr <332716892+kotorvr@users.noreply.github.com>2026-11-22 20:13:36 +0000
commit08b7920b64d6b5aad6cd99b91ef5db965114ce42 (patch)
tree74ef61a097d26a194a3d8c81af3ece060b6e3a8d /tools/rtti_scan.py
parentf847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff)
rtti_scan: read template, back-referenced and local class names; find classes local to a function
simple_name split the mangled name on '@', so a template's arguments came out as namespaces ('.?AV?$Pool@H@mem@@' was reported as 'mem::H::?$Pool'), and a back-reference digit or an anonymous namespace as a scope name. It now reads the name: scopes, templates and their arguments, back-references, anonymous namespaces and classes local to a function. A form it does not read (a pointer to a member, an address as a template argument) is reported mangled, unchanged, instead of as a made-up scope chain. The type-descriptor pattern also required the name to end with '@@'. A class declared inside a function ends with that function's 'Z@', so its descriptor, the class and its vtables were not found at all. Union descriptors ('.?AT') are matched too. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'tools/rtti_scan.py')
-rw-r--r--tools/rtti_scan.py272
1 files changed, 265 insertions, 7 deletions
diff --git a/tools/rtti_scan.py b/tools/rtti_scan.py
index 710cabc7f..876555730 100644
--- a/tools/rtti_scan.py
+++ b/tools/rtti_scan.py
@@ -102,13 +102,270 @@ def load_pe64_image(data: bytes) -> tuple[int, bytes, list[dict]]:
102 return image_base, bytes(img), sections 102 return image_base, bytes(img), sections
103 103
104 104
105_CV = {"A": (), "B": ("const",), "C": ("volatile",), "D": ("const", "volatile")}
106_BUILTIN = {"X": "void", "C": "signed char", "D": "char", "E": "unsigned char", "F": "short", "G": "unsigned short",
107 "H": "int", "I": "unsigned int", "J": "long", "K": "unsigned long", "M": "float", "N": "double",
108 "O": "long double", "_D": "__int8", "_E": "unsigned __int8", "_F": "__int16", "_G": "unsigned __int16",
109 "_H": "__int32", "_I": "unsigned __int32", "_J": "__int64", "_K": "unsigned __int64", "_L": "__int128",
110 "_M": "unsigned __int128", "_N": "bool", "_Q": "char8_t", "_S": "char16_t", "_U": "char32_t",
111 "_W": "wchar_t"}
112_OPERATOR = {"2": " new", "3": " delete", "4": "=", "5": ">>", "6": "<<", "7": "!", "8": "==", "9": "!=", "A": "[]",
113 "B": "", "C": "->", "D": "*", "E": "++", "F": "--", "G": "-", "H": "+", "I": "&", "J": "->*", "K": "/",
114 "L": "%", "M": "<", "N": "<=", "O": ">", "P": ">=", "Q": ",", "R": "()", "S": "~", "T": "^", "U": "|",
115 "V": "&&", "W": "||", "X": "*=", "Y": "+=", "Z": "-=", "_0": "/=", "_1": "%=", "_2": ">>=",
116 "_3": "<<=", "_4": "&=", "_5": "|=", "_6": "^=", "_U": " new[]", "_V": " delete[]"}
117_POINTER = {"P": " *", "Q": " * const", "R": " * volatile", "S": " * const volatile", "A": " &", "B": " & volatile"}
118_QUALIFIERS = re.compile(r"(?: const| volatile)*$")
119_LOCAL_SCOPE = re.compile(r"\?(?:\d|[B-P][A-P]*@)\?")
120
121
122class _TypeName:
123 """A reader for the part of MSVC's name mangling that a class name can contain: scopes, templates and their
124 arguments, back-references, anonymous namespaces and names local to a function. A form it does not know
125 raises ValueError (or runs off the end: IndexError); it never guesses."""
126
127 def __init__(self, text):
128 self.s, self.i = text, 0
129 self.names, self.params = [], [] # the back-reference tables: name pieces, function parameter types
130
131 def peek(self):
132 return self.s[self.i:self.i + 1]
133
134 def next(self):
135 c = self.s[self.i]
136 self.i += 1
137 return c
138
139 def eat(self, text):
140 if self.s.startswith(text, self.i):
141 self.i += len(text)
142 return True
143 return False
144
145 def number(self):
146 negative = self.eat("?")
147 c = self.next()
148 if c.isdigit():
149 value = int(c) + 1
150 else:
151 value = 0
152 while c != "@":
153 if not "A" <= c <= "P":
154 raise ValueError("bad number")
155 value = value * 16 + ord(c) - ord("A")
156 c = self.next()
157 return -value if negative else value
158
159 def memorize(self, name):
160 if name not in self.names and len(self.names) < 10:
161 self.names.append(name)
162
163 def simple(self):
164 end = self.s.index("@", self.i)
165 name = self.s[self.i:end]
166 if not name or name[0] in "?$" or name[0].isdigit():
167 raise ValueError("bad name")
168 self.i = end + 1
169 self.memorize(name)
170 return name
171
172 def piece(self):
173 """One piece of a scope chain."""
174 c = self.peek()
175 if c.isdigit():
176 self.i += 1
177 return self.names[int(c)]
178 if self.s.startswith("?$", self.i):
179 name = self.template()
180 self.memorize(name)
181 return name
182 if self.eat("?A"):
183 self.i = self.s.index("@", self.i) + 1
184 self.memorize("`anonymous namespace'")
185 return "`anonymous namespace'"
186 if _LOCAL_SCOPE.match(self.s, self.i):
187 self.i += 1
188 ordinal = self.number()
189 self.i += 1
190 return f"`{self.symbol()}'::`{ordinal}'"
191 return self.simple()
192
193 def qualified(self):
194 pieces = [self.piece()]
195 while not self.eat("@"):
196 pieces.append(self.piece())
197 return "::".join(reversed(pieces))
198
199 def template(self):
200 """`?$name@arguments@`. A template name has back-reference tables of its own."""
201 self.i += 2
202 outer = self.names, self.params
203 self.names, self.params = [], []
204 name = self.operator() if self.peek() == "?" else self.simple()
205 arguments = []
206 while not self.eat("@"):
207 if self.eat("$$$V") or self.eat("$$V") or self.eat("$$Z") or self.eat("$S"):
208 continue # an empty pack, or the boundary between two packs
209 if self.eat("$M"): # a value of a deduced (`auto`) type: the type, the value
210 self.type()
211 if not self.eat("0"):
212 raise ValueError("unknown template argument")
213 arguments.append(str(self.number()))
214 elif self.eat("$0"):
215 arguments.append(str(self.number()))
216 elif self.eat("$$Y"):
217 arguments.append(self.qualified())
218 else:
219 arguments.append(self.type())
220 self.names, self.params = outer
221 return f"{name}<{', '.join(arguments)}>"
222
223 def operator(self):
224 self.i += 1
225 code = self.next()
226 if code == "_":
227 code += self.next()
228 if code in ("0", "1"):
229 return code # constructor, destructor: named after the class
230 if code not in _OPERATOR:
231 raise ValueError("unknown special name")
232 return "operator" + _OPERATOR[code]
233
234 def symbol(self):
235 """A whole decorated function name, as a local scope holds one. Returns its qualified name; the signature
236 is read, to find where it ends, and dropped."""
237 if not self.eat("?"):
238 raise ValueError("not a symbol")
239 c = self.peek()
240 if c.isdigit():
241 self.i += 1
242 name = self.names[int(c)]
243 elif self.s.startswith("?$", self.i):
244 name = self.template()
245 elif c == "?":
246 name = self.operator()
247 else:
248 name = self.simple()
249 scope = []
250 while not self.eat("@"):
251 scope.append(self.piece())
252 if name[0] in "01":
253 if not scope:
254 raise ValueError("a constructor outside a class")
255 name = ("~" if name[0] == "1" else "") + scope[0] + name[1:]
256 kind = self.next()
257 if kind in "ABEFIJMNQRUV": # a non-static member: `this` qualifiers
258 while self.peek() in ("E", "F", "G", "H", "I"):
259 self.i += 1
260 self.cv()
261 elif kind not in "CDKLSTYZ":
262 raise ValueError("not a plain function")
263 self.signature()
264 return "::".join(scope[::-1] + [name])
265
266 def cv(self):
267 return _CV[self.next()]
268
269 def sizes(self):
270 """An array's dimensions: how many, then each."""
271 return "".join(f"[{self.number()}]" for _ in range(self.number()))
272
273 @staticmethod
274 def qualify(text, qualifiers):
275 """`text` with `const`/`volatile` after it. A const pointer is marked twice, by its own code and by the
276 qualifiers of whatever refers to it, so one that is already there is not repeated."""
277 present = _QUALIFIERS.search(text).group(0).split()
278 return text + "".join(f" {q}" for q in qualifiers if q not in present)
279
280 def signature(self):
281 """Calling convention, return type, parameters, exception specification: (return type, parameters,
282 ` noexcept` or nothing)."""
283 if not "A" <= self.next() <= "W":
284 raise ValueError("unknown calling convention")
285 result = "" if self.eat("@") else self.type()
286 parameters = []
287 if self.eat("X"):
288 parameters.append("void")
289 else:
290 while not self.eat("@"):
291 if self.eat("Z"):
292 parameters.append("...")
293 break
294 if self.peek().isdigit():
295 parameters.append(self.params[int(self.next())])
296 continue
297 start = self.i
298 parameters.append(self.type())
299 if self.i - start > 1 and len(self.params) < 10:
300 self.params.append(parameters[-1])
301 if self.eat("_E"):
302 return result, parameters, " noexcept"
303 if not self.eat("Z"):
304 raise ValueError("no exception specification")
305 return result, parameters, ""
306
307 def function(self, declarator):
308 result, parameters, noexcept = self.signature()
309 return f"{result} {declarator}({', '.join(parameters)}){noexcept}"
310
311 def indirect(self, suffix):
312 """What a pointer or reference refers to, with `suffix` (` *`, ` &`, ...) after it."""
313 unaligned = ()
314 while self.peek() in ("E", "F", "I"): # __ptr64, __unaligned, __restrict
315 if self.next() == "F":
316 unaligned = ("__unaligned",)
317 if self.eat("6"):
318 return self.function(f"({suffix.strip()})")
319 if self.eat("$A"): # a C++/CX handle
320 suffix = suffix.replace("*", "^")
321 qualifiers = self.cv()
322 if self.eat("Y"):
323 sizes = self.sizes()
324 return f"{self.qualify(self.type(), qualifiers + unaligned)} ({suffix.strip()}){sizes}"
325 return self.qualify(self.type(), qualifiers + unaligned) + suffix
326
327 def type(self):
328 if self.eat("$$Q"):
329 return self.indirect(" &&")
330 if self.eat("$$T"):
331 return "std::nullptr_t"
332 if self.eat("$$A6"):
333 return self.function("")
334 if self.eat("$$C") or self.eat("?"): # a qualified type passed by value
335 qualifiers = self.cv()
336 return self.qualify(self.type(), qualifiers)
337 if self.eat("$$BY"): # an array passed as a template argument
338 sizes = self.sizes()
339 return f"{self.type()} {sizes}"
340 c = self.next()
341 if c == "_":
342 c += self.next()
343 if c in _BUILTIN:
344 return _BUILTIN[c]
345 if c in ("T", "U", "V"):
346 return self.qualified()
347 if c == "W":
348 if not "0" <= self.next() <= "7":
349 raise ValueError("bad enum")
350 return self.qualified()
351 if c in _POINTER:
352 return self.indirect(_POINTER[c])
353 raise ValueError("unknown type")
354
355
105def simple_name(mangled: str) -> str: 356def simple_name(mangled: str) -> str:
106 """'.?AVFoo@bar@@' -> 'bar::Foo' (enough to read; full demangling isn't needed here).""" 357 """'.?AVFoo@bar@@' -> 'bar::Foo', '.?AV?$Foo@H@bar@@' -> 'bar::Foo<int>'. The `class`/`struct`/`enum` keywords,
107 m = re.match(r"\.\?A[VUW](.*)@@$", mangled) 358 calling conventions and the signature of a function that a local class sits in are left out. A name with a
108 if not m: 359 form this does not read (a member pointer or an array as a template argument, say) is returned as it is."""
360 m = re.match(r"\.\?A(?:[TUV]|W[0-7]?)", mangled)
361 if not m or not mangled.endswith("@"):
362 return mangled
363 reader = _TypeName(mangled[m.end():])
364 try:
365 name = reader.qualified()
366 except (ValueError, IndexError, KeyError, RecursionError):
109 return mangled 367 return mangled
110 parts = [p for p in m.group(1).split("@") if p] 368 return name if reader.i == len(reader.s) else mangled
111 return "::".join(reversed(parts))
112 369
113 370
114def scan_pe64_rtti(data: bytes) -> dict: 371def scan_pe64_rtti(data: bytes) -> dict:
@@ -126,9 +383,10 @@ def scan_pe64_rtti(data: bytes) -> dict:
126 def u32(rva): 383 def u32(rva):
127 return struct.unpack_from("<I", img, rva)[0] 384 return struct.unpack_from("<I", img, rva)[0]
128 385
129 # 1. Type descriptors: '.?AV' / '.?AU' / '.?AW' strings, 16 bytes after the descriptor start. 386 # 1. Type descriptors: '.?AV' / '.?AU' / '.?AW' / '.?AT' strings, 16 bytes after the descriptor start. A name
387 # ends with '@': '@@' for most, but a class local to a function ends with that function's 'Z@'.
130 tds = {} 388 tds = {}
131 for m in re.finditer(rb"\.\?A[VUW][\x21-\x7e]{1,2000}?@@\x00", img): 389 for m in re.finditer(rb"\.\?A[TUVW][\x21-\x7e]{1,2000}?@\x00", img):
132 rva = m.start() - 16 390 rva = m.start() - 16
133 if rva >= 0: 391 if rva >= 0:
134 tds[rva] = m.group(0)[:-1].decode("latin-1") 392 tds[rva] = m.group(0)[:-1].decode("latin-1")