PageRenderTime 59ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

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

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

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