PageRenderTime 165ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

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

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