PageRenderTime 92ms CodeModel.GetById 44ms RepoModel.GetById 1ms app.codeStats 1ms

/rpython/translator/c/gcc/trackgcroot.py

https://bitbucket.org/squeaky/pypy
Python | 2080 lines | 1917 code | 69 blank | 94 comment | 191 complexity | cff59f5dd03fefee469b99834a1dae52 MD5 | raw file
Possible License(s): Apache-2.0

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

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

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