PageRenderTime 133ms CodeModel.GetById 44ms RepoModel.GetById 6ms app.codeStats 0ms

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

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

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