PageRenderTime 35ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/kostialopuhin/pypy
Python | 2094 lines | 1903 code | 73 blank | 118 comment | 229 complexity | 9c5193355f3edef423c9e1b1169eaf76 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0, BSD-3-Clause
  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. ])
  487. # a partial list is hopefully good enough for now; it's all to support
  488. # only one corner case, tested in elf64/track_zero.s
  489. OPS_WITH_PREFIXES_CHANGING_FLAGS = dict.fromkeys([
  490. 'cmp', 'test', 'lahf', 'cld', 'std', 'rep',
  491. 'ucomi', 'comi',
  492. 'add', 'sub', 'xor',
  493. 'inc', 'dec', 'not', 'neg', 'or', 'and', 'sbb', 'adc',
  494. 'shl', 'shr', 'sal', 'sar', 'rol', 'ror', 'mul', 'imul', 'div', 'idiv',
  495. 'bt', 'call', 'int',
  496. 'jmp', # not really changing flags, but we shouldn't assume
  497. # anything about the operations on the following lines
  498. ], True)
  499. visit_movb = visit_nop
  500. visit_movw = visit_nop
  501. visit_addb = visit_nop
  502. visit_addw = visit_nop
  503. visit_subb = visit_nop
  504. visit_subw = visit_nop
  505. visit_xorb = visit_nop
  506. visit_xorw = visit_nop
  507. def _visit_add(self, line, sign=+1):
  508. match = self.r_binaryinsn.match(line)
  509. source = match.group("source")
  510. target = match.group("target")
  511. if target == self.ESP:
  512. count = self.extract_immediate(source)
  513. if count is None:
  514. # strange instruction - I've seen 'subl %eax, %esp'
  515. return InsnCannotFollowEsp()
  516. return InsnStackAdjust(sign * count)
  517. elif self.r_localvar.match(target):
  518. return InsnSetLocal(target, [source, target])
  519. else:
  520. return []
  521. def _visit_sub(self, line):
  522. return self._visit_add(line, sign=-1)
  523. def unary_insn(self, line):
  524. match = self.r_unaryinsn.match(line)
  525. target = match.group(1)
  526. if self.r_localvar.match(target):
  527. return InsnSetLocal(target)
  528. else:
  529. return []
  530. def binary_insn(self, line):
  531. match = self.r_binaryinsn.match(line)
  532. if not match:
  533. raise UnrecognizedOperation(line)
  534. source = match.group("source")
  535. target = match.group("target")
  536. if self.r_localvar.match(target):
  537. return InsnSetLocal(target, [source])
  538. elif target == self.ESP:
  539. raise UnrecognizedOperation(line)
  540. else:
  541. return []
  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. [InsnPushed(-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. # First, find the latest InsnStackAdjust; if it's not a PUSH,
  616. # then consider that this 'mov %rsp, %rbp' is actually unrelated
  617. i = -1
  618. while not isinstance(self.insns[i], InsnStackAdjust):
  619. i -= 1
  620. if not isinstance(self.insns[i], InsnPushed):
  621. return []
  622. #
  623. self.uses_frame_pointer = True
  624. self.r_localvar = self.r_localvarfp
  625. return [InsnPrologue(self.WORD)]
  626. def _visit_epilogue(self):
  627. if not self.uses_frame_pointer:
  628. raise UnrecognizedOperation('epilogue without prologue')
  629. return [InsnEpilogue(self.WORD)]
  630. def visit_leave(self, line):
  631. return self._visit_epilogue() + self._visit_pop(self.EBP)
  632. def visit_ret(self, line):
  633. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  634. def visit_rep(self, line):
  635. # 'rep ret' or 'rep; ret': bad reasons for this bogus 'rep' here
  636. if line.split()[:2] == ['rep', 'ret']:
  637. return self.visit_ret(line)
  638. return []
  639. def visit_ud2(self, line):
  640. return InsnStop("ud2") # unreachable instruction
  641. def visit_jmp(self, line):
  642. tablelabels = []
  643. match = self.r_jmp_switch.match(line)
  644. if match:
  645. # this is a jmp *Label(%index) or jmp *%addr, used for
  646. # table-based switches. Assume that the table is coming
  647. # after a .section .rodata and a label, and is a list of
  648. # lines looking like .long LABEL or .long 0 or .long L2-L1,
  649. # ending in a .text or .section .text.hot.
  650. lineno = self.currentlineno + 1
  651. if '.section' not in self.lines[lineno]:
  652. pass # bah, probably a tail-optimized indirect call...
  653. else:
  654. assert '.rodata' in self.lines[lineno]
  655. lineno += 1
  656. while '.align' in self.lines[lineno]:
  657. lineno += 1
  658. match = self.r_label.match(self.lines[lineno])
  659. assert match, repr(self.lines[lineno])
  660. tablelabels.append(match.group(1))
  661. elif self.r_unaryinsn_star.match(line):
  662. # maybe a jmp similar to the above, but stored in a
  663. # registry:
  664. # movl L9341(%eax), %eax
  665. # jmp *%eax
  666. operand = self.r_unaryinsn_star.match(line).group(1)
  667. def walker(insn, locs):
  668. sources = []
  669. for loc in locs:
  670. for s in insn.all_sources_of(loc):
  671. # if the source looks like 8(%eax,%edx,4)
  672. # %eax is the real source, %edx is an offset.
  673. match = self.r_jmp_source.match(s)
  674. if match and not self.r_localvar_esp.match(s):
  675. sources.append(match.group(1))
  676. else:
  677. sources.append(s)
  678. for source in sources:
  679. label_match = re.compile(self.LABEL).match(source)
  680. if label_match:
  681. tablelabels.append(label_match.group(0))
  682. return
  683. yield tuple(sources)
  684. insn = InsnStop()
  685. insn.previous_insns = [self.insns[-1]]
  686. self.walk_instructions_backwards(walker, insn, (operand,))
  687. # Remove probable tail-calls
  688. tablelabels = [label for label in tablelabels
  689. if label in self.labels]
  690. assert len(tablelabels) <= 1
  691. if tablelabels:
  692. tablelin = self.labels[tablelabels[0]].lineno + 1
  693. while not self.r_jmptable_end.match(self.lines[tablelin]):
  694. # skip empty lines
  695. if (not self.lines[tablelin].strip()
  696. or self.lines[tablelin].startswith(';')):
  697. tablelin += 1
  698. continue
  699. match = self.r_jmptable_item.match(self.lines[tablelin])
  700. if not match:
  701. raise NoPatternMatch(repr(self.lines[tablelin]))
  702. label = match.group(1)
  703. if label != '0':
  704. self.register_jump_to(label)
  705. tablelin += 1
  706. return InsnStop("jump table")
  707. if self.r_unaryinsn_star.match(line):
  708. # that looks like an indirect tail-call.
  709. # tail-calls are equivalent to RET for us
  710. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  711. try:
  712. self.conditional_jump(line)
  713. except KeyError:
  714. # label not found: check if it's a tail-call turned into a jump
  715. match = self.r_unaryinsn.match(line)
  716. target = match.group(1)
  717. assert not target.startswith('.')
  718. # tail-calls are equivalent to RET for us
  719. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  720. return InsnStop("jump")
  721. def register_jump_to(self, label, lastinsn=None):
  722. if lastinsn is None:
  723. lastinsn = self.insns[-1]
  724. if not isinstance(lastinsn, InsnStop):
  725. self.labels[label].previous_insns.append(lastinsn)
  726. def conditional_jump(self, line, je=False, jne=False):
  727. match = self.r_jump.match(line)
  728. if not match:
  729. match = self.r_jump_rel_label.match(line)
  730. if not match:
  731. raise UnrecognizedOperation(line)
  732. # j* NNNf
  733. label = match.group(1)
  734. label += ":"
  735. i = self.currentlineno + 1
  736. while True:
  737. if self.lines[i].startswith(label):
  738. label = "rel %d" % i
  739. break
  740. i += 1
  741. else:
  742. label = match.group(1)
  743. prefix = []
  744. lastinsn = None
  745. postfix = []
  746. if self.tested_for_zero is not None:
  747. if je:
  748. # generate pseudo-code...
  749. prefix = [InsnCopyLocal(self.tested_for_zero, '%tmp'),
  750. InsnSetLocal(self.tested_for_zero)]
  751. postfix = [InsnCopyLocal('%tmp', self.tested_for_zero)]
  752. lastinsn = prefix[-1]
  753. elif jne:
  754. postfix = [InsnSetLocal(self.tested_for_zero)]
  755. self.register_jump_to(label, lastinsn)
  756. return prefix + [InsnCondJump(label)] + postfix
  757. visit_jmpl = visit_jmp
  758. # The various conditional jumps and cmov* operations
  759. for name in '''
  760. e g ge l le a ae b be p s o c
  761. '''.split():
  762. # NB. visit_je() and visit_jne() are overridden below
  763. locals()['visit_j' + name] = conditional_jump
  764. locals()['visit_jn' + name] = conditional_jump
  765. locals()['visit_cmov' + name] = binary_insn
  766. locals()['visit_cmov' + name + 'l'] = binary_insn
  767. locals()['visit_cmovn' + name] = binary_insn
  768. locals()['visit_cmovn' + name + 'l'] = binary_insn
  769. def visit_je(self, line):
  770. return self.conditional_jump(line, je=True)
  771. def visit_jne(self, line):
  772. return self.conditional_jump(line, jne=True)
  773. def _visit_test(self, line):
  774. match = self.r_binaryinsn.match(line)
  775. source = match.group("source")
  776. target = match.group("target")
  777. if source == target:
  778. self.tested_for_zero = source
  779. return []
  780. def _visit_xchg(self, line):
  781. # support the format used in VALGRIND_DISCARD_TRANSLATIONS
  782. # which is to use a marker no-op "xchgl %ebx, %ebx"
  783. match = self.r_binaryinsn.match(line)
  784. source = match.group("source")
  785. target = match.group("target")
  786. if source == target:
  787. return []
  788. # ignore the 'rpy_fastgil' atomic exchange, or any locked
  789. # atomic exchange at all (involving memory)
  790. if not source.startswith('%'):
  791. return []
  792. raise UnrecognizedOperation(line)
  793. def visit_call(self, line):
  794. match = self.r_unaryinsn.match(line)
  795. if match is None:
  796. assert self.r_unaryinsn_star.match(line) # indirect call
  797. return [InsnCall('<indirect>', self.currentlineno),
  798. InsnSetLocal(self.EAX)] # the result is there
  799. target = match.group(1)
  800. if self.format in ('msvc',):
  801. # On win32, the address of a foreign function must be
  802. # computed, the optimizer may store it in a register. We
  803. # could ignore this, except when the function need special
  804. # processing (not returning, __stdcall...)
  805. def find_register(target):
  806. reg = []
  807. def walker(insn, locs):
  808. sources = []
  809. for loc in locs:
  810. for s in insn.all_sources_of(loc):
  811. sources.append(s)
  812. for source in sources:
  813. m = re.match("DWORD PTR " + self.LABEL, source)
  814. if m:
  815. reg.append(m.group(1))
  816. if reg:
  817. return
  818. yield tuple(sources)
  819. insn = InsnStop()
  820. insn.previous_insns = [self.insns[-1]]
  821. self.walk_instructions_backwards(walker, insn, (target,))
  822. return reg
  823. if match and self.r_localvarfp.match(target):
  824. sources = find_register(target)
  825. if sources:
  826. target, = sources
  827. if target.endswith('@PLT'):
  828. # In -fPIC mode, all functions calls have this suffix
  829. target = target[:-4]
  830. if target in self.FUNCTIONS_NOT_RETURNING:
  831. return [InsnStop(target)]
  832. if self.format == 'mingw32' and target == '__alloca':
  833. # in functions with large stack requirements, windows
  834. # needs a call to _alloca(), to turn reserved pages
  835. # into committed memory.
  836. # With mingw32 gcc at least, %esp is not used before
  837. # this call. So we don't bother to compute the exact
  838. # stack effect.
  839. return [InsnCannotFollowEsp()]
  840. if target in self.labels:
  841. lineoffset = self.labels[target].lineno - self.currentlineno
  842. if lineoffset >= 0:
  843. assert lineoffset in (1,2)
  844. return [InsnStackAdjust(-4)]
  845. insns = [InsnCall(target, self.currentlineno),
  846. InsnSetLocal(self.EAX)] # the result is there
  847. if self.format in ('mingw32', 'msvc'):
  848. # handle __stdcall calling convention:
  849. # Stack cleanup is performed by the called function,
  850. # Function name is decorated with "@N" where N is the stack size
  851. if '@' in target and not target.startswith('@'):
  852. insns.append(InsnStackAdjust(int(target.rsplit('@', 1)[1])))
  853. # Some (intrinsic?) functions use the "fastcall" calling convention
  854. # XXX without any declaration, how can we guess the stack effect?
  855. if target in ['__alldiv', '__allrem', '__allmul', '__alldvrm',
  856. '__aulldiv', '__aullrem', '__aullmul', '__aulldvrm']:
  857. insns.append(InsnStackAdjust(16))
  858. return insns
  859. # __________ debugging output __________
  860. @classmethod
  861. def format_location(cls, loc):
  862. # A 'location' is a single number describing where a value is stored
  863. # across a call. It can be in one of the CALLEE_SAVE_REGISTERS, or
  864. # in the stack frame at an address relative to either %esp or %ebp.
  865. # The last two bits of the location number are used to tell the cases
  866. # apart; see format_location().
  867. assert loc >= 0
  868. kind = loc & LOC_MASK
  869. if kind == LOC_REG:
  870. if loc == LOC_NOWHERE:
  871. return '?'
  872. reg = (loc >> 2) - 1
  873. return '%' + cls.CALLEE_SAVE_REGISTERS[reg].replace("%", "")
  874. else:
  875. offset = loc & ~ LOC_MASK
  876. if cls.WORD == 8:
  877. offset <<= 1
  878. if kind == LOC_EBP_PLUS:
  879. result = '(%' + cls.EBP.replace("%", "") + ')'
  880. elif kind == LOC_EBP_MINUS:
  881. result = '(%' + cls.EBP.replace("%", "") + ')'
  882. offset = -offset
  883. elif kind == LOC_ESP_PLUS:
  884. result = '(%' + cls.ESP.replace("%", "") + ')'
  885. else:
  886. assert 0, kind
  887. if offset != 0:
  888. result = str(offset) + result
  889. return result
  890. @classmethod
  891. def format_callshape(cls, shape):
  892. # A 'call shape' is a tuple of locations in the sense of
  893. # format_location(). They describe where in a function frame
  894. # interesting values are stored, when this function executes a 'call'
  895. # instruction.
  896. #
  897. # shape[0] is the location that stores the fn's own return
  898. # address (not the return address for the currently
  899. # executing 'call')
  900. #
  901. # shape[1..N] is where the fn saved its own caller's value of a
  902. # certain callee save register. (where N is the number
  903. # of callee save registers.)
  904. #
  905. # shape[>N] are GC roots: where the fn has put its local GCPTR
  906. # vars
  907. #
  908. num_callee_save_regs = len(cls.CALLEE_SAVE_REGISTERS)
  909. assert isinstance(shape, tuple)
  910. # + 1 for the return address
  911. assert len(shape) >= (num_callee_save_regs + 1)
  912. result = [cls.format_location(loc) for loc in shape]
  913. return '{%s | %s | %s}' % (result[0],
  914. ', '.join(result[1:(num_callee_save_regs+1)]),
  915. ', '.join(result[(num_callee_save_regs+1):]))
  916. class FunctionGcRootTracker32(FunctionGcRootTracker):
  917. WORD = 4
  918. visit_mov = FunctionGcRootTracker._visit_mov
  919. visit_movl = FunctionGcRootTracker._visit_mov
  920. visit_pushl = FunctionGcRootTracker._visit_push
  921. visit_leal = FunctionGcRootTracker._visit_lea
  922. visit_addl = FunctionGcRootTracker._visit_add
  923. visit_subl = FunctionGcRootTracker._visit_sub
  924. visit_andl = FunctionGcRootTracker._visit_and
  925. visit_and = FunctionGcRootTracker._visit_and
  926. visit_xchgl = FunctionGcRootTracker._visit_xchg
  927. visit_testl = FunctionGcRootTracker._visit_test
  928. # used in "xor reg, reg" to create a NULL GC ptr
  929. visit_xorl = FunctionGcRootTracker.binary_insn
  930. visit_orl = FunctionGcRootTracker.binary_insn # unsure about this one
  931. # occasionally used on 32-bits to move floats around
  932. visit_movq = FunctionGcRootTracker.visit_nop
  933. def visit_pushw(self, line):
  934. return [InsnStackAdjust(-2)] # rare but not impossible
  935. def visit_popl(self, line):
  936. match = self.r_unaryinsn.match(line)
  937. target = match.group(1)
  938. return self._visit_pop(target)
  939. class FunctionGcRootTracker64(FunctionGcRootTracker):
  940. WORD = 8
  941. # Regex ignores destination
  942. r_save_xmm_register = re.compile(r"\tmovaps\s+%xmm(\d+)")
  943. def _maybe_32bit_dest(func):
  944. def wrapper(self, line):
  945. # Using a 32-bit reg as a destination in 64-bit mode zero-extends
  946. # to 64-bits, so sometimes gcc uses a 32-bit operation to copy a
  947. # statically known pointer to a register
  948. # %eax -> %rax
  949. new_line = re.sub(r"%e(ax|bx|cx|dx|di|si|bp)$", r"%r\1", line)
  950. # %r10d -> %r10
  951. new_line = re.sub(r"%r(\d+)d$", r"%r\1", new_line)
  952. return func(self, new_line)
  953. return wrapper
  954. visit_addl = FunctionGcRootTracker.visit_nop
  955. visit_subl = FunctionGcRootTracker.visit_nop
  956. visit_leal = FunctionGcRootTracker.visit_nop
  957. visit_cltq = FunctionGcRootTracker.visit_nop
  958. visit_movq = FunctionGcRootTracker._visit_mov
  959. # just a special assembler mnemonic for mov
  960. visit_movabsq = FunctionGcRootTracker._visit_mov
  961. visit_mov = _maybe_32bit_dest(FunctionGcRootTracker._visit_mov)
  962. visit_movl = visit_mov
  963. visit_xorl = _maybe_32bit_dest(FunctionGcRootTracker.binary_insn)
  964. visit_pushq = FunctionGcRootTracker._visit_push
  965. visit_addq = FunctionGcRootTracker._visit_add
  966. visit_subq = FunctionGcRootTracker._visit_sub
  967. visit_leaq = FunctionGcRootTracker._visit_lea
  968. visit_xorq = FunctionGcRootTracker.binary_insn
  969. visit_xchgl = FunctionGcRootTracker._visit_xchg
  970. visit_xchgq = FunctionGcRootTracker._visit_xchg
  971. visit_testq = FunctionGcRootTracker._visit_test
  972. # FIXME: similar to visit_popl for 32-bit
  973. def visit_popq(self, line):
  974. match = self.r_unaryinsn.match(line)
  975. target = match.group(1)
  976. return self._visit_pop(target)
  977. def visit_jmp(self, line):
  978. # On 64-bit, %al is used when calling varargs functions to specify an
  979. # upper-bound on the number of xmm registers used in the call. gcc
  980. # uses %al to compute an indirect jump that looks like:
  981. #
  982. # jmp *[some register]
  983. # movaps %xmm7, [stack location]
  984. # movaps %xmm6, [stack location]
  985. # movaps %xmm5, [stack location]
  986. # movaps %xmm4, [stack location]
  987. # movaps %xmm3, [stack location]
  988. # movaps %xmm2, [stack location]
  989. # movaps %xmm1, [stack location]
  990. # movaps %xmm0, [stack location]
  991. #
  992. # The jmp is always to somewhere in the block of "movaps"
  993. # instructions, according to how many xmm registers need to be saved
  994. # to the stack. The point of all this is that we can safely ignore
  995. # jmp instructions of that form.
  996. if (self.currentlineno + 8) < len(self.lines) and self.r_unaryinsn_star.match(line):
  997. matches = [self.r_save_xmm_register.match(self.lines[self.currentlineno + 1 + i]) for i in range(8)]
  998. if all(m and int(m.group(1)) == (7 - i) for i, m in enumerate(matches)):
  999. return []
  1000. return FunctionGcRootTracker.visit_jmp(self, line)
  1001. class ElfFunctionGcRootTracker32(FunctionGcRootTracker32):
  1002. format = 'elf'
  1003. function_names_prefix = ''
  1004. ESP = '%esp'
  1005. EBP = '%ebp'
  1006. EAX = '%eax'
  1007. CALLEE_SAVE_REGISTERS = ['%ebx', '%esi', '%edi', '%ebp']
  1008. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  1009. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  1010. OPERAND = r'(?:[-\w$%+.:@"]+(?:[(][\w%,]+[)])?|[(][\w%,]+[)])'
  1011. LABEL = r'([a-zA-Z_$.][a-zA-Z0-9_$@.]*)'
  1012. OFFSET_LABELS = 2**30
  1013. TOP_OF_STACK_MINUS_WORD = '-4(%esp)'
  1014. r_functionstart = re.compile(r"\t.type\s+"+LABEL+",\s*[@]function\s*$")
  1015. r_functionend = re.compile(r"\t.size\s+"+LABEL+",\s*[.]-"+LABEL+"\s*$")
  1016. LOCALVAR = r"%eax|%edx|%ecx|%ebx|%esi|%edi|%ebp|-?\d*[(]%esp[)]"
  1017. LOCALVARFP = LOCALVAR + r"|-?\d*[(]%ebp[)]"
  1018. r_localvarnofp = re.compile(LOCALVAR)
  1019. r_localvarfp = re.compile(LOCALVARFP)
  1020. r_localvar_esp = re.compile(r"(-?\d*)[(]%esp[)]")
  1021. r_localvar_ebp = re.compile(r"(-?\d*)[(]%ebp[)]")
  1022. r_rel_label = re.compile(r"(\d+):\s*$")
  1023. r_jump_rel_label = re.compile(r"\tj\w+\s+"+"(\d+)f"+"\s*$")
  1024. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+[*]("+OPERAND+")\s*$")
  1025. r_jmptable_item = re.compile(r"\t.long\t"+LABEL+"(-\"[A-Za-z0-9$]+\")?\s*$")
  1026. r_jmptable_end = re.compile(r"\t.text|\t.section\s+.text|\t\.align|"+LABEL)
  1027. r_gcroot_marker = re.compile(r"\t/[*] GCROOT ("+LOCALVARFP+") [*]/")
  1028. r_gcnocollect_marker = re.compile(r"\t/[*] GC_NOCOLLECT ("+OPERAND+") [*]/")
  1029. r_bottom_marker = re.compile(r"\t/[*] GC_STACK_BOTTOM [*]/")
  1030. FUNCTIONS_NOT_RETURNING = {
  1031. '_exit': None,
  1032. '__assert_fail': None,
  1033. '___assert_rtn': None,
  1034. 'L___assert_rtn$stub': None,
  1035. 'L___eprintf$stub': None,
  1036. '__stack_chk_fail': None,
  1037. }
  1038. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1039. FUNCTIONS_NOT_RETURNING[_name] = None
  1040. def __init__(self, lines, filetag=0):
  1041. match = self.r_functionstart.match(lines[0])
  1042. funcname = match.group(1)
  1043. match = self.r_functionend.match(lines[-1])
  1044. assert funcname == match.group(1)
  1045. assert funcname == match.group(2)
  1046. super(ElfFunctionGcRootTracker32, self).__init__(
  1047. funcname, lines, filetag)
  1048. def extract_immediate(self, value):
  1049. if not value.startswith('$'):
  1050. return None
  1051. return int(value[1:])
  1052. ElfFunctionGcRootTracker32.init_regexp()
  1053. class ElfFunctionGcRootTracker64(FunctionGcRootTracker64):
  1054. format = 'elf64'
  1055. function_names_prefix = ''
  1056. ESP = '%rsp'
  1057. EBP = '%rbp'
  1058. EAX = '%rax'
  1059. CALLEE_SAVE_REGISTERS = ['%rbx', '%r12', '%r13', '%r14', '%r15', '%rbp']
  1060. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  1061. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  1062. OPERAND = r'(?:[-\w$%+.:@"]+(?:[(][\w%,]+[)])?|[(][\w%,]+[)])'
  1063. LABEL = r'([a-zA-Z_$.][a-zA-Z0-9_$@.]*)'
  1064. OFFSET_LABELS = 2**30
  1065. TOP_OF_STACK_MINUS_WORD = '-8(%rsp)'
  1066. r_functionstart = re.compile(r"\t.type\s+"+LABEL+",\s*[@]function\s*$")
  1067. r_functionend = re.compile(r"\t.size\s+"+LABEL+",\s*[.]-"+LABEL+"\s*$")
  1068. LOCALVAR = r"%rax|%rbx|%rcx|%rdx|%rdi|%rsi|%rbp|%r8|%r9|%r10|%r11|%r12|%r13|%r14|%r15|-?\d*[(]%rsp[)]"
  1069. LOCALVARFP = LOCALVAR + r"|-?\d*[(]%rbp[)]"
  1070. r_localvarnofp = re.compile(LOCALVAR)
  1071. r_localvarfp = re.compile(LOCALVARFP)
  1072. r_localvar_esp = re.compile(r"(-?\d*)[(]%rsp[)]")
  1073. r_localvar_ebp = re.compile(r"(-?\d*)[(]%rbp[)]")
  1074. r_rel_label = re.compile(r"(\d+):\s*$")
  1075. r_jump_rel_label = re.compile(r"\tj\w+\s+"+"(\d+)f"+"\s*$")
  1076. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+[*]("+OPERAND+")\s*$")
  1077. r_jmptable_item = re.compile(r"\t.(?:quad|long)\t"+LABEL+"(-\"[A-Za-z0-9$]+\"|-"+LABEL+")?\s*$")
  1078. r_jmptable_end = re.compile(r"\t.text|\t.section\s+.text|\t\.align|"+LABEL)
  1079. r_gcroot_marker = re.compile(r"\t/[*] GCROOT ("+LOCALVARFP+") [*]/")
  1080. r_gcnocollect_marker = re.compile(r"\t/[*] GC_NOCOLLECT ("+OPERAND+") [*]/")
  1081. r_bottom_marker = re.compile(r"\t/[*] GC_STACK_BOTTOM [*]/")
  1082. FUNCTIONS_NOT_RETURNING = {
  1083. '_exit': None,
  1084. '__assert_fail': None,
  1085. '___assert_rtn': None,
  1086. 'L___assert_rtn$stub': None,
  1087. 'L___eprintf$stub': None,
  1088. '__stack_chk_fail': None,
  1089. }
  1090. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1091. FUNCTIONS_NOT_RETURNING[_name] = None
  1092. def __init__(self, lines, filetag=0):
  1093. match = self.r_functionstart.match(lines[0])
  1094. funcname = match.group(1)
  1095. match = self.r_functionend.match(lines[-1])
  1096. assert funcname == match.group(1)
  1097. assert funcname == match.group(2)
  1098. super(ElfFunctionGcRootTracker64, self).__init__(
  1099. funcname, lines, filetag)
  1100. def extract_immediate(self, value):
  1101. if not value.startswith('$'):
  1102. return None
  1103. return int(value[1:])
  1104. ElfFunctionGcRootTracker64.init_regexp()
  1105. class DarwinFunctionGcRootTracker32(ElfFunctionGcRootTracker32):
  1106. format = 'darwin'
  1107. function_names_prefix = '_'
  1108. r_functionstart = re.compile(r"_(\w+):\s*$")
  1109. OFFSET_LABELS = 0
  1110. def __init__(self, lines, filetag=0):
  1111. match = self.r_functionstart.match(lines[0])
  1112. funcname = '_' + match.group(1)
  1113. FunctionGcRootTracker32.__init__(self, funcname, lines, filetag)
  1114. class DarwinFunctionGcRootTracker64(ElfFunctionGcRootTracker64):
  1115. format = 'darwin64'
  1116. function_names_prefix = '_'
  1117. LABEL = ElfFunctionGcRootTracker64.LABEL
  1118. r_jmptable_item = re.compile(r"\t.(?:long|quad)\t"+LABEL+"(-\"?[A-Za-z0-9$]+\"?)?\s*$")
  1119. r_functionstart = re.compile(r"_(\w+):\s*$")
  1120. OFFSET_LABELS = 0
  1121. def __init__(self, lines, filetag=0):
  1122. match = self.r_functionstart.match(lines[0])
  1123. funcname = '_' + match.group(1)
  1124. FunctionGcRootTracker64.__init__(self, funcname, lines, filetag)
  1125. class Mingw32FunctionGcRootTracker(DarwinFunctionGcRootTracker32):
  1126. format = 'mingw32'
  1127. function_names_prefix = '_'
  1128. FUNCTIONS_NOT_RETURNING = {
  1129. '_exit': None,
  1130. '__assert': None,
  1131. }
  1132. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1133. FUNCTIONS_NOT_RETURNING['_' + _name] = None
  1134. class MsvcFunctionGcRootTracker(FunctionGcRootTracker32):
  1135. format = 'msvc'
  1136. function_names_prefix = '_'
  1137. ESP = 'esp'
  1138. EBP = 'ebp'
  1139. EAX = 'eax'
  1140. CALLEE_SAVE_REGISTERS = ['ebx', 'esi', 'edi', 'ebp']
  1141. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  1142. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  1143. TOP_OF_STACK_MINUS_WORD = 'DWORD PTR [esp-4]'
  1144. OPERAND = r'(?:(:?WORD|DWORD|BYTE) PTR |OFFSET )?[_\w?:@$]*(?:[-+0-9]+)?(:?\[[-+*\w0-9]+\])?'
  1145. LABEL = r'([a-zA-Z_$@.][a-zA-Z0-9_$@.]*)'
  1146. OFFSET_LABELS = 0
  1147. r_segmentstart = re.compile(r"[_A-Z]+\tSEGMENT$")
  1148. r_segmentend = re.compile(r"[_A-Z]+\tENDS$")
  1149. r_functionstart = re.compile(r"; Function compile flags: ")
  1150. r_codestart = re.compile(LABEL+r"\s+PROC\s*(:?;.+)?\n$")
  1151. r_functionend = re.compile(LABEL+r"\s+ENDP\s*$")
  1152. r_symboldefine = re.compile(r"([_A-Za-z0-9$]+) = ([-0-9]+)\s*;.+\n")
  1153. LOCALVAR = r"eax|edx|ecx|ebx|esi|edi|ebp|DWORD PTR [-+]?\d*\[esp[-+]?\d*\]"
  1154. LOCALVARFP = LOCALVAR + r"|DWORD PTR -?\d*\[ebp\]"
  1155. r_localvarnofp = re.compile(LOCALVAR)
  1156. r_localvarfp = re.compile(LOCALVARFP)
  1157. r_localvar_esp = re.compile(r"DWORD PTR ([-+]?\d+)?\[esp([-+]?\d+)?\]")
  1158. r_localvar_ebp = re.compile(r"DWORD PTR ([-+]?\d+)?\[ebp([-+]?\d+)?\]")
  1159. r_rel_label = re.compile(r"$1") # never matches
  1160. r_jump_rel_label = re.compile(r"$1") # never matches
  1161. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+DWORD PTR ("+OPERAND+")\s*$")
  1162. r_jmptable_item = re.compile(r"\tDD\t"+LABEL+"(-\"[A-Za-z0-9$]+\")?\s*$")
  1163. r_jmptable_end = re.compile(r"[^\t\n;]")
  1164. r_gcroot_marker = re.compile(r"$1") # never matches
  1165. r_gcroot_marker_var = re.compile(r"DWORD PTR .+_constant_always_one_.+pypy_asm_gcroot")
  1166. r_gcnocollect_marker = re.compile(r"\spypy_asm_gc_nocollect\(("+OPERAND+")\);")
  1167. r_bottom_marker = re.compile(r"; .+\spypy_asm_stack_bottom\(\);")
  1168. FUNCTIONS_NOT_RETURNING = {
  1169. '__exit': None,
  1170. '__assert': None,
  1171. '__wassert': None,
  1172. '__imp__abort': None,
  1173. '__imp___wassert': None,
  1174. 'DWORD PTR __imp__abort': None,
  1175. 'DWORD PTR __imp___wassert': None,
  1176. }
  1177. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1178. FUNCTIONS_NOT_RETURNING['_' + _name] = None
  1179. @classmethod
  1180. def init_regexp(cls):
  1181. super(MsvcFunctionGcRootTracker, cls).init_regexp()
  1182. cls.r_binaryinsn = re.compile(r"\t[a-z]\w*\s+(?P<target>"+cls.OPERAND+r"),\s*(?P<source>"+cls.OPERAND+r")\s*(?:;.+)?$")
  1183. cls.r_jump = re.compile(r"\tj\w+\s+(?:SHORT |DWORD PTR )?"+cls.LABEL+"\s*$")
  1184. def __init__(self, lines, filetag=0):
  1185. self.defines = {}
  1186. for i, line in enumerate(lines):
  1187. if self.r_symboldefine.match(line):
  1188. match = self.r_symboldefine.match(line)
  1189. name = match.group(1)
  1190. value = int(match.group(2))
  1191. self.defines[name] = value
  1192. continue
  1193. match = self.r_codestart.match(line)
  1194. if match:
  1195. self.skip = i
  1196. break
  1197. funcname = match.group(1)
  1198. super(MsvcFunctionGcRootTracker, self).__init__(
  1199. funcname, lines, filetag)
  1200. def replace_symbols(self, operand):
  1201. for name, value in self.defines.items():
  1202. operand = operand.replace(name, str(value))
  1203. return operand
  1204. for name in '''
  1205. push pop mov lea
  1206. xor sub add
  1207. '''.split():
  1208. locals()['visit_' + name] = getattr(FunctionGcRootTracker32,
  1209. 'visit_' + name + 'l')
  1210. visit_int = FunctionGcRootTracker32.visit_nop
  1211. # probably not GC pointers
  1212. visit_cdq = FunctionGcRootTracker32.visit_nop
  1213. def visit_npad(self, line):
  1214. # MASM has a nasty bug: it implements "npad 5" with "add eax, 0"
  1215. # which is a not no-op because it clears flags.
  1216. # I've seen this instruction appear between "test" and "jne"...
  1217. # see http://www.masm32.com/board/index.php?topic=13122
  1218. match = self.r_unaryinsn.match(line)
  1219. arg = match.group(1)
  1220. if arg == "5":
  1221. # replace with "npad 3; npad 2"
  1222. self.lines[self.currentlineno] = "\tnpad\t3\n" "\tnpad\t2\n"
  1223. return []
  1224. def extract_immediate(self, value):
  1225. try:
  1226. return int(value)
  1227. except ValueError:
  1228. return None
  1229. def _visit_gcroot_marker(self, line=None):
  1230. # two possible patterns:
  1231. # 1. mov reg, DWORD PTR _always_one_
  1232. # imul target, reg
  1233. # 2. mov reg, DWORD PTR _always_one_
  1234. # imul reg, target
  1235. assert self.lines[self.currentlineno].startswith("\tmov\t")
  1236. mov = self.r_binaryinsn.match(self.lines[self.currentlineno])
  1237. assert re.match("DWORD PTR .+_always_one_", mov.group("source"))
  1238. reg = mov.group("target")
  1239. self.lines[self.currentlineno] = ";" + self.lines[self.currentlineno]
  1240. # the 'imul' must appear in the same block; the 'reg' must not
  1241. # appear in the instructions between
  1242. imul = None
  1243. lineno = self.currentlineno + 1
  1244. stop = False
  1245. while not stop:
  1246. line = self.lines[lineno]
  1247. if line == '\n':
  1248. stop = True
  1249. elif line.startswith("\tjmp\t"):
  1250. stop = True
  1251. elif self.r_gcroot_marker_var.search(line):
  1252. stop = True
  1253. elif (line.startswith("\tmov\t%s," % (reg,)) or
  1254. line.startswith("\tmovsx\t%s," % (reg,)) or
  1255. line.startswith("\tmovzx\t%s," % (reg,))):
  1256. # mov reg, <arg>
  1257. stop = True
  1258. elif line.startswith("\txor\t%s, %s" % (reg, reg)):
  1259. # xor reg, reg
  1260. stop = True
  1261. elif line.startswith("\timul\t"):
  1262. imul = self.r_binaryinsn.match(line)
  1263. imul_arg1 = imul.group("target")
  1264. imul_arg2 = imul.group("source")
  1265. if imul_arg1 == reg or imul_arg2 == reg:
  1266. break
  1267. # the register may not appear in other instructions
  1268. elif reg in line:
  1269. assert False, (line, lineno)
  1270. lineno += 1
  1271. else:
  1272. # No imul, the returned value is not used in this function
  1273. return []
  1274. if reg == imul_arg2:
  1275. self.lines[lineno] = ";" + self.lines[lineno]
  1276. return InsnGCROOT(self.replace_symbols(imul_arg1))
  1277. else:
  1278. assert reg == imul_arg1
  1279. self.lines[lineno] = "\tmov\t%s, %s\n" % (imul_arg1, imul_arg2)
  1280. if imul_arg2.startswith('OFFSET '):
  1281. # ignore static global variables
  1282. pass
  1283. else:
  1284. self.lines[lineno] += "\t; GCROOT\n"
  1285. return []
  1286. def insns_for_copy(self, source, target):
  1287. if self.r_gcroot_marker_var.match(source):
  1288. return self._visit_gcroot_marker()
  1289. if self.lines[self.currentlineno].endswith("\t; GCROOT\n"):
  1290. insns = [InsnGCROOT(self.replace_symbols(source))]
  1291. else:
  1292. insns = []
  1293. return insns + super(MsvcFunctionGcRootTracker, self).insns_for_copy(source, target)
  1294. MsvcFunctionGcRootTracker.init_regexp()
  1295. class AssemblerParser(object):
  1296. def __init__(self, verbose=0, shuffle=False):
  1297. self.verbose = verbose
  1298. self.shuffle = shuffle
  1299. self.gcmaptable = []
  1300. def process(self, iterlines, newfile, filename='?'):
  1301. for in_function, lines in self.find_functions(iterlines):
  1302. if in_function:
  1303. tracker = self.process_function(lines, filename)
  1304. lines = tracker.lines
  1305. self.write_newfile(newfile, lines, filename.split('.')[0])
  1306. if self.verbose == 1:
  1307. sys.stderr.write('\n')
  1308. def write_newfile(self, newfile, lines, grist):
  1309. newfile.writelines(lines)
  1310. def process_function(self, lines, filename):
  1311. tracker = self.FunctionGcRootTracker(
  1312. lines, filetag=getidentifier(filename))
  1313. if self.verbose == 1:
  1314. sys.stderr.write('.')
  1315. elif self.verbose > 1:
  1316. print >> sys.stderr, '[trackgcroot:%s] %s' % (filename,
  1317. tracker.funcname)
  1318. table = tracker.computegcmaptable(self.verbose)
  1319. if self.verbose > 1:
  1320. for label, state in table:
  1321. print >> sys.stderr, label, '\t', tracker.format_callshape(state)
  1322. table = compress_gcmaptable(table)
  1323. if self.shuffle and random.random() < 0.5:
  1324. self.gcmaptable[:0] = table
  1325. else:
  1326. self.gcmaptable.extend(table)
  1327. return tracker
  1328. class ElfAssemblerParser(AssemblerParser):
  1329. format = "elf"
  1330. FunctionGcRootTracker = ElfFunctionGcRootTracker32
  1331. def find_functions(self, iterlines):
  1332. functionlines = []
  1333. in_function = False
  1334. for line in iterlines:
  1335. if self.FunctionGcRootTracker.r_functionstart.match(line):
  1336. assert not in_function, (
  1337. "missed the end of the previous function")
  1338. yield False, functionlines
  1339. in_function = True
  1340. functionlines = []
  1341. functionlines.append(line)
  1342. if self.FunctionGcRootTracker.r_functionend.match(line):
  1343. assert in_function, (
  1344. "missed the start of the current function")
  1345. yield True, functionlines
  1346. in_function = False
  1347. functionlines = []
  1348. if in_function and ".get_pc_thunk.bx" in functionlines[0]:
  1349. in_function = False # xxx? ignore this rare unclosed stub at
  1350. # the end of the file
  1351. assert not in_function, (
  1352. "missed the end of the previous function")
  1353. yield False, functionlines
  1354. class ElfAssemblerParser64(ElfAssemblerParser):
  1355. format = "elf64"
  1356. FunctionGcRootTracker = ElfFunctionGcRootTracker64
  1357. class DarwinAssemblerParser(AssemblerParser):
  1358. format = "darwin"
  1359. FunctionGcRootTracker = DarwinFunctionGcRootTracker32
  1360. r_textstart = re.compile(r"\t.text\s*$")
  1361. # see
  1362. # http://developer.apple.com/documentation/developertools/Reference/Assembler/040-Assembler_Directives/asm_directives.html
  1363. OTHERSECTIONS = ['section', 'zerofill',
  1364. 'const', 'static_const', 'cstring',
  1365. 'literal4', 'literal8', 'literal16',
  1366. 'constructor', 'desctructor',
  1367. 'symbol_stub',
  1368. 'data', 'static_data',
  1369. 'non_lazy_symbol_pointer', 'lazy_symbol_pointer',
  1370. 'dyld', 'mod_init_func', 'mod_term_func',
  1371. 'const_data'
  1372. ]
  1373. r_sectionstart = re.compile(r"\t\.("+'|'.join(OTHERSECTIONS)+").*$")
  1374. sections_doesnt_end_function = {'cstring': True, 'const': True}
  1375. def find_functions(self, iterlines):
  1376. functionlines = []
  1377. in_text = False
  1378. in_function = False
  1379. for n, line in enumerate(iterlines):
  1380. if self.r_textstart.match(line):
  1381. in_text = True
  1382. elif self.r_sectionstart.match(line):
  1383. sectionname = self.r_sectionstart.match(line).group(1)
  1384. if (in_function and
  1385. sectionname not in self.sections_doesnt_end_function):
  1386. yield in_function, functionlines
  1387. functionlines = []
  1388. in_function = False
  1389. in_text = False
  1390. elif in_text and self.FunctionGcRootTracker.r_functionstart.match(line):
  1391. yield in_function, functionlines
  1392. functionlines = []
  1393. in_function = True
  1394. functionlines.append(line)
  1395. if functionlines:
  1396. yield in_function, functionlines
  1397. class DarwinAssemblerParser64(DarwinAssemblerParser):
  1398. format = "darwin64"
  1399. FunctionGcRootTracker = DarwinFunctionGcRootTracker64
  1400. class Mingw32AssemblerParser(DarwinAssemblerParser):
  1401. format = "mingw32"
  1402. r_sectionstart = re.compile(r"^_loc()")
  1403. FunctionGcRootTracker = Mingw32FunctionGcRootTracker
  1404. class MsvcAssemblerParser(AssemblerParser):
  1405. format = "msvc"
  1406. FunctionGcRootTracker = MsvcFunctionGcRootTracker
  1407. def find_functions(self, iterlines):
  1408. functionlines = []
  1409. in_function = False
  1410. in_segment = False
  1411. ignore_public = False
  1412. self.inline_functions = {}
  1413. for line in iterlines:
  1414. if line.startswith('; File '):
  1415. filename = line[:-1].split(' ', 2)[2]
  1416. ignore_public = ('wspiapi.h' in filename.lower())
  1417. if ignore_public:
  1418. # this header define __inline functions, that are
  1419. # still marked as PUBLIC in the generated assembler
  1420. if line.startswith(';\tCOMDAT '):
  1421. funcname = line[:-1].split(' ', 1)[1]
  1422. self.inline_functions[funcname] = True
  1423. elif line.startswith('PUBLIC\t'):
  1424. funcname = line[:-1].split('\t')[1]
  1425. self.inline_functions[funcname] = True
  1426. if self.FunctionGcRootTracker.r_segmentstart.match(line):
  1427. in_segment = True
  1428. elif self.FunctionGcRootTracker.r_functionstart.match(line):
  1429. assert not in_function, (
  1430. "missed the end of the previous function")
  1431. in_function = True
  1432. if in_segment:
  1433. yield False, functionlines
  1434. functionlines = []
  1435. functionlines.append(line)
  1436. if self.FunctionGcRootTracker.r_segmentend.match(line):
  1437. yield False, functionlines
  1438. in_segment = False
  1439. functionlines = []
  1440. elif self.FunctionGcRootTracker.r_functionend.match(line):
  1441. assert in_function, (
  1442. "missed the start of the current function")
  1443. yield True, functionlines
  1444. in_function = False
  1445. functionlines = []
  1446. assert not in_function, (
  1447. "missed the end of the previous function")
  1448. yield False, functionlines
  1449. def write_newfile(self, newfile, lines, grist):
  1450. newlines = []
  1451. for line in lines:
  1452. # truncate long comments
  1453. if line.startswith(";"):
  1454. line = line[:-1][:500] + '\n'
  1455. # Workaround a bug in the .s files generated by msvc
  1456. # compiler: every string or float constant is exported
  1457. # with a name built after its value, and will conflict
  1458. # with other modules.
  1459. if line.startswith("PUBLIC\t"):
  1460. symbol = line[:-1].split()[1]
  1461. if symbol.startswith('__real@'):
  1462. line = '; ' + line
  1463. elif symbol.startswith("__mask@@"):
  1464. line = '; ' + line
  1465. elif symbol.startswith("??_C@"):
  1466. line = '; ' + line
  1467. elif symbol == "__$ArrayPad$":
  1468. line = '; ' + line
  1469. elif symbol in self.inline_functions:
  1470. line = '; ' + line
  1471. # The msvc compiler writes "fucomip ST(1)" when the correct
  1472. # syntax is "fucomip ST, ST(1)"
  1473. if line == "\tfucomip\tST(1)\n":
  1474. line = "\tfucomip\tST, ST(1)\n"
  1475. # Because we insert labels in the code, some "SHORT" jumps
  1476. # are now longer than 127 bytes. We turn them all into
  1477. # "NEAR" jumps. Note that the assembler allocates space
  1478. # for a near jump, but still generates a short jump when
  1479. # it can.
  1480. line = line.replace('\tjmp\tSHORT ', '\tjmp\t')
  1481. line = line.replace('\tjne\tSHORT ', '\tjne\t')
  1482. line = line.replace('\tje\tSHORT ', '\tje\t')
  1483. newlines.append(line)
  1484. if line == "\t.model\tflat\n":
  1485. newlines.append("\tassume fs:nothing\n")
  1486. newfile.writelines(newlines)
  1487. PARSERS = {
  1488. 'elf': ElfAssemblerParser,
  1489. 'elf64': ElfAssemblerParser64,
  1490. 'darwin': DarwinAssemblerParser,
  1491. 'darwin64': DarwinAssemblerParser64,
  1492. 'mingw32': Mingw32AssemblerParser,
  1493. 'msvc': MsvcAssemblerParser,
  1494. }
  1495. class GcRootTracker(object):
  1496. def __init__(self, verbose=0, shuffle=False, format='elf'):
  1497. self.verbose = verbose
  1498. self.shuffle = shuffle # to debug the sorting logic in asmgcroot.py
  1499. self.format = format
  1500. self.gcmaptable = []
  1501. def dump_raw_table(self, output):
  1502. print 'raw table'
  1503. for entry in self.gcmaptable:
  1504. print >> output, entry
  1505. def reload_raw_table(self, input):
  1506. firstline = input.readline()
  1507. assert firstline == 'raw table\n'
  1508. for line in input:
  1509. entry = eval(line)
  1510. assert type(entry) is tuple
  1511. self.gcmaptable.append(entry)
  1512. def dump(self, output):
  1513. def _globalname(name, disp=""):
  1514. return tracker_cls.function_names_prefix + name
  1515. def _variant(**kwargs):
  1516. txt = kwargs[self.format]
  1517. print >> output, "\t%s" % txt
  1518. if self.format in ('elf64', 'darwin64'):
  1519. word_decl = '.quad'
  1520. else:
  1521. word_decl = '.long'
  1522. tracker_cls = PARSERS[self.format].FunctionGcRootTracker
  1523. # The pypy_asm_stackwalk() function
  1524. if self.format == 'msvc':
  1525. print >> output, """\
  1526. /* See description in asmgcroot.py */
  1527. __declspec(naked)
  1528. long pypy_asm_stackwalk(void *callback)
  1529. {
  1530. __asm {
  1531. mov\tedx, DWORD PTR [esp+4]\t; 1st argument, which is the callback
  1532. mov\tecx, DWORD PTR [esp+8]\t; 2nd argument, which is gcrootanchor
  1533. mov\teax, esp\t\t; my frame top address
  1534. push\teax\t\t\t; ASM_FRAMEDATA[6]
  1535. push\tebp\t\t\t; ASM_FRAMEDATA[5]
  1536. push\tedi\t\t\t; ASM_FRAMEDATA[4]
  1537. push\tesi\t\t\t; ASM_FRAMEDATA[3]
  1538. push\tebx\t\t\t; ASM_FRAMEDATA[2]
  1539. ; Add this ASM_FRAMEDATA to the front of the circular linked
  1540. ; list. Let's call it 'self'.
  1541. mov\teax, DWORD PTR [ecx+4]\t\t; next = gcrootanchor->next
  1542. push\teax\t\t\t\t\t\t\t\t\t; self->next = next
  1543. push\tecx ; self->prev = gcrootanchor
  1544. mov\tDWORD PTR [ecx+4], esp\t\t; gcrootanchor->next = self
  1545. mov\tDWORD PTR [eax+0], esp\t\t\t\t\t; next->prev = self
  1546. call\tedx\t\t\t\t\t\t; invoke the callback
  1547. ; Detach this ASM_FRAMEDATA from the circular linked list
  1548. pop\tesi\t\t\t\t\t\t\t; prev = self->prev
  1549. pop\tedi\t\t\t\t\t\t\t; next = self->next
  1550. mov\tDWORD PTR [esi+4], edi\t\t; prev->next = next
  1551. mov\tDWORD PTR [edi+0], esi\t\t; next->prev = prev
  1552. pop\tebx\t\t\t\t; restore from ASM_FRAMEDATA[2]
  1553. pop\tesi\t\t\t\t; restore from ASM_FRAMEDATA[3]
  1554. pop\tedi\t\t\t\t; restore from ASM_FRAMEDATA[4]
  1555. pop\tebp\t\t\t\t; restore from ASM_FRAMEDATA[5]
  1556. pop\tecx\t\t\t\t; ignored ASM_FRAMEDATA[6]
  1557. ; the return value is the one of the 'call' above,
  1558. ; because %eax (and possibly %edx) are unmodified
  1559. ret
  1560. }
  1561. }
  1562. """
  1563. elif self.format in ('elf64', 'darwin64'):
  1564. if self.format == 'elf64': # gentoo patch: hardened systems
  1565. print >> output, "\t.section .note.GNU-stack,\"\",%progbits"
  1566. print >> output, "\t.text"
  1567. print >> output, "\t.globl %s" % _globalname('pypy_asm_stackwalk')
  1568. _variant(elf64='.type pypy_asm_stackwalk, @function',
  1569. darwin64='')
  1570. print >> output, "%s:" % _globalname('pypy_asm_stackwalk')
  1571. s = """\
  1572. /* See description in asmgcroot.py */
  1573. .cfi_startproc
  1574. /* %rdi is the 1st argument, which is the callback */
  1575. /* %rsi is the 2nd argument, which is gcrootanchor */
  1576. movq\t%rsp, %rax\t/* my frame top address */
  1577. pushq\t%rax\t\t/* ASM_FRAMEDATA[8] */
  1578. pushq\t%rbp\t\t/* ASM_FRAMEDATA[7] */
  1579. pushq\t%r15\t\t/* ASM_FRAMEDATA[6] */
  1580. pushq\t%r14\t\t/* ASM_FRAMEDATA[5] */
  1581. pushq\t%r13\t\t/* ASM_FRAMEDATA[4] */
  1582. pushq\t%r12\t\t/* ASM_FRAMEDATA[3] */
  1583. pushq\t%rbx\t\t/* ASM_FRAMEDATA[2] */
  1584. /* Add this ASM_FRAMEDATA to the front of the circular linked */
  1585. /* list. Let's call it 'self'. */
  1586. movq\t8(%rsi), %rax\t/* next = gcrootanchor->next */
  1587. pushq\t%rax\t\t\t\t/* self->next = next */
  1588. pushq\t%rsi\t\t\t/* self->prev = gcrootanchor */
  1589. movq\t%rsp, 8(%rsi)\t/* gcrootanchor->next = self */
  1590. movq\t%rsp, 0(%rax)\t\t\t/* next->prev = self */
  1591. .cfi_def_cfa_offset 80\t/* 9 pushes + the retaddr = 80 bytes */
  1592. /* note: the Mac OS X 16 bytes aligment must be respected. */
  1593. call\t*%rdi\t\t/* invoke the callback */
  1594. /* Detach this ASM_FRAMEDATA from the circular linked list */
  1595. popq\t%rsi\t\t/* prev = self->prev */
  1596. popq\t%rdi\t\t/* next = self->next */
  1597. movq\t%rdi, 8(%rsi)\t/* prev->next = next */
  1598. movq\t%rsi, 0(%rdi)\t/* next->prev = prev */
  1599. popq\t%rbx\t\t/* restore from ASM_FRAMEDATA[2] */
  1600. popq\t%r12\t\t/* restore from ASM_FRAMEDATA[3] */
  1601. popq\t%r13\t\t/* restore from ASM_FRAMEDATA[4] */
  1602. popq\t%r14\t\t/* restore from ASM_FRAMEDATA[5] */
  1603. popq\t%r15\t\t/* restore from ASM_FRAMEDATA[6] */
  1604. popq\t%rbp\t\t/* restore from ASM_FRAMEDATA[7] */
  1605. popq\t%rcx\t\t/* ignored ASM_FRAMEDATA[8] */
  1606. /* the return value is the one of the 'call' above, */
  1607. /* because %rax is unmodified */
  1608. ret
  1609. .cfi_endproc
  1610. """
  1611. if self.format == 'darwin64':
  1612. # obscure. gcc there seems not to support .cfi_...
  1613. # hack it out...
  1614. s = re.sub(r'([.]cfi_[^/\n]+)([/\n])',
  1615. r'/* \1 disabled on darwin */\2', s)
  1616. print >> output, s
  1617. _variant(elf64='.size pypy_asm_stackwalk, .-pypy_asm_stackwalk',
  1618. darwin64='')
  1619. else:
  1620. print >> output, "\t.text"
  1621. print >> output, "\t.globl %s" % _globalname('pypy_asm_stackwalk')
  1622. _variant(elf='.type pypy_asm_stackwalk, @function',
  1623. darwin='',
  1624. mingw32='')
  1625. print >> output, "%s:" % _globalname('pypy_asm_stackwalk')
  1626. print >> output, """\
  1627. /* See description in asmgcroot.py */
  1628. movl\t4(%esp), %edx\t/* 1st argument, which is the callback */
  1629. movl\t8(%esp), %ecx\t/* 2nd argument, which is gcrootanchor */
  1630. movl\t%esp, %eax\t/* my frame top address */
  1631. pushl\t%eax\t\t/* ASM_FRAMEDATA[6] */
  1632. pushl\t%ebp\t\t/* ASM_FRAMEDATA[5] */
  1633. pushl\t%edi\t\t/* ASM_FRAMEDATA[4] */
  1634. pushl\t%esi\t\t/* ASM_FRAMEDATA[3] */
  1635. pushl\t%ebx\t\t/* ASM_FRAMEDATA[2] */
  1636. /* Add this ASM_FRAMEDATA to the front of the circular linked */
  1637. /* list. Let's call it 'self'. */
  1638. movl\t4(%ecx), %eax\t/* next = gcrootanchor->next */
  1639. pushl\t%eax\t\t\t\t/* self->next = next */
  1640. pushl\t%ecx\t\t\t/* self->prev = gcrootanchor */
  1641. movl\t%esp, 4(%ecx)\t/* gcrootanchor->next = self */
  1642. movl\t%esp, 0(%eax)\t\t\t/* next->prev = self */
  1643. /* note: the Mac OS X 16 bytes aligment must be respected. */
  1644. call\t*%edx\t\t/* invoke the callback */
  1645. /* Detach this ASM_FRAMEDATA from the circular linked list */
  1646. popl\t%esi\t\t/* prev = self->prev */
  1647. popl\t%edi\t\t/* next = self->next */
  1648. movl\t%edi, 4(%esi)\t/* prev->next = next */
  1649. movl\t%esi, 0(%edi)\t/* next->prev = prev */
  1650. popl\t%ebx\t\t/* restore from ASM_FRAMEDATA[2] */
  1651. popl\t%esi\t\t/* restore from ASM_FRAMEDATA[3] */
  1652. popl\t%edi\t\t/* restore from ASM_FRAMEDATA[4] */
  1653. popl\t%ebp\t\t/* restore from ASM_FRAMEDATA[5] */
  1654. popl\t%ecx\t\t/* ignored ASM_FRAMEDATA[6] */
  1655. /* the return value is the one of the 'call' above, */
  1656. /* because %eax (and possibly %edx) are unmodified */
  1657. ret
  1658. """
  1659. _variant(elf='.size pypy_asm_stackwalk, .-pypy_asm_stackwalk',
  1660. darwin='',
  1661. mingw32='')
  1662. if self.format == 'msvc':
  1663. for label, state, is_range in self.gcmaptable:
  1664. label = label[1:]
  1665. print >> output, "extern void* %s;" % label
  1666. shapes = {}
  1667. shapelines = []
  1668. shapeofs = 0
  1669. # write the tables
  1670. if self.format == 'msvc':
  1671. print >> output, """\
  1672. static struct { void* addr; long shape; } __gcmap[%d] = {
  1673. """ % (len(self.gcmaptable),)
  1674. for label, state, is_range in self.gcmaptable:
  1675. label = label[1:]
  1676. try:
  1677. n = shapes[state]
  1678. except KeyError:
  1679. n = shapes[state] = shapeofs
  1680. bytes = [str(b) for b in tracker_cls.compress_callshape(state)]
  1681. shapelines.append('\t%s,\t/* %s */\n' % (
  1682. ', '.join(bytes),
  1683. shapeofs))
  1684. shapeofs += len(bytes)
  1685. if is_range:
  1686. n = ~ n
  1687. print >> output, '{ &%s, %d},' % (label, n)
  1688. print >> output, """\
  1689. };
  1690. void* __gcmapstart = __gcmap;
  1691. void* __gcmapend = __gcmap + %d;
  1692. char __gccallshapes[] = {
  1693. """ % (len(self.gcmaptable),)
  1694. output.writelines(shapelines)
  1695. print >> output, """\
  1696. };
  1697. """
  1698. else:
  1699. print >> output, """\
  1700. .data
  1701. .align 4
  1702. .globl __gcmapstart
  1703. __gcmapstart:
  1704. """.replace("__gcmapstart", _globalname("__gcmapstart"))
  1705. for label, state, is_range in self.gcmaptable:
  1706. try:
  1707. n = shapes[state]
  1708. except KeyError:
  1709. n = shapes[state] = shapeofs
  1710. bytes = [str(b) for b in tracker_cls.compress_callshape(state)]
  1711. shapelines.append('\t/*%d*/\t.byte\t%s\n' % (
  1712. shapeofs,
  1713. ', '.join(bytes)))
  1714. shapeofs += len(bytes)
  1715. if is_range:
  1716. n = ~ n
  1717. print >> output, '\t%s\t%s-%d' % (
  1718. word_decl,
  1719. label,
  1720. tracker_cls.OFFSET_LABELS)
  1721. print >> output, '\t%s\t%d' % (word_decl, n)
  1722. print >> output, """\
  1723. .globl __gcmapend
  1724. __gcmapend:
  1725. """.replace("__gcmapend", _globalname("__gcmapend"))
  1726. _variant(elf='.section\t.rodata',
  1727. elf64='.section\t.rodata',
  1728. darwin='.const',
  1729. darwin64='.const',
  1730. mingw32='')
  1731. print >> output, """\
  1732. .globl __gccallshapes
  1733. __gccallshapes:
  1734. """.replace("__gccallshapes", _globalname("__gccallshapes"))
  1735. output.writelines(shapelines)
  1736. print >> output, """\
  1737. #if defined(__linux__) && defined(__ELF__)
  1738. .section .note.GNU-stack,"",%progbits
  1739. #endif
  1740. """
  1741. def process(self, iterlines, newfile, filename='?'):
  1742. parser = PARSERS[format](verbose=self.verbose, shuffle=self.shuffle)
  1743. for in_function, lines in parser.find_functions(iterlines):
  1744. if in_function:
  1745. tracker = parser.process_function(lines, filename)
  1746. lines = tracker.lines
  1747. parser.write_newfile(newfile, lines, filename.split('.')[0])
  1748. if self.verbose == 1:
  1749. sys.stderr.write('\n')
  1750. if self.shuffle and random.random() < 0.5:
  1751. self.gcmaptable[:0] = parser.gcmaptable
  1752. else:
  1753. self.gcmaptable.extend(parser.gcmaptable)
  1754. class UnrecognizedOperation(Exception):
  1755. pass
  1756. class NoPatternMatch(Exception):
  1757. pass
  1758. # __________ table compression __________
  1759. def compress_gcmaptable(table):
  1760. # Compress ranges table[i:j] of entries with the same state
  1761. # into a single entry whose label is the start of the range.
  1762. # The last element in the table is never compressed in this
  1763. # way for debugging reasons, to avoid that a random address
  1764. # in memory gets mapped to the last element in the table
  1765. # just because it's the closest address.
  1766. # To be on the safe side, compress_gcmaptable() should be called
  1767. # after each function processed -- otherwise the result depends on
  1768. # the linker not rearranging the functions in memory, which is
  1769. # fragile (and wrong e.g. with "make profopt").
  1770. i = 0
  1771. limit = len(table) - 1 # only process entries table[:limit]
  1772. while i < len(table):
  1773. label1, state = table[i]
  1774. is_range = False
  1775. j = i + 1
  1776. while j < limit and table[j][1] == state:
  1777. is_range = True
  1778. j += 1
  1779. # now all entries in table[i:j] have the same state
  1780. yield (label1, state, is_range)
  1781. i = j
  1782. def getidentifier(s):
  1783. def mapchar(c):
  1784. if c.isalnum():
  1785. return c
  1786. else:
  1787. return '_'
  1788. if s.endswith('.s'):
  1789. s = s[:-2]
  1790. s = ''.join([mapchar(c) for c in s])
  1791. while s.endswith('__'):
  1792. s = s[:-1]
  1793. return s
  1794. if __name__ == '__main__':
  1795. verbose = 0
  1796. shuffle = False
  1797. output_raw_table = False
  1798. if sys.platform == 'darwin':
  1799. if sys.maxint > 2147483647:
  1800. format = 'darwin64'
  1801. else:
  1802. format = 'darwin'
  1803. elif sys.platform == 'win32':
  1804. format = 'mingw32'
  1805. else:
  1806. if sys.maxint > 2147483647:
  1807. format = 'elf64'
  1808. else:
  1809. format = 'elf'
  1810. while len(sys.argv) > 1:
  1811. if sys.argv[1] == '-v':
  1812. del sys.argv[1]
  1813. verbose = sys.maxint
  1814. elif sys.argv[1] == '-r':
  1815. del sys.argv[1]
  1816. shuffle = True
  1817. elif sys.argv[1] == '-t':
  1818. del sys.argv[1]
  1819. output_raw_table = True
  1820. elif sys.argv[1].startswith('-f'):
  1821. format = sys.argv[1][2:]
  1822. del sys.argv[1]
  1823. elif sys.argv[1].startswith('-'):
  1824. print >> sys.stderr, "unrecognized option:", sys.argv[1]
  1825. sys.exit(1)
  1826. else:
  1827. break
  1828. tracker = GcRootTracker(verbose=verbose, shuffle=shuffle, format=format)
  1829. for fn in sys.argv[1:]:
  1830. f = open(fn, 'r')
  1831. firstline = f.readline()
  1832. f.seek(0)
  1833. assert firstline, "file %r is empty!" % (fn,)
  1834. if firstline == 'raw table\n':
  1835. tracker.reload_raw_table(f)
  1836. f.close()
  1837. else:
  1838. assert fn.endswith('.s'), fn
  1839. lblfn = fn[:-2] + '.lbl.s'
  1840. g = open(lblfn, 'w')
  1841. try:
  1842. tracker.process(f, g, filename=fn)
  1843. except:
  1844. g.close()
  1845. os.unlink(lblfn)
  1846. raise
  1847. g.close()
  1848. f.close()
  1849. if output_raw_table:
  1850. tracker.dump_raw_table(sys.stdout)
  1851. if not output_raw_table:
  1852. tracker.dump(sys.stdout)