PageRenderTime 67ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/timfel/pypy
Python | 2104 lines | 1908 code | 74 blank | 122 comment | 230 complexity | 6ea9005cfb35600ba29913375f7d6bcc MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0, BSD-3-Clause

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

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