PageRenderTime 65ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/pypy/pypy/translator/c/gcc/trackgcroot.py

https://bitbucket.org/csenger/benchmarks
Python | 1954 lines | 1817 code | 60 blank | 77 comment | 170 complexity | e4532df0809a31baa337118e84515488 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. #! /usr/bin/env python
  2. import autopath
  3. import re, sys, os, random
  4. from pypy.translator.c.gcc.instruction import Insn, Label, InsnCall, InsnRet
  5. from pypy.translator.c.gcc.instruction import InsnFunctionStart, InsnStop
  6. from pypy.translator.c.gcc.instruction import InsnSetLocal, InsnCopyLocal
  7. from pypy.translator.c.gcc.instruction import InsnPrologue, InsnEpilogue
  8. from pypy.translator.c.gcc.instruction import InsnGCROOT, InsnCondJump
  9. from pypy.translator.c.gcc.instruction import InsnStackAdjust
  10. from pypy.translator.c.gcc.instruction import InsnCannotFollowEsp
  11. from pypy.translator.c.gcc.instruction import LocalVar, somenewvalue
  12. from pypy.translator.c.gcc.instruction import frameloc_esp, frameloc_ebp
  13. from pypy.translator.c.gcc.instruction import LOC_REG, LOC_NOWHERE, LOC_MASK
  14. from pypy.translator.c.gcc.instruction import LOC_EBP_PLUS, LOC_EBP_MINUS
  15. from pypy.translator.c.gcc.instruction import LOC_ESP_PLUS
  16. class FunctionGcRootTracker(object):
  17. skip = 0
  18. COMMENT = "([#;].*)?"
  19. @classmethod
  20. def init_regexp(cls):
  21. cls.r_label = re.compile(cls.LABEL+"[:]\s*$")
  22. cls.r_globl = re.compile(r"\t[.]globl\t"+cls.LABEL+"\s*$")
  23. cls.r_globllabel = re.compile(cls.LABEL+r"=[.][+]%d\s*$"%cls.OFFSET_LABELS)
  24. cls.r_insn = re.compile(r"\t([a-z]\w*)\s")
  25. cls.r_unaryinsn = re.compile(r"\t[a-z]\w*\s+("+cls.OPERAND+")\s*" + cls.COMMENT + "$")
  26. cls.r_binaryinsn = re.compile(r"\t[a-z]\w*\s+(?P<source>"+cls.OPERAND+"),\s*(?P<target>"+cls.OPERAND+")\s*$")
  27. cls.r_jump = re.compile(r"\tj\w+\s+"+cls.LABEL+"\s*" + cls.COMMENT + "$")
  28. cls.r_jmp_switch = re.compile(r"\tjmp\t[*]"+cls.LABEL+"[(]")
  29. cls.r_jmp_source = re.compile(r"\d*[(](%[\w]+)[,)]")
  30. def __init__(self, funcname, lines, filetag=0):
  31. self.funcname = funcname
  32. self.lines = lines
  33. self.uses_frame_pointer = False
  34. self.r_localvar = self.r_localvarnofp
  35. self.filetag = filetag
  36. # a "stack bottom" function is either pypy_main_function() or a
  37. # callback from C code. In both cases they are identified by
  38. # the presence of pypy_asm_stack_bottom().
  39. self.is_stack_bottom = False
  40. def computegcmaptable(self, verbose=0):
  41. if self.funcname in ['main', '_main']:
  42. return [] # don't analyze main(), its prologue may contain
  43. # strange instructions
  44. self.findlabels()
  45. self.parse_instructions()
  46. try:
  47. self.trim_unreachable_instructions()
  48. self.find_noncollecting_calls()
  49. if not self.list_collecting_call_insns():
  50. return []
  51. self.findframesize()
  52. self.fixlocalvars()
  53. self.trackgcroots()
  54. self.extend_calls_with_labels()
  55. finally:
  56. if verbose > 2:
  57. self.dump()
  58. return self.gettable()
  59. def replace_symbols(self, operand):
  60. return operand
  61. def gettable(self):
  62. """Returns a list [(label_after_call, callshape_tuple)]
  63. See format_callshape() for more details about callshape_tuple.
  64. """
  65. table = []
  66. for insn in self.list_collecting_call_insns():
  67. if not hasattr(insn, 'framesize'):
  68. continue # calls that never end up reaching a RET
  69. if self.is_stack_bottom:
  70. retaddr = LOC_NOWHERE # end marker for asmgcroot.py
  71. elif self.uses_frame_pointer:
  72. retaddr = frameloc_ebp(self.WORD)
  73. else:
  74. retaddr = frameloc_esp(insn.framesize)
  75. shape = [retaddr]
  76. # the first gcroots are always the ones corresponding to
  77. # the callee-saved registers
  78. for reg in self.CALLEE_SAVE_REGISTERS:
  79. shape.append(LOC_NOWHERE)
  80. gcroots = []
  81. for localvar, tag in insn.gcroots.items():
  82. if isinstance(localvar, LocalVar):
  83. loc = localvar.getlocation(insn.framesize,
  84. self.uses_frame_pointer,
  85. self.WORD)
  86. elif localvar in self.REG2LOC:
  87. loc = self.REG2LOC[localvar]
  88. else:
  89. assert False, "%s: %s" % (self.funcname,
  90. localvar)
  91. assert isinstance(loc, int)
  92. if tag is None:
  93. gcroots.append(loc)
  94. else:
  95. regindex = self.CALLEE_SAVE_REGISTERS.index(tag)
  96. shape[1 + regindex] = loc
  97. if LOC_NOWHERE in shape and not self.is_stack_bottom:
  98. reg = self.CALLEE_SAVE_REGISTERS[shape.index(LOC_NOWHERE) - 1]
  99. raise AssertionError("cannot track where register %s is saved"
  100. % (reg,))
  101. gcroots.sort()
  102. shape.extend(gcroots)
  103. table.append((insn.global_label, tuple(shape)))
  104. return table
  105. def findlabels(self):
  106. self.labels = {} # {name: Label()}
  107. for lineno, line in enumerate(self.lines):
  108. match = self.r_label.match(line)
  109. label = None
  110. if match:
  111. label = match.group(1)
  112. else:
  113. # labels used by: j* NNNf
  114. match = self.r_rel_label.match(line)
  115. if match:
  116. label = "rel %d" % lineno
  117. if label:
  118. assert label not in self.labels, "duplicate label: %s" % label
  119. self.labels[label] = Label(label, lineno)
  120. def trim_unreachable_instructions(self):
  121. reached = set([self.insns[0]])
  122. prevlen = 0
  123. while len(reached) > prevlen:
  124. prevlen = len(reached)
  125. for insn in self.insns:
  126. if insn not in reached:
  127. for previnsn in insn.previous_insns:
  128. if previnsn in reached:
  129. # this instruction is reachable too
  130. reached.add(insn)
  131. break
  132. # now kill all unreachable instructions
  133. i = 0
  134. while i < len(self.insns):
  135. if self.insns[i] in reached:
  136. i += 1
  137. else:
  138. del self.insns[i]
  139. def find_noncollecting_calls(self):
  140. cannot_collect = {}
  141. for line in self.lines:
  142. match = self.r_gcnocollect_marker.search(line)
  143. if match:
  144. name = match.group(1)
  145. cannot_collect[name] = True
  146. #
  147. self.cannot_collect = dict.fromkeys(
  148. [self.function_names_prefix + name for name in cannot_collect])
  149. def append_instruction(self, insn):
  150. # Add the instruction to the list, and link it to the previous one.
  151. previnsn = self.insns[-1]
  152. self.insns.append(insn)
  153. try:
  154. lst = insn.previous_insns
  155. except AttributeError:
  156. lst = insn.previous_insns = []
  157. if not isinstance(previnsn, InsnStop):
  158. lst.append(previnsn)
  159. def parse_instructions(self):
  160. self.insns = [InsnFunctionStart(self.CALLEE_SAVE_REGISTERS, self.WORD)]
  161. ignore_insns = False
  162. for lineno, line in enumerate(self.lines):
  163. if lineno < self.skip:
  164. continue
  165. self.currentlineno = lineno
  166. insn = []
  167. match = self.r_insn.match(line)
  168. if self.r_bottom_marker.match(line):
  169. self.is_stack_bottom = True
  170. elif match:
  171. if not ignore_insns:
  172. opname = match.group(1)
  173. try:
  174. meth = getattr(self, 'visit_' + opname)
  175. except AttributeError:
  176. self.find_missing_visit_method(opname)
  177. meth = getattr(self, 'visit_' + opname)
  178. line = line.rsplit(';', 1)[0]
  179. insn = meth(line)
  180. elif self.r_gcroot_marker.match(line):
  181. insn = self._visit_gcroot_marker(line)
  182. elif line == '\t/* ignore_in_trackgcroot */\n':
  183. ignore_insns = True
  184. elif line == '\t/* end_ignore_in_trackgcroot */\n':
  185. ignore_insns = False
  186. else:
  187. match = self.r_label.match(line)
  188. if match:
  189. insn = self.labels[match.group(1)]
  190. if isinstance(insn, list):
  191. for i in insn:
  192. self.append_instruction(i)
  193. else:
  194. self.append_instruction(insn)
  195. del self.currentlineno
  196. @classmethod
  197. def find_missing_visit_method(cls, opname):
  198. # only for operations that are no-ops as far as we are concerned
  199. prefix = opname
  200. while prefix not in cls.IGNORE_OPS_WITH_PREFIXES:
  201. prefix = prefix[:-1]
  202. if not prefix:
  203. raise UnrecognizedOperation(opname)
  204. setattr(cls, 'visit_' + opname, cls.visit_nop)
  205. def list_collecting_call_insns(self):
  206. return [insn for insn in self.insns if isinstance(insn, InsnCall)
  207. if insn.name not in self.cannot_collect]
  208. def findframesize(self):
  209. # the 'framesize' attached to an instruction is the number of bytes
  210. # in the frame at this point. This doesn't count the return address
  211. # which is the word immediately following the frame in memory.
  212. # The 'framesize' is set to an odd value if it is only an estimate
  213. # (see InsnCannotFollowEsp).
  214. def walker(insn, size_delta):
  215. check = deltas.setdefault(insn, size_delta)
  216. assert check == size_delta, (
  217. "inconsistent frame size at instruction %s" % (insn,))
  218. if isinstance(insn, InsnStackAdjust):
  219. size_delta -= insn.delta
  220. if not hasattr(insn, 'framesize'):
  221. yield size_delta # continue walking backwards
  222. for insn in self.insns:
  223. if isinstance(insn, (InsnRet, InsnEpilogue, InsnGCROOT)):
  224. deltas = {}
  225. self.walk_instructions_backwards(walker, insn, 0)
  226. size_at_insn = []
  227. for insn1, delta1 in deltas.items():
  228. if hasattr(insn1, 'framesize'):
  229. size_at_insn.append(insn1.framesize + delta1)
  230. if not size_at_insn:
  231. continue
  232. size_at_insn = size_at_insn[0]
  233. for insn1, delta1 in deltas.items():
  234. size_at_insn1 = size_at_insn - delta1
  235. if hasattr(insn1, 'framesize'):
  236. assert insn1.framesize == size_at_insn1, (
  237. "inconsistent frame size at instruction %s" %
  238. (insn1,))
  239. else:
  240. insn1.framesize = size_at_insn1
  241. def fixlocalvars(self):
  242. def fixvar(localvar):
  243. if localvar is None:
  244. return None
  245. elif isinstance(localvar, (list, tuple)):
  246. return [fixvar(var) for var in localvar]
  247. match = self.r_localvar_esp.match(localvar)
  248. if match:
  249. if localvar == self.TOP_OF_STACK_MINUS_WORD:
  250. # for pushl and popl, by
  251. hint = None # default ebp addressing is
  252. else: # a bit nicer
  253. hint = 'esp'
  254. ofs_from_esp = int(match.group(1) or '0')
  255. if self.format == 'msvc':
  256. ofs_from_esp += int(match.group(2) or '0')
  257. localvar = ofs_from_esp - insn.framesize
  258. assert localvar != 0 # that's the return address
  259. return LocalVar(localvar, hint=hint)
  260. elif self.uses_frame_pointer:
  261. match = self.r_localvar_ebp.match(localvar)
  262. if match:
  263. ofs_from_ebp = int(match.group(1) or '0')
  264. if self.format == 'msvc':
  265. ofs_from_ebp += int(match.group(2) or '0')
  266. localvar = ofs_from_ebp - self.WORD
  267. assert localvar != 0 # that's the return address
  268. return LocalVar(localvar, hint='ebp')
  269. return localvar
  270. for insn in self.insns:
  271. if not hasattr(insn, 'framesize'):
  272. continue
  273. for name in insn._locals_:
  274. localvar = getattr(insn, name)
  275. setattr(insn, name, fixvar(localvar))
  276. def trackgcroots(self):
  277. def walker(insn, loc):
  278. source = insn.source_of(loc, tag)
  279. if source is somenewvalue:
  280. pass # done
  281. else:
  282. yield source
  283. for insn in self.insns:
  284. for loc, tag in insn.requestgcroots(self).items():
  285. self.walk_instructions_backwards(walker, insn, loc)
  286. def dump(self):
  287. for insn in self.insns:
  288. size = getattr(insn, 'framesize', '?')
  289. print >> sys.stderr, '%4s %s' % (size, insn)
  290. def walk_instructions_backwards(self, walker, initial_insn, initial_state):
  291. pending = []
  292. seen = {}
  293. def schedule(insn, state):
  294. for previnsn in insn.previous_insns:
  295. key = previnsn, state
  296. if key not in seen:
  297. seen[key] = True
  298. pending.append(key)
  299. schedule(initial_insn, initial_state)
  300. while pending:
  301. insn, state = pending.pop()
  302. for prevstate in walker(insn, state):
  303. schedule(insn, prevstate)
  304. def extend_calls_with_labels(self):
  305. # walk backwards, because inserting the global labels in self.lines
  306. # is going to invalidate the lineno of all the InsnCall objects
  307. # after the current one.
  308. for call in self.list_collecting_call_insns()[::-1]:
  309. if hasattr(call, 'framesize'):
  310. self.create_global_label(call)
  311. def create_global_label(self, call):
  312. # we need a globally-declared label just after the call.
  313. # Reuse one if it is already there (e.g. from a previous run of this
  314. # script); otherwise invent a name and add the label to tracker.lines.
  315. label = None
  316. # this checks for a ".globl NAME" followed by "NAME:"
  317. match = self.r_globl.match(self.lines[call.lineno+1])
  318. if match:
  319. label1 = match.group(1)
  320. match = self.r_globllabel.match(self.lines[call.lineno+2])
  321. if match:
  322. label2 = match.group(1)
  323. if label1 == label2:
  324. label = label2
  325. if label is None:
  326. k = call.lineno
  327. if self.format == 'msvc':
  328. # Some header files (ws2tcpip.h) define STDCALL functions
  329. funcname = self.funcname.split('@')[0]
  330. else:
  331. funcname = self.funcname
  332. while 1:
  333. label = '__gcmap_%s__%s_%d' % (self.filetag, funcname, k)
  334. if label not in self.labels:
  335. break
  336. k += 1
  337. self.labels[label] = None
  338. if self.format == 'msvc':
  339. self.lines.insert(call.lineno+1, '%s::\n' % (label,))
  340. self.lines.insert(call.lineno+1, 'PUBLIC\t%s\n' % (label,))
  341. else:
  342. # These global symbols are not directly labels pointing to the
  343. # code location because such global labels in the middle of
  344. # functions confuse gdb. Instead, we add to the global symbol's
  345. # value a big constant, which is subtracted again when we need
  346. # the original value for gcmaptable.s. That's a hack.
  347. self.lines.insert(call.lineno+1, '%s=.+%d\n' % (label,
  348. self.OFFSET_LABELS))
  349. self.lines.insert(call.lineno+1, '\t.globl\t%s\n' % (label,))
  350. call.global_label = label
  351. @classmethod
  352. def compress_callshape(cls, shape):
  353. # For a single shape, this turns the list of integers into a list of
  354. # bytes and reverses the order of the entries. The length is
  355. # encoded by inserting a 0 marker after the gc roots coming from
  356. # shape[N:] and before the N values coming from shape[N-1] to
  357. # shape[0] (for N == 5 on 32-bit or 7 on 64-bit platforms).
  358. # In practice it seems that shapes contain many integers
  359. # whose value is up to a few thousands, which the algorithm below
  360. # compresses down to 2 bytes. Very small values compress down to a
  361. # single byte.
  362. # Callee-save regs plus ret addr
  363. min_size = len(cls.CALLEE_SAVE_REGISTERS) + 1
  364. assert len(shape) >= min_size
  365. shape = list(shape)
  366. assert 0 not in shape[min_size:]
  367. shape.insert(min_size, 0)
  368. result = []
  369. for loc in shape:
  370. assert loc >= 0
  371. flag = 0
  372. while loc >= 0x80:
  373. result.append(int(loc & 0x7F) | flag)
  374. flag = 0x80
  375. loc >>= 7
  376. result.append(int(loc) | flag)
  377. result.reverse()
  378. return result
  379. @classmethod
  380. def decompress_callshape(cls, bytes):
  381. # For tests. This logic is copied in asmgcroot.py.
  382. result = []
  383. n = 0
  384. while n < len(bytes):
  385. value = 0
  386. while True:
  387. b = bytes[n]
  388. n += 1
  389. value += b
  390. if b < 0x80:
  391. break
  392. value = (value - 0x80) << 7
  393. result.append(value)
  394. result.reverse()
  395. assert result[5] == 0
  396. del result[5]
  397. return result
  398. # ____________________________________________________________
  399. BASE_FUNCTIONS_NOT_RETURNING = {
  400. 'abort': None,
  401. 'pypy_debug_catch_fatal_exception': None,
  402. 'RPyAbort': None,
  403. 'RPyAssertFailed': None,
  404. }
  405. def _visit_gcroot_marker(self, line):
  406. match = self.r_gcroot_marker.match(line)
  407. loc = match.group(1)
  408. return InsnGCROOT(self.replace_symbols(loc))
  409. def visit_nop(self, line):
  410. return []
  411. IGNORE_OPS_WITH_PREFIXES = dict.fromkeys([
  412. 'cmp', 'test', 'set', 'sahf', 'lahf', 'cltd', 'cld', 'std',
  413. 'rep', 'movs', 'lods', 'stos', 'scas', 'cwtl', 'cwde', 'prefetch',
  414. # floating-point operations cannot produce GC pointers
  415. 'f',
  416. 'cvt', 'ucomi', 'comi', 'subs', 'subp' , 'adds', 'addp', 'xorp',
  417. 'movap', 'movd', 'movlp', 'sqrtsd', 'movhpd',
  418. 'mins', 'minp', 'maxs', 'maxp', 'unpck', 'pxor', 'por', # sse2
  419. # arithmetic operations should not produce GC pointers
  420. 'inc', 'dec', 'not', 'neg', 'or', 'and', 'sbb', 'adc',
  421. 'shl', 'shr', 'sal', 'sar', 'rol', 'ror', 'mul', 'imul', 'div', 'idiv',
  422. 'bswap', 'bt', 'rdtsc',
  423. 'punpck', 'pshufd', 'pcmp', 'pand', 'psllw', 'pslld', 'psllq',
  424. 'paddq', 'pinsr',
  425. # zero-extending moves should not produce GC pointers
  426. 'movz',
  427. ])
  428. visit_movb = visit_nop
  429. visit_movw = visit_nop
  430. visit_addb = visit_nop
  431. visit_addw = visit_nop
  432. visit_subb = visit_nop
  433. visit_subw = visit_nop
  434. visit_xorb = visit_nop
  435. visit_xorw = visit_nop
  436. def _visit_add(self, line, sign=+1):
  437. match = self.r_binaryinsn.match(line)
  438. source = match.group("source")
  439. target = match.group("target")
  440. if target == self.ESP:
  441. count = self.extract_immediate(source)
  442. if count is None:
  443. # strange instruction - I've seen 'subl %eax, %esp'
  444. return InsnCannotFollowEsp()
  445. return InsnStackAdjust(sign * count)
  446. elif self.r_localvar.match(target):
  447. return InsnSetLocal(target, [source, target])
  448. else:
  449. return []
  450. def _visit_sub(self, line):
  451. return self._visit_add(line, sign=-1)
  452. def unary_insn(self, line):
  453. match = self.r_unaryinsn.match(line)
  454. target = match.group(1)
  455. if self.r_localvar.match(target):
  456. return InsnSetLocal(target)
  457. else:
  458. return []
  459. def binary_insn(self, line):
  460. match = self.r_binaryinsn.match(line)
  461. if not match:
  462. raise UnrecognizedOperation(line)
  463. source = match.group("source")
  464. target = match.group("target")
  465. if self.r_localvar.match(target):
  466. return InsnSetLocal(target, [source])
  467. elif target == self.ESP:
  468. raise UnrecognizedOperation(line)
  469. else:
  470. return []
  471. # The various cmov* operations
  472. for name in '''
  473. e ne g ge l le a ae b be p np s ns o no
  474. '''.split():
  475. locals()['visit_cmov' + name] = binary_insn
  476. locals()['visit_cmov' + name + 'l'] = binary_insn
  477. def _visit_and(self, line):
  478. match = self.r_binaryinsn.match(line)
  479. target = match.group("target")
  480. if target == self.ESP:
  481. # only for andl $-16, %esp used to align the stack in main().
  482. # main() should not be seen at all. But on e.g. MSVC we see
  483. # the instruction somewhere else too...
  484. return InsnCannotFollowEsp()
  485. else:
  486. return self.binary_insn(line)
  487. def _visit_lea(self, line):
  488. match = self.r_binaryinsn.match(line)
  489. target = match.group("target")
  490. if target == self.ESP:
  491. # only for leal -12(%ebp), %esp in function epilogues
  492. source = match.group("source")
  493. match = self.r_localvar_ebp.match(source)
  494. if match:
  495. if not self.uses_frame_pointer:
  496. raise UnrecognizedOperation('epilogue without prologue')
  497. ofs_from_ebp = int(match.group(1) or '0')
  498. assert ofs_from_ebp <= 0
  499. framesize = self.WORD - ofs_from_ebp
  500. else:
  501. match = self.r_localvar_esp.match(source)
  502. # leal 12(%esp), %esp
  503. if match:
  504. return InsnStackAdjust(int(match.group(1)))
  505. framesize = None # strange instruction
  506. return InsnEpilogue(framesize)
  507. else:
  508. return self.binary_insn(line)
  509. def insns_for_copy(self, source, target):
  510. source = self.replace_symbols(source)
  511. target = self.replace_symbols(target)
  512. if target == self.ESP:
  513. raise UnrecognizedOperation('%s -> %s' % (source, target))
  514. elif self.r_localvar.match(target):
  515. if self.r_localvar.match(source):
  516. # eg, movl %eax, %ecx: possibly copies a GC root
  517. return [InsnCopyLocal(source, target)]
  518. else:
  519. # eg, movl (%eax), %edi or mov %esp, %edi: load a register
  520. # from "outside". If it contains a pointer to a GC root,
  521. # it will be announced later with the GCROOT macro.
  522. return [InsnSetLocal(target, [source])]
  523. else:
  524. # eg, movl %ebx, (%edx) or mov %ebp, %esp: does not write into
  525. # a general register
  526. return []
  527. def _visit_mov(self, line):
  528. match = self.r_binaryinsn.match(line)
  529. source = match.group("source")
  530. target = match.group("target")
  531. if source == self.ESP and target == self.EBP:
  532. return self._visit_prologue()
  533. elif source == self.EBP and target == self.ESP:
  534. return self._visit_epilogue()
  535. if source == self.ESP and self.funcname.startswith('VALGRIND_'):
  536. return [] # in VALGRIND_XXX functions, there is a dummy-looking
  537. # mov %esp, %eax. Shows up only when compiling with
  538. # gcc -fno-unit-at-a-time.
  539. return self.insns_for_copy(source, target)
  540. def _visit_push(self, line):
  541. match = self.r_unaryinsn.match(line)
  542. source = match.group(1)
  543. return self.insns_for_copy(source, self.TOP_OF_STACK_MINUS_WORD) + \
  544. [InsnStackAdjust(-self.WORD)]
  545. def _visit_pop(self, target):
  546. return [InsnStackAdjust(+self.WORD)] + \
  547. self.insns_for_copy(self.TOP_OF_STACK_MINUS_WORD, target)
  548. def _visit_prologue(self):
  549. # for the prologue of functions that use %ebp as frame pointer
  550. self.uses_frame_pointer = True
  551. self.r_localvar = self.r_localvarfp
  552. return [InsnPrologue(self.WORD)]
  553. def _visit_epilogue(self):
  554. if not self.uses_frame_pointer:
  555. raise UnrecognizedOperation('epilogue without prologue')
  556. return [InsnEpilogue(self.WORD)]
  557. def visit_leave(self, line):
  558. return self._visit_epilogue() + self._visit_pop(self.EBP)
  559. def visit_ret(self, line):
  560. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  561. def visit_jmp(self, line):
  562. tablelabels = []
  563. match = self.r_jmp_switch.match(line)
  564. if match:
  565. # this is a jmp *Label(%index), used for table-based switches.
  566. # Assume that the table is just a list of lines looking like
  567. # .long LABEL or .long 0, ending in a .text or .section .text.hot.
  568. tablelabels.append(match.group(1))
  569. elif self.r_unaryinsn_star.match(line):
  570. # maybe a jmp similar to the above, but stored in a
  571. # registry:
  572. # movl L9341(%eax), %eax
  573. # jmp *%eax
  574. operand = self.r_unaryinsn_star.match(line).group(1)
  575. def walker(insn, locs):
  576. sources = []
  577. for loc in locs:
  578. for s in insn.all_sources_of(loc):
  579. # if the source looks like 8(%eax,%edx,4)
  580. # %eax is the real source, %edx is an offset.
  581. match = self.r_jmp_source.match(s)
  582. if match and not self.r_localvar_esp.match(s):
  583. sources.append(match.group(1))
  584. else:
  585. sources.append(s)
  586. for source in sources:
  587. label_match = re.compile(self.LABEL).match(source)
  588. if label_match:
  589. tablelabels.append(label_match.group(0))
  590. return
  591. yield tuple(sources)
  592. insn = InsnStop()
  593. insn.previous_insns = [self.insns[-1]]
  594. self.walk_instructions_backwards(walker, insn, (operand,))
  595. # Remove probable tail-calls
  596. tablelabels = [label for label in tablelabels
  597. if label in self.labels]
  598. assert len(tablelabels) <= 1
  599. if tablelabels:
  600. tablelin = self.labels[tablelabels[0]].lineno + 1
  601. while not self.r_jmptable_end.match(self.lines[tablelin]):
  602. # skip empty lines
  603. if (not self.lines[tablelin].strip()
  604. or self.lines[tablelin].startswith(';')):
  605. tablelin += 1
  606. continue
  607. match = self.r_jmptable_item.match(self.lines[tablelin])
  608. if not match:
  609. raise NoPatternMatch(repr(self.lines[tablelin]))
  610. label = match.group(1)
  611. if label != '0':
  612. self.register_jump_to(label)
  613. tablelin += 1
  614. return InsnStop("jump table")
  615. if self.r_unaryinsn_star.match(line):
  616. # that looks like an indirect tail-call.
  617. # tail-calls are equivalent to RET for us
  618. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  619. try:
  620. self.conditional_jump(line)
  621. except KeyError:
  622. # label not found: check if it's a tail-call turned into a jump
  623. match = self.r_unaryinsn.match(line)
  624. target = match.group(1)
  625. assert not target.startswith('.')
  626. # tail-calls are equivalent to RET for us
  627. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  628. return InsnStop("jump")
  629. def register_jump_to(self, label):
  630. if not isinstance(self.insns[-1], InsnStop):
  631. self.labels[label].previous_insns.append(self.insns[-1])
  632. def conditional_jump(self, line):
  633. match = self.r_jump.match(line)
  634. if not match:
  635. match = self.r_jump_rel_label.match(line)
  636. if not match:
  637. raise UnrecognizedOperation(line)
  638. # j* NNNf
  639. label = match.group(1)
  640. label += ":"
  641. i = self.currentlineno + 1
  642. while True:
  643. if self.lines[i].startswith(label):
  644. label = "rel %d" % i
  645. break
  646. i += 1
  647. else:
  648. label = match.group(1)
  649. self.register_jump_to(label)
  650. return [InsnCondJump(label)]
  651. visit_jmpl = visit_jmp
  652. visit_je = conditional_jump
  653. visit_jne = conditional_jump
  654. visit_jg = conditional_jump
  655. visit_jge = conditional_jump
  656. visit_jl = conditional_jump
  657. visit_jle = conditional_jump
  658. visit_ja = conditional_jump
  659. visit_jae = conditional_jump
  660. visit_jb = conditional_jump
  661. visit_jbe = conditional_jump
  662. visit_jp = conditional_jump
  663. visit_jnp = conditional_jump
  664. visit_js = conditional_jump
  665. visit_jns = conditional_jump
  666. visit_jo = conditional_jump
  667. visit_jno = conditional_jump
  668. visit_jc = conditional_jump
  669. visit_jnc = conditional_jump
  670. def _visit_xchg(self, line):
  671. # only support the format used in VALGRIND_DISCARD_TRANSLATIONS
  672. # which is to use a marker no-op "xchgl %ebx, %ebx"
  673. match = self.r_binaryinsn.match(line)
  674. source = match.group("source")
  675. target = match.group("target")
  676. if source == target:
  677. return []
  678. raise UnrecognizedOperation(line)
  679. def visit_call(self, line):
  680. match = self.r_unaryinsn.match(line)
  681. if match is None:
  682. assert self.r_unaryinsn_star.match(line) # indirect call
  683. return [InsnCall('<indirect>', self.currentlineno),
  684. InsnSetLocal(self.EAX)] # the result is there
  685. target = match.group(1)
  686. if self.format in ('msvc',):
  687. # On win32, the address of a foreign function must be
  688. # computed, the optimizer may store it in a register. We
  689. # could ignore this, except when the function need special
  690. # processing (not returning, __stdcall...)
  691. def find_register(target):
  692. reg = []
  693. def walker(insn, locs):
  694. sources = []
  695. for loc in locs:
  696. for s in insn.all_sources_of(loc):
  697. sources.append(s)
  698. for source in sources:
  699. m = re.match("DWORD PTR " + self.LABEL, source)
  700. if m:
  701. reg.append(m.group(1))
  702. if reg:
  703. return
  704. yield tuple(sources)
  705. insn = InsnStop()
  706. insn.previous_insns = [self.insns[-1]]
  707. self.walk_instructions_backwards(walker, insn, (target,))
  708. return reg
  709. if match and self.r_localvarfp.match(target):
  710. sources = find_register(target)
  711. if sources:
  712. target, = sources
  713. if target in self.FUNCTIONS_NOT_RETURNING:
  714. return [InsnStop(target)]
  715. if self.format == 'mingw32' and target == '__alloca':
  716. # in functions with large stack requirements, windows
  717. # needs a call to _alloca(), to turn reserved pages
  718. # into committed memory.
  719. # With mingw32 gcc at least, %esp is not used before
  720. # this call. So we don't bother to compute the exact
  721. # stack effect.
  722. return [InsnCannotFollowEsp()]
  723. if target in self.labels:
  724. lineoffset = self.labels[target].lineno - self.currentlineno
  725. if lineoffset >= 0:
  726. assert lineoffset in (1,2)
  727. return [InsnStackAdjust(-4)]
  728. insns = [InsnCall(target, self.currentlineno),
  729. InsnSetLocal(self.EAX)] # the result is there
  730. if self.format in ('mingw32', 'msvc'):
  731. # handle __stdcall calling convention:
  732. # Stack cleanup is performed by the called function,
  733. # Function name is decorated with "@N" where N is the stack size
  734. if '@' in target and not target.startswith('@'):
  735. insns.append(InsnStackAdjust(int(target.rsplit('@', 1)[1])))
  736. # Some (intrinsic?) functions use the "fastcall" calling convention
  737. # XXX without any declaration, how can we guess the stack effect?
  738. if target in ['__alldiv', '__allrem', '__allmul', '__alldvrm',
  739. '__aulldiv', '__aullrem', '__aullmul', '__aulldvrm']:
  740. insns.append(InsnStackAdjust(16))
  741. return insns
  742. # __________ debugging output __________
  743. @classmethod
  744. def format_location(cls, loc):
  745. # A 'location' is a single number describing where a value is stored
  746. # across a call. It can be in one of the CALLEE_SAVE_REGISTERS, or
  747. # in the stack frame at an address relative to either %esp or %ebp.
  748. # The last two bits of the location number are used to tell the cases
  749. # apart; see format_location().
  750. assert loc >= 0
  751. kind = loc & LOC_MASK
  752. if kind == LOC_REG:
  753. if loc == LOC_NOWHERE:
  754. return '?'
  755. reg = (loc >> 2) - 1
  756. return '%' + cls.CALLEE_SAVE_REGISTERS[reg].replace("%", "")
  757. else:
  758. offset = loc & ~ LOC_MASK
  759. if kind == LOC_EBP_PLUS:
  760. result = '(%' + cls.EBP.replace("%", "") + ')'
  761. elif kind == LOC_EBP_MINUS:
  762. result = '(%' + cls.EBP.replace("%", "") + ')'
  763. offset = -offset
  764. elif kind == LOC_ESP_PLUS:
  765. result = '(%' + cls.ESP.replace("%", "") + ')'
  766. else:
  767. assert 0, kind
  768. if offset != 0:
  769. result = str(offset) + result
  770. return result
  771. @classmethod
  772. def format_callshape(cls, shape):
  773. # A 'call shape' is a tuple of locations in the sense of
  774. # format_location(). They describe where in a function frame
  775. # interesting values are stored, when this function executes a 'call'
  776. # instruction.
  777. #
  778. # shape[0] is the location that stores the fn's own return
  779. # address (not the return address for the currently
  780. # executing 'call')
  781. #
  782. # shape[1..N] is where the fn saved its own caller's value of a
  783. # certain callee save register. (where N is the number
  784. # of callee save registers.)
  785. #
  786. # shape[>N] are GC roots: where the fn has put its local GCPTR
  787. # vars
  788. #
  789. num_callee_save_regs = len(cls.CALLEE_SAVE_REGISTERS)
  790. assert isinstance(shape, tuple)
  791. # + 1 for the return address
  792. assert len(shape) >= (num_callee_save_regs + 1)
  793. result = [cls.format_location(loc) for loc in shape]
  794. return '{%s | %s | %s}' % (result[0],
  795. ', '.join(result[1:(num_callee_save_regs+1)]),
  796. ', '.join(result[(num_callee_save_regs+1):]))
  797. class FunctionGcRootTracker32(FunctionGcRootTracker):
  798. WORD = 4
  799. visit_mov = FunctionGcRootTracker._visit_mov
  800. visit_movl = FunctionGcRootTracker._visit_mov
  801. visit_pushl = FunctionGcRootTracker._visit_push
  802. visit_leal = FunctionGcRootTracker._visit_lea
  803. visit_addl = FunctionGcRootTracker._visit_add
  804. visit_subl = FunctionGcRootTracker._visit_sub
  805. visit_andl = FunctionGcRootTracker._visit_and
  806. visit_and = FunctionGcRootTracker._visit_and
  807. visit_xchgl = FunctionGcRootTracker._visit_xchg
  808. # used in "xor reg, reg" to create a NULL GC ptr
  809. visit_xorl = FunctionGcRootTracker.binary_insn
  810. visit_orl = FunctionGcRootTracker.binary_insn # unsure about this one
  811. # occasionally used on 32-bits to move floats around
  812. visit_movq = FunctionGcRootTracker.visit_nop
  813. def visit_pushw(self, line):
  814. return [InsnStackAdjust(-2)] # rare but not impossible
  815. def visit_popl(self, line):
  816. match = self.r_unaryinsn.match(line)
  817. target = match.group(1)
  818. return self._visit_pop(target)
  819. class FunctionGcRootTracker64(FunctionGcRootTracker):
  820. WORD = 8
  821. # Regex ignores destination
  822. r_save_xmm_register = re.compile(r"\tmovaps\s+%xmm(\d+)")
  823. def _maybe_32bit_dest(func):
  824. def wrapper(self, line):
  825. # Using a 32-bit reg as a destination in 64-bit mode zero-extends
  826. # to 64-bits, so sometimes gcc uses a 32-bit operation to copy a
  827. # statically known pointer to a register
  828. # %eax -> %rax
  829. new_line = re.sub(r"%e(ax|bx|cx|dx|di|si|bp)$", r"%r\1", line)
  830. # %r10d -> %r10
  831. new_line = re.sub(r"%r(\d+)d$", r"%r\1", new_line)
  832. return func(self, new_line)
  833. return wrapper
  834. visit_addl = FunctionGcRootTracker.visit_nop
  835. visit_subl = FunctionGcRootTracker.visit_nop
  836. visit_leal = FunctionGcRootTracker.visit_nop
  837. visit_cltq = FunctionGcRootTracker.visit_nop
  838. visit_movq = FunctionGcRootTracker._visit_mov
  839. # just a special assembler mnemonic for mov
  840. visit_movabsq = FunctionGcRootTracker._visit_mov
  841. visit_mov = _maybe_32bit_dest(FunctionGcRootTracker._visit_mov)
  842. visit_movl = visit_mov
  843. visit_xorl = _maybe_32bit_dest(FunctionGcRootTracker.binary_insn)
  844. visit_pushq = FunctionGcRootTracker._visit_push
  845. visit_addq = FunctionGcRootTracker._visit_add
  846. visit_subq = FunctionGcRootTracker._visit_sub
  847. visit_leaq = FunctionGcRootTracker._visit_lea
  848. visit_xorq = FunctionGcRootTracker.binary_insn
  849. visit_xchgq = FunctionGcRootTracker._visit_xchg
  850. # FIXME: similar to visit_popl for 32-bit
  851. def visit_popq(self, line):
  852. match = self.r_unaryinsn.match(line)
  853. target = match.group(1)
  854. return self._visit_pop(target)
  855. def visit_jmp(self, line):
  856. # On 64-bit, %al is used when calling varargs functions to specify an
  857. # upper-bound on the number of xmm registers used in the call. gcc
  858. # uses %al to compute an indirect jump that looks like:
  859. #
  860. # jmp *[some register]
  861. # movaps %xmm7, [stack location]
  862. # movaps %xmm6, [stack location]
  863. # movaps %xmm5, [stack location]
  864. # movaps %xmm4, [stack location]
  865. # movaps %xmm3, [stack location]
  866. # movaps %xmm2, [stack location]
  867. # movaps %xmm1, [stack location]
  868. # movaps %xmm0, [stack location]
  869. #
  870. # The jmp is always to somewhere in the block of "movaps"
  871. # instructions, according to how many xmm registers need to be saved
  872. # to the stack. The point of all this is that we can safely ignore
  873. # jmp instructions of that form.
  874. if (self.currentlineno + 8) < len(self.lines) and self.r_unaryinsn_star.match(line):
  875. matches = [self.r_save_xmm_register.match(self.lines[self.currentlineno + 1 + i]) for i in range(8)]
  876. if all(m and int(m.group(1)) == (7 - i) for i, m in enumerate(matches)):
  877. return []
  878. return FunctionGcRootTracker.visit_jmp(self, line)
  879. class ElfFunctionGcRootTracker32(FunctionGcRootTracker32):
  880. format = 'elf'
  881. function_names_prefix = ''
  882. ESP = '%esp'
  883. EBP = '%ebp'
  884. EAX = '%eax'
  885. CALLEE_SAVE_REGISTERS = ['%ebx', '%esi', '%edi', '%ebp']
  886. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  887. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  888. OPERAND = r'(?:[-\w$%+.:@"]+(?:[(][\w%,]+[)])?|[(][\w%,]+[)])'
  889. LABEL = r'([a-zA-Z_$.][a-zA-Z0-9_$@.]*)'
  890. OFFSET_LABELS = 2**30
  891. TOP_OF_STACK_MINUS_WORD = '-4(%esp)'
  892. r_functionstart = re.compile(r"\t.type\s+"+LABEL+",\s*[@]function\s*$")
  893. r_functionend = re.compile(r"\t.size\s+"+LABEL+",\s*[.]-"+LABEL+"\s*$")
  894. LOCALVAR = r"%eax|%edx|%ecx|%ebx|%esi|%edi|%ebp|-?\d*[(]%esp[)]"
  895. LOCALVARFP = LOCALVAR + r"|-?\d*[(]%ebp[)]"
  896. r_localvarnofp = re.compile(LOCALVAR)
  897. r_localvarfp = re.compile(LOCALVARFP)
  898. r_localvar_esp = re.compile(r"(-?\d*)[(]%esp[)]")
  899. r_localvar_ebp = re.compile(r"(-?\d*)[(]%ebp[)]")
  900. r_rel_label = re.compile(r"(\d+):\s*$")
  901. r_jump_rel_label = re.compile(r"\tj\w+\s+"+"(\d+)f"+"\s*$")
  902. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+[*]("+OPERAND+")\s*$")
  903. r_jmptable_item = re.compile(r"\t.long\t"+LABEL+"(-\"[A-Za-z0-9$]+\")?\s*$")
  904. r_jmptable_end = re.compile(r"\t.text|\t.section\s+.text|\t\.align|"+LABEL)
  905. r_gcroot_marker = re.compile(r"\t/[*] GCROOT ("+LOCALVARFP+") [*]/")
  906. r_gcnocollect_marker = re.compile(r"\t/[*] GC_NOCOLLECT ("+OPERAND+") [*]/")
  907. r_bottom_marker = re.compile(r"\t/[*] GC_STACK_BOTTOM [*]/")
  908. FUNCTIONS_NOT_RETURNING = {
  909. '_exit': None,
  910. '__assert_fail': None,
  911. '___assert_rtn': None,
  912. 'L___assert_rtn$stub': None,
  913. 'L___eprintf$stub': None,
  914. }
  915. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  916. FUNCTIONS_NOT_RETURNING[_name] = None
  917. def __init__(self, lines, filetag=0):
  918. match = self.r_functionstart.match(lines[0])
  919. funcname = match.group(1)
  920. match = self.r_functionend.match(lines[-1])
  921. assert funcname == match.group(1)
  922. assert funcname == match.group(2)
  923. super(ElfFunctionGcRootTracker32, self).__init__(
  924. funcname, lines, filetag)
  925. def extract_immediate(self, value):
  926. if not value.startswith('$'):
  927. return None
  928. return int(value[1:])
  929. ElfFunctionGcRootTracker32.init_regexp()
  930. class ElfFunctionGcRootTracker64(FunctionGcRootTracker64):
  931. format = 'elf64'
  932. function_names_prefix = ''
  933. ESP = '%rsp'
  934. EBP = '%rbp'
  935. EAX = '%rax'
  936. CALLEE_SAVE_REGISTERS = ['%rbx', '%r12', '%r13', '%r14', '%r15', '%rbp']
  937. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  938. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  939. OPERAND = r'(?:[-\w$%+.:@"]+(?:[(][\w%,]+[)])?|[(][\w%,]+[)])'
  940. LABEL = r'([a-zA-Z_$.][a-zA-Z0-9_$@.]*)'
  941. OFFSET_LABELS = 2**30
  942. TOP_OF_STACK_MINUS_WORD = '-8(%rsp)'
  943. r_functionstart = re.compile(r"\t.type\s+"+LABEL+",\s*[@]function\s*$")
  944. r_functionend = re.compile(r"\t.size\s+"+LABEL+",\s*[.]-"+LABEL+"\s*$")
  945. LOCALVAR = r"%rax|%rbx|%rcx|%rdx|%rdi|%rsi|%rbp|%r8|%r9|%r10|%r11|%r12|%r13|%r14|%r15|-?\d*[(]%rsp[)]"
  946. LOCALVARFP = LOCALVAR + r"|-?\d*[(]%rbp[)]"
  947. r_localvarnofp = re.compile(LOCALVAR)
  948. r_localvarfp = re.compile(LOCALVARFP)
  949. r_localvar_esp = re.compile(r"(-?\d*)[(]%rsp[)]")
  950. r_localvar_ebp = re.compile(r"(-?\d*)[(]%rbp[)]")
  951. r_rel_label = re.compile(r"(\d+):\s*$")
  952. r_jump_rel_label = re.compile(r"\tj\w+\s+"+"(\d+)f"+"\s*$")
  953. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+[*]("+OPERAND+")\s*$")
  954. r_jmptable_item = re.compile(r"\t.quad\t"+LABEL+"(-\"[A-Za-z0-9$]+\")?\s*$")
  955. r_jmptable_end = re.compile(r"\t.text|\t.section\s+.text|\t\.align|"+LABEL)
  956. r_gcroot_marker = re.compile(r"\t/[*] GCROOT ("+LOCALVARFP+") [*]/")
  957. r_gcnocollect_marker = re.compile(r"\t/[*] GC_NOCOLLECT ("+OPERAND+") [*]/")
  958. r_bottom_marker = re.compile(r"\t/[*] GC_STACK_BOTTOM [*]/")
  959. FUNCTIONS_NOT_RETURNING = {
  960. '_exit': None,
  961. '__assert_fail': None,
  962. '___assert_rtn': None,
  963. 'L___assert_rtn$stub': None,
  964. 'L___eprintf$stub': None,
  965. }
  966. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  967. FUNCTIONS_NOT_RETURNING[_name] = None
  968. def __init__(self, lines, filetag=0):
  969. match = self.r_functionstart.match(lines[0])
  970. funcname = match.group(1)
  971. match = self.r_functionend.match(lines[-1])
  972. assert funcname == match.group(1)
  973. assert funcname == match.group(2)
  974. super(ElfFunctionGcRootTracker64, self).__init__(
  975. funcname, lines, filetag)
  976. def extract_immediate(self, value):
  977. if not value.startswith('$'):
  978. return None
  979. return int(value[1:])
  980. ElfFunctionGcRootTracker64.init_regexp()
  981. class DarwinFunctionGcRootTracker32(ElfFunctionGcRootTracker32):
  982. format = 'darwin'
  983. function_names_prefix = '_'
  984. r_functionstart = re.compile(r"_(\w+):\s*$")
  985. OFFSET_LABELS = 0
  986. def __init__(self, lines, filetag=0):
  987. match = self.r_functionstart.match(lines[0])
  988. funcname = '_' + match.group(1)
  989. FunctionGcRootTracker32.__init__(self, funcname, lines, filetag)
  990. class DarwinFunctionGcRootTracker64(ElfFunctionGcRootTracker64):
  991. format = 'darwin64'
  992. function_names_prefix = '_'
  993. LABEL = ElfFunctionGcRootTracker64.LABEL
  994. r_jmptable_item = re.compile(r"\t.(?:long|quad)\t"+LABEL+"(-\"?[A-Za-z0-9$]+\"?)?\s*$")
  995. r_functionstart = re.compile(r"_(\w+):\s*$")
  996. OFFSET_LABELS = 0
  997. def __init__(self, lines, filetag=0):
  998. match = self.r_functionstart.match(lines[0])
  999. funcname = '_' + match.group(1)
  1000. FunctionGcRootTracker64.__init__(self, funcname, lines, filetag)
  1001. class Mingw32FunctionGcRootTracker(DarwinFunctionGcRootTracker32):
  1002. format = 'mingw32'
  1003. function_names_prefix = '_'
  1004. FUNCTIONS_NOT_RETURNING = {
  1005. '_exit': None,
  1006. '__assert': None,
  1007. }
  1008. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1009. FUNCTIONS_NOT_RETURNING['_' + _name] = None
  1010. class MsvcFunctionGcRootTracker(FunctionGcRootTracker32):
  1011. format = 'msvc'
  1012. function_names_prefix = '_'
  1013. ESP = 'esp'
  1014. EBP = 'ebp'
  1015. EAX = 'eax'
  1016. CALLEE_SAVE_REGISTERS = ['ebx', 'esi', 'edi', 'ebp']
  1017. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  1018. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  1019. TOP_OF_STACK_MINUS_WORD = 'DWORD PTR [esp-4]'
  1020. OPERAND = r'(?:(:?WORD|DWORD|BYTE) PTR |OFFSET )?[_\w?:@$]*(?:[-+0-9]+)?(:?\[[-+*\w0-9]+\])?'
  1021. LABEL = r'([a-zA-Z_$@.][a-zA-Z0-9_$@.]*)'
  1022. OFFSET_LABELS = 0
  1023. r_segmentstart = re.compile(r"[_A-Z]+\tSEGMENT$")
  1024. r_segmentend = re.compile(r"[_A-Z]+\tENDS$")
  1025. r_functionstart = re.compile(r"; Function compile flags: ")
  1026. r_codestart = re.compile(LABEL+r"\s+PROC\s*(:?;.+)?\n$")
  1027. r_functionend = re.compile(LABEL+r"\s+ENDP\s*$")
  1028. r_symboldefine = re.compile(r"([_A-Za-z0-9$]+) = ([-0-9]+)\s*;.+\n")
  1029. LOCALVAR = r"eax|edx|ecx|ebx|esi|edi|ebp|DWORD PTR [-+]?\d*\[esp[-+]?\d*\]"
  1030. LOCALVARFP = LOCALVAR + r"|DWORD PTR -?\d*\[ebp\]"
  1031. r_localvarnofp = re.compile(LOCALVAR)
  1032. r_localvarfp = re.compile(LOCALVARFP)
  1033. r_localvar_esp = re.compile(r"DWORD PTR ([-+]?\d+)?\[esp([-+]?\d+)?\]")
  1034. r_localvar_ebp = re.compile(r"DWORD PTR ([-+]?\d+)?\[ebp([-+]?\d+)?\]")
  1035. r_rel_label = re.compile(r"$1") # never matches
  1036. r_jump_rel_label = re.compile(r"$1") # never matches
  1037. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+DWORD PTR ("+OPERAND+")\s*$")
  1038. r_jmptable_item = re.compile(r"\tDD\t"+LABEL+"(-\"[A-Za-z0-9$]+\")?\s*$")
  1039. r_jmptable_end = re.compile(r"[^\t\n;]")
  1040. r_gcroot_marker = re.compile(r"$1") # never matches
  1041. r_gcroot_marker_var = re.compile(r"DWORD PTR .+_constant_always_one_.+pypy_asm_gcroot")
  1042. r_gcnocollect_marker = re.compile(r"\spypy_asm_gc_nocollect\(("+OPERAND+")\);")
  1043. r_bottom_marker = re.compile(r"; .+\spypy_asm_stack_bottom\(\);")
  1044. FUNCTIONS_NOT_RETURNING = {
  1045. '__exit': None,
  1046. '__assert': None,
  1047. '__wassert': None,
  1048. '__imp__abort': None,
  1049. '__imp___wassert': None,
  1050. 'DWORD PTR __imp__abort': None,
  1051. 'DWORD PTR __imp___wassert': None,
  1052. }
  1053. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1054. FUNCTIONS_NOT_RETURNING['_' + _name] = None
  1055. @classmethod
  1056. def init_regexp(cls):
  1057. super(MsvcFunctionGcRootTracker, cls).init_regexp()
  1058. cls.r_binaryinsn = re.compile(r"\t[a-z]\w*\s+(?P<target>"+cls.OPERAND+r"),\s*(?P<source>"+cls.OPERAND+r")\s*(?:;.+)?$")
  1059. cls.r_jump = re.compile(r"\tj\w+\s+(?:SHORT |DWORD PTR )?"+cls.LABEL+"\s*$")
  1060. def __init__(self, lines, filetag=0):
  1061. self.defines = {}
  1062. for i, line in enumerate(lines):
  1063. if self.r_symboldefine.match(line):
  1064. match = self.r_symboldefine.match(line)
  1065. name = match.group(1)
  1066. value = int(match.group(2))
  1067. self.defines[name] = value
  1068. continue
  1069. match = self.r_codestart.match(line)
  1070. if match:
  1071. self.skip = i
  1072. break
  1073. funcname = match.group(1)
  1074. super(MsvcFunctionGcRootTracker, self).__init__(
  1075. funcname, lines, filetag)
  1076. def replace_symbols(self, operand):
  1077. for name, value in self.defines.items():
  1078. operand = operand.replace(name, str(value))
  1079. return operand
  1080. for name in '''
  1081. push pop mov lea
  1082. xor sub add
  1083. '''.split():
  1084. locals()['visit_' + name] = getattr(FunctionGcRootTracker32,
  1085. 'visit_' + name + 'l')
  1086. visit_int = FunctionGcRootTracker32.visit_nop
  1087. # probably not GC pointers
  1088. visit_cdq = FunctionGcRootTracker32.visit_nop
  1089. def visit_npad(self, line):
  1090. #

Large files files are truncated, but you can click here to view the full file