PageRenderTime 177ms CodeModel.GetById 18ms RepoModel.GetById 5ms app.codeStats 1ms

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

https://bitbucket.org/alex_gaynor/pypy-postgresql/
Python | 1945 lines | 1809 code | 60 blank | 76 comment | 170 complexity | 9cd391fe775507fb67713c981c656bb4 MD5 | raw file

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

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