PageRenderTime 82ms CodeModel.GetById 37ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/translator/c/gcc/trackgcroot.py

https://bitbucket.org/mikestewart/pypy
Python | 2033 lines | 1880 code | 66 blank | 87 comment | 183 complexity | 2952b5dcd162bbcb07413af3b4fce814 MD5 | raw file
  1. #! /usr/bin/env python
  2. import autopath
  3. import re, sys, os, random
  4. from pypy.translator.c.gcc.instruction import Insn, Label, InsnCall, InsnRet
  5. from pypy.translator.c.gcc.instruction import InsnFunctionStart, InsnStop
  6. from pypy.translator.c.gcc.instruction import InsnSetLocal, InsnCopyLocal
  7. from pypy.translator.c.gcc.instruction import InsnPrologue, InsnEpilogue
  8. from pypy.translator.c.gcc.instruction import InsnGCROOT, InsnCondJump
  9. from pypy.translator.c.gcc.instruction import InsnStackAdjust
  10. from pypy.translator.c.gcc.instruction import InsnCannotFollowEsp
  11. from pypy.translator.c.gcc.instruction import LocalVar, somenewvalue
  12. from pypy.translator.c.gcc.instruction import frameloc_esp, frameloc_ebp
  13. from pypy.translator.c.gcc.instruction import LOC_REG, LOC_NOWHERE, LOC_MASK
  14. from pypy.translator.c.gcc.instruction import LOC_EBP_PLUS, LOC_EBP_MINUS
  15. from pypy.translator.c.gcc.instruction import LOC_ESP_PLUS
  16. class FunctionGcRootTracker(object):
  17. skip = 0
  18. COMMENT = "([#;].*)?"
  19. @classmethod
  20. def init_regexp(cls):
  21. cls.r_label = re.compile(cls.LABEL+"[:]\s*$")
  22. cls.r_globl = re.compile(r"\t[.]globl\t"+cls.LABEL+"\s*$")
  23. cls.r_globllabel = re.compile(cls.LABEL+r"=[.][+]%d\s*$"%cls.OFFSET_LABELS)
  24. cls.r_insn = re.compile(r"\t([a-z]\w*)\s")
  25. cls.r_unaryinsn = re.compile(r"\t[a-z]\w*\s+("+cls.OPERAND+")\s*" + cls.COMMENT + "$")
  26. cls.r_binaryinsn = re.compile(r"\t[a-z]\w*\s+(?P<source>"+cls.OPERAND+"),\s*(?P<target>"+cls.OPERAND+")\s*$")
  27. cls.r_jump = re.compile(r"\tj\w+\s+"+cls.LABEL+"\s*" + cls.COMMENT + "$")
  28. cls.r_jmp_switch = re.compile(r"\tjmp\t[*]"+cls.LABEL+"[(]")
  29. cls.r_jmp_source = re.compile(r"\d*[(](%[\w]+)[,)]")
  30. def __init__(self, funcname, lines, filetag=0):
  31. self.funcname = funcname
  32. self.lines = lines
  33. self.uses_frame_pointer = False
  34. self.r_localvar = self.r_localvarnofp
  35. self.filetag = filetag
  36. # a "stack bottom" function is either pypy_main_function() or a
  37. # callback from C code. In both cases they are identified by
  38. # the presence of pypy_asm_stack_bottom().
  39. self.is_stack_bottom = False
  40. def computegcmaptable(self, verbose=0):
  41. if self.funcname in ['main', '_main']:
  42. return [] # don't analyze main(), its prologue may contain
  43. # strange instructions
  44. self.findlabels()
  45. self.parse_instructions()
  46. try:
  47. self.trim_unreachable_instructions()
  48. self.find_noncollecting_calls()
  49. if not self.list_collecting_call_insns():
  50. return []
  51. self.findframesize()
  52. self.fixlocalvars()
  53. self.trackgcroots()
  54. self.extend_calls_with_labels()
  55. finally:
  56. if verbose > 2:
  57. self.dump()
  58. return self.gettable()
  59. def replace_symbols(self, operand):
  60. return operand
  61. def gettable(self):
  62. """Returns a list [(label_after_call, callshape_tuple)]
  63. See format_callshape() for more details about callshape_tuple.
  64. """
  65. table = []
  66. for insn in self.list_collecting_call_insns():
  67. if not hasattr(insn, 'framesize'):
  68. continue # calls that never end up reaching a RET
  69. if self.is_stack_bottom:
  70. retaddr = LOC_NOWHERE # end marker for asmgcroot.py
  71. elif self.uses_frame_pointer:
  72. retaddr = frameloc_ebp(self.WORD, self.WORD)
  73. else:
  74. retaddr = frameloc_esp(insn.framesize, self.WORD)
  75. shape = [retaddr]
  76. # the first gcroots are always the ones corresponding to
  77. # the callee-saved registers
  78. for reg in self.CALLEE_SAVE_REGISTERS:
  79. shape.append(LOC_NOWHERE)
  80. gcroots = []
  81. for localvar, tag in insn.gcroots.items():
  82. if isinstance(localvar, LocalVar):
  83. loc = localvar.getlocation(insn.framesize,
  84. self.uses_frame_pointer,
  85. self.WORD)
  86. elif localvar in self.REG2LOC:
  87. loc = self.REG2LOC[localvar]
  88. else:
  89. assert False, "%s: %s" % (self.funcname,
  90. localvar)
  91. assert isinstance(loc, int)
  92. if tag is None:
  93. gcroots.append(loc)
  94. else:
  95. regindex = self.CALLEE_SAVE_REGISTERS.index(tag)
  96. shape[1 + regindex] = loc
  97. if LOC_NOWHERE in shape and not self.is_stack_bottom:
  98. reg = self.CALLEE_SAVE_REGISTERS[shape.index(LOC_NOWHERE) - 1]
  99. raise AssertionError("cannot track where register %s is saved"
  100. % (reg,))
  101. gcroots.sort()
  102. shape.extend(gcroots)
  103. table.append((insn.global_label, tuple(shape)))
  104. return table
  105. def findlabels(self):
  106. self.labels = {} # {name: Label()}
  107. for lineno, line in enumerate(self.lines):
  108. match = self.r_label.match(line)
  109. label = None
  110. if match:
  111. label = match.group(1)
  112. else:
  113. # labels used by: j* NNNf
  114. match = self.r_rel_label.match(line)
  115. if match:
  116. label = "rel %d" % lineno
  117. if label:
  118. assert label not in self.labels, "duplicate label: %s" % label
  119. self.labels[label] = Label(label, lineno)
  120. def trim_unreachable_instructions(self):
  121. reached = set([self.insns[0]])
  122. prevlen = 0
  123. while len(reached) > prevlen:
  124. prevlen = len(reached)
  125. for insn in self.insns:
  126. if insn not in reached:
  127. for previnsn in insn.previous_insns:
  128. if previnsn in reached:
  129. # this instruction is reachable too
  130. reached.add(insn)
  131. break
  132. # now kill all unreachable instructions
  133. i = 0
  134. while i < len(self.insns):
  135. if self.insns[i] in reached:
  136. i += 1
  137. else:
  138. del self.insns[i]
  139. def find_noncollecting_calls(self):
  140. cannot_collect = {}
  141. for line in self.lines:
  142. match = self.r_gcnocollect_marker.search(line)
  143. if match:
  144. name = match.group(1)
  145. cannot_collect[name] = True
  146. #
  147. self.cannot_collect = dict.fromkeys(
  148. [self.function_names_prefix + name for name in cannot_collect])
  149. def append_instruction(self, insn):
  150. # Add the instruction to the list, and link it to the previous one.
  151. previnsn = self.insns[-1]
  152. self.insns.append(insn)
  153. if (isinstance(insn, (InsnSetLocal, InsnCopyLocal)) and
  154. insn.target == self.tested_for_zero):
  155. self.tested_for_zero = None
  156. try:
  157. lst = insn.previous_insns
  158. except AttributeError:
  159. lst = insn.previous_insns = []
  160. if not isinstance(previnsn, InsnStop):
  161. lst.append(previnsn)
  162. def parse_instructions(self):
  163. self.insns = [InsnFunctionStart(self.CALLEE_SAVE_REGISTERS, self.WORD)]
  164. self.tested_for_zero = None
  165. ignore_insns = False
  166. for lineno, line in enumerate(self.lines):
  167. if lineno < self.skip:
  168. continue
  169. self.currentlineno = lineno
  170. insn = []
  171. match = self.r_insn.match(line)
  172. if self.r_bottom_marker.match(line):
  173. self.is_stack_bottom = True
  174. elif match:
  175. if not ignore_insns:
  176. opname = match.group(1)
  177. #
  178. try:
  179. cf = self.OPS_WITH_PREFIXES_CHANGING_FLAGS[opname]
  180. except KeyError:
  181. cf = self.find_missing_changing_flags(opname)
  182. if cf:
  183. self.tested_for_zero = None
  184. #
  185. try:
  186. meth = getattr(self, 'visit_' + opname)
  187. except AttributeError:
  188. self.find_missing_visit_method(opname)
  189. meth = getattr(self, 'visit_' + opname)
  190. line = line.rsplit(';', 1)[0]
  191. insn = meth(line)
  192. elif self.r_gcroot_marker.match(line):
  193. insn = self._visit_gcroot_marker(line)
  194. elif line == '\t/* ignore_in_trackgcroot */\n':
  195. ignore_insns = True
  196. elif line == '\t/* end_ignore_in_trackgcroot */\n':
  197. ignore_insns = False
  198. else:
  199. match = self.r_label.match(line)
  200. if match:
  201. insn = self.labels[match.group(1)]
  202. if isinstance(insn, list):
  203. for i in insn:
  204. self.append_instruction(i)
  205. else:
  206. self.append_instruction(insn)
  207. del self.currentlineno
  208. @classmethod
  209. def find_missing_visit_method(cls, opname):
  210. # only for operations that are no-ops as far as we are concerned
  211. prefix = opname
  212. while prefix not in cls.IGNORE_OPS_WITH_PREFIXES:
  213. prefix = prefix[:-1]
  214. if not prefix:
  215. raise UnrecognizedOperation(opname)
  216. setattr(cls, 'visit_' + opname, cls.visit_nop)
  217. @classmethod
  218. def find_missing_changing_flags(cls, opname):
  219. prefix = opname
  220. while prefix and prefix not in cls.OPS_WITH_PREFIXES_CHANGING_FLAGS:
  221. prefix = prefix[:-1]
  222. cf = cls.OPS_WITH_PREFIXES_CHANGING_FLAGS.get(prefix, False)
  223. cls.OPS_WITH_PREFIXES_CHANGING_FLAGS[opname] = cf
  224. return cf
  225. def list_collecting_call_insns(self):
  226. return [insn for insn in self.insns if isinstance(insn, InsnCall)
  227. if insn.name not in self.cannot_collect]
  228. def findframesize(self):
  229. # the 'framesize' attached to an instruction is the number of bytes
  230. # in the frame at this point. This doesn't count the return address
  231. # which is the word immediately following the frame in memory.
  232. # The 'framesize' is set to an odd value if it is only an estimate
  233. # (see InsnCannotFollowEsp).
  234. def walker(insn, size_delta):
  235. check = deltas.setdefault(insn, size_delta)
  236. assert check == size_delta, (
  237. "inconsistent frame size at instruction %s" % (insn,))
  238. if isinstance(insn, InsnStackAdjust):
  239. size_delta -= insn.delta
  240. if not hasattr(insn, 'framesize'):
  241. yield size_delta # continue walking backwards
  242. for insn in self.insns:
  243. if isinstance(insn, (InsnRet, InsnEpilogue, InsnGCROOT)):
  244. deltas = {}
  245. self.walk_instructions_backwards(walker, insn, 0)
  246. size_at_insn = []
  247. for insn1, delta1 in deltas.items():
  248. if hasattr(insn1, 'framesize'):
  249. size_at_insn.append(insn1.framesize + delta1)
  250. if not size_at_insn:
  251. continue
  252. size_at_insn = size_at_insn[0]
  253. for insn1, delta1 in deltas.items():
  254. size_at_insn1 = size_at_insn - delta1
  255. if hasattr(insn1, 'framesize'):
  256. assert insn1.framesize == size_at_insn1, (
  257. "inconsistent frame size at instruction %s" %
  258. (insn1,))
  259. else:
  260. insn1.framesize = size_at_insn1
  261. def fixlocalvars(self):
  262. def fixvar(localvar):
  263. if localvar is None:
  264. return None
  265. elif isinstance(localvar, (list, tuple)):
  266. return [fixvar(var) for var in localvar]
  267. match = self.r_localvar_esp.match(localvar)
  268. if match:
  269. if localvar == self.TOP_OF_STACK_MINUS_WORD:
  270. # for pushl and popl, by
  271. hint = None # default ebp addressing is
  272. else: # a bit nicer
  273. hint = 'esp'
  274. ofs_from_esp = int(match.group(1) or '0')
  275. if self.format == 'msvc':
  276. ofs_from_esp += int(match.group(2) or '0')
  277. localvar = ofs_from_esp - insn.framesize
  278. assert localvar != 0 # that's the return address
  279. return LocalVar(localvar, hint=hint)
  280. elif self.uses_frame_pointer:
  281. match = self.r_localvar_ebp.match(localvar)
  282. if match:
  283. ofs_from_ebp = int(match.group(1) or '0')
  284. if self.format == 'msvc':
  285. ofs_from_ebp += int(match.group(2) or '0')
  286. localvar = ofs_from_ebp - self.WORD
  287. assert localvar != 0 # that's the return address
  288. return LocalVar(localvar, hint='ebp')
  289. return localvar
  290. for insn in self.insns:
  291. if not hasattr(insn, 'framesize'):
  292. continue
  293. for name in insn._locals_:
  294. localvar = getattr(insn, name)
  295. setattr(insn, name, fixvar(localvar))
  296. def trackgcroots(self):
  297. def walker(insn, loc):
  298. source = insn.source_of(loc, tag)
  299. if source is somenewvalue:
  300. pass # done
  301. else:
  302. yield source
  303. for insn in self.insns:
  304. for loc, tag in insn.requestgcroots(self).items():
  305. self.walk_instructions_backwards(walker, insn, loc)
  306. def dump(self):
  307. for insn in self.insns:
  308. size = getattr(insn, 'framesize', '?')
  309. print >> sys.stderr, '%4s %s' % (size, insn)
  310. def walk_instructions_backwards(self, walker, initial_insn, initial_state):
  311. pending = []
  312. seen = {}
  313. def schedule(insn, state):
  314. for previnsn in insn.previous_insns:
  315. key = previnsn, state
  316. if key not in seen:
  317. seen[key] = True
  318. pending.append(key)
  319. schedule(initial_insn, initial_state)
  320. while pending:
  321. insn, state = pending.pop()
  322. for prevstate in walker(insn, state):
  323. schedule(insn, prevstate)
  324. def extend_calls_with_labels(self):
  325. # walk backwards, because inserting the global labels in self.lines
  326. # is going to invalidate the lineno of all the InsnCall objects
  327. # after the current one.
  328. for call in self.list_collecting_call_insns()[::-1]:
  329. if hasattr(call, 'framesize'):
  330. self.create_global_label(call)
  331. def create_global_label(self, call):
  332. # we need a globally-declared label just after the call.
  333. # Reuse one if it is already there (e.g. from a previous run of this
  334. # script); otherwise invent a name and add the label to tracker.lines.
  335. label = None
  336. # this checks for a ".globl NAME" followed by "NAME:"
  337. match = self.r_globl.match(self.lines[call.lineno+1])
  338. if match:
  339. label1 = match.group(1)
  340. match = self.r_globllabel.match(self.lines[call.lineno+2])
  341. if match:
  342. label2 = match.group(1)
  343. if label1 == label2:
  344. label = label2
  345. if label is None:
  346. k = call.lineno
  347. if self.format == 'msvc':
  348. # Some header files (ws2tcpip.h) define STDCALL functions
  349. funcname = self.funcname.split('@')[0]
  350. else:
  351. funcname = self.funcname
  352. while 1:
  353. label = '__gcmap_%s__%s_%d' % (self.filetag, funcname, k)
  354. if label not in self.labels:
  355. break
  356. k += 1
  357. self.labels[label] = None
  358. if self.format == 'msvc':
  359. self.lines.insert(call.lineno+1, '%s::\n' % (label,))
  360. self.lines.insert(call.lineno+1, 'PUBLIC\t%s\n' % (label,))
  361. else:
  362. # These global symbols are not directly labels pointing to the
  363. # code location because such global labels in the middle of
  364. # functions confuse gdb. Instead, we add to the global symbol's
  365. # value a big constant, which is subtracted again when we need
  366. # the original value for gcmaptable.s. That's a hack.
  367. self.lines.insert(call.lineno+1, '%s=.+%d\n' % (label,
  368. self.OFFSET_LABELS))
  369. self.lines.insert(call.lineno+1, '\t.globl\t%s\n' % (label,))
  370. call.global_label = label
  371. @classmethod
  372. def compress_callshape(cls, shape):
  373. # For a single shape, this turns the list of integers into a list of
  374. # bytes and reverses the order of the entries. The length is
  375. # encoded by inserting a 0 marker after the gc roots coming from
  376. # shape[N:] and before the N values coming from shape[N-1] to
  377. # shape[0] (for N == 5 on 32-bit or 7 on 64-bit platforms).
  378. # In practice it seems that shapes contain many integers
  379. # whose value is up to a few thousands, which the algorithm below
  380. # compresses down to 2 bytes. Very small values compress down to a
  381. # single byte.
  382. # Callee-save regs plus ret addr
  383. min_size = len(cls.CALLEE_SAVE_REGISTERS) + 1
  384. assert len(shape) >= min_size
  385. shape = list(shape)
  386. assert 0 not in shape[min_size:]
  387. shape.insert(min_size, 0)
  388. result = []
  389. for loc in shape:
  390. assert loc >= 0
  391. flag = 0
  392. while loc >= 0x80:
  393. result.append(int(loc & 0x7F) | flag)
  394. flag = 0x80
  395. loc >>= 7
  396. result.append(int(loc) | flag)
  397. result.reverse()
  398. return result
  399. @classmethod
  400. def decompress_callshape(cls, bytes):
  401. # For tests. This logic is copied in asmgcroot.py.
  402. result = []
  403. n = 0
  404. while n < len(bytes):
  405. value = 0
  406. while True:
  407. b = bytes[n]
  408. n += 1
  409. value += b
  410. if b < 0x80:
  411. break
  412. value = (value - 0x80) << 7
  413. result.append(value)
  414. result.reverse()
  415. assert result[5] == 0
  416. del result[5]
  417. return result
  418. # ____________________________________________________________
  419. BASE_FUNCTIONS_NOT_RETURNING = {
  420. 'abort': None,
  421. 'pypy_debug_catch_fatal_exception': None,
  422. 'RPyAbort': None,
  423. 'RPyAssertFailed': None,
  424. }
  425. def _visit_gcroot_marker(self, line):
  426. match = self.r_gcroot_marker.match(line)
  427. loc = match.group(1)
  428. return InsnGCROOT(self.replace_symbols(loc))
  429. def visit_nop(self, line):
  430. return []
  431. IGNORE_OPS_WITH_PREFIXES = dict.fromkeys([
  432. 'cmp', 'test', 'set', 'sahf', 'lahf', 'cld', 'std',
  433. 'rep', 'movs', 'movhp', 'lods', 'stos', 'scas', 'cwde', 'prefetch',
  434. # floating-point operations cannot produce GC pointers
  435. 'f',
  436. 'cvt', 'ucomi', 'comi', 'subs', 'subp' , 'adds', 'addp', 'xorp',
  437. 'movap', 'movd', 'movlp', 'movup', 'sqrt', 'rsqrt', 'movhpd',
  438. 'mins', 'minp', 'maxs', 'maxp', 'unpck', 'pxor', 'por', # sse2
  439. 'shufps', 'shufpd',
  440. # arithmetic operations should not produce GC pointers
  441. 'inc', 'dec', 'not', 'neg', 'or', 'and', 'sbb', 'adc',
  442. 'shl', 'shr', 'sal', 'sar', 'rol', 'ror', 'mul', 'imul', 'div', 'idiv',
  443. 'bswap', 'bt', 'rdtsc', 'rounds',
  444. 'pabs', 'pack', 'padd', 'palign', 'pand', 'pavg', 'pcmp', 'pextr',
  445. 'phadd', 'phsub', 'pinsr', 'pmadd', 'pmax', 'pmin', 'pmovmsk',
  446. 'pmul', 'por', 'psadb', 'pshuf', 'psign', 'psll', 'psra', 'psrl',
  447. 'psub', 'punpck', 'pxor',
  448. # all vectors don't produce pointers
  449. 'v',
  450. # sign-extending moves should not produce GC pointers
  451. 'cbtw', 'cwtl', 'cwtd', 'cltd', 'cltq', 'cqto',
  452. # zero-extending moves should not produce GC pointers
  453. 'movz',
  454. # locked operations should not move GC pointers, at least so far
  455. 'lock', 'pause',
  456. ])
  457. # a partial list is hopefully good enough for now; it's all to support
  458. # only one corner case, tested in elf64/track_zero.s
  459. OPS_WITH_PREFIXES_CHANGING_FLAGS = dict.fromkeys([
  460. 'cmp', 'test', 'lahf', 'cld', 'std', 'rep',
  461. 'ucomi', 'comi',
  462. 'add', 'sub', 'xor',
  463. 'inc', 'dec', 'not', 'neg', 'or', 'and', 'sbb', 'adc',
  464. 'shl', 'shr', 'sal', 'sar', 'rol', 'ror', 'mul', 'imul', 'div', 'idiv',
  465. 'bt', 'call', 'int',
  466. 'jmp', # not really changing flags, but we shouldn't assume
  467. # anything about the operations on the following lines
  468. ], True)
  469. visit_movb = visit_nop
  470. visit_movw = visit_nop
  471. visit_addb = visit_nop
  472. visit_addw = visit_nop
  473. visit_subb = visit_nop
  474. visit_subw = visit_nop
  475. visit_xorb = visit_nop
  476. visit_xorw = visit_nop
  477. def _visit_add(self, line, sign=+1):
  478. match = self.r_binaryinsn.match(line)
  479. source = match.group("source")
  480. target = match.group("target")
  481. if target == self.ESP:
  482. count = self.extract_immediate(source)
  483. if count is None:
  484. # strange instruction - I've seen 'subl %eax, %esp'
  485. return InsnCannotFollowEsp()
  486. return InsnStackAdjust(sign * count)
  487. elif self.r_localvar.match(target):
  488. return InsnSetLocal(target, [source, target])
  489. else:
  490. return []
  491. def _visit_sub(self, line):
  492. return self._visit_add(line, sign=-1)
  493. def unary_insn(self, line):
  494. match = self.r_unaryinsn.match(line)
  495. target = match.group(1)
  496. if self.r_localvar.match(target):
  497. return InsnSetLocal(target)
  498. else:
  499. return []
  500. def binary_insn(self, line):
  501. match = self.r_binaryinsn.match(line)
  502. if not match:
  503. raise UnrecognizedOperation(line)
  504. source = match.group("source")
  505. target = match.group("target")
  506. if self.r_localvar.match(target):
  507. return InsnSetLocal(target, [source])
  508. elif target == self.ESP:
  509. raise UnrecognizedOperation(line)
  510. else:
  511. return []
  512. # The various cmov* operations
  513. for name in '''
  514. e ne g ge l le a ae b be p np s ns o no
  515. '''.split():
  516. locals()['visit_cmov' + name] = binary_insn
  517. locals()['visit_cmov' + name + 'l'] = binary_insn
  518. def _visit_and(self, line):
  519. match = self.r_binaryinsn.match(line)
  520. target = match.group("target")
  521. if target == self.ESP:
  522. # only for andl $-16, %esp used to align the stack in main().
  523. # main() should not be seen at all. But on e.g. MSVC we see
  524. # the instruction somewhere else too...
  525. return InsnCannotFollowEsp()
  526. else:
  527. return self.binary_insn(line)
  528. def _visit_lea(self, line):
  529. match = self.r_binaryinsn.match(line)
  530. target = match.group("target")
  531. if target == self.ESP:
  532. # only for leal -12(%ebp), %esp in function epilogues
  533. source = match.group("source")
  534. match = self.r_localvar_ebp.match(source)
  535. if match:
  536. if not self.uses_frame_pointer:
  537. raise UnrecognizedOperation('epilogue without prologue')
  538. ofs_from_ebp = int(match.group(1) or '0')
  539. assert ofs_from_ebp <= 0
  540. framesize = self.WORD - ofs_from_ebp
  541. else:
  542. match = self.r_localvar_esp.match(source)
  543. # leal 12(%esp), %esp
  544. if match:
  545. return InsnStackAdjust(int(match.group(1)))
  546. framesize = None # strange instruction
  547. return InsnEpilogue(framesize)
  548. else:
  549. return self.binary_insn(line)
  550. def insns_for_copy(self, source, target):
  551. source = self.replace_symbols(source)
  552. target = self.replace_symbols(target)
  553. if target == self.ESP:
  554. raise UnrecognizedOperation('%s -> %s' % (source, target))
  555. elif self.r_localvar.match(target):
  556. if self.r_localvar.match(source):
  557. # eg, movl %eax, %ecx: possibly copies a GC root
  558. return [InsnCopyLocal(source, target)]
  559. else:
  560. # eg, movl (%eax), %edi or mov %esp, %edi: load a register
  561. # from "outside". If it contains a pointer to a GC root,
  562. # it will be announced later with the GCROOT macro.
  563. return [InsnSetLocal(target, [source])]
  564. else:
  565. # eg, movl %ebx, (%edx) or mov %ebp, %esp: does not write into
  566. # a general register
  567. return []
  568. def _visit_mov(self, line):
  569. match = self.r_binaryinsn.match(line)
  570. source = match.group("source")
  571. target = match.group("target")
  572. if source == self.ESP and target == self.EBP:
  573. return self._visit_prologue()
  574. elif source == self.EBP and target == self.ESP:
  575. return self._visit_epilogue()
  576. if source == self.ESP and self.funcname.startswith('VALGRIND_'):
  577. return [] # in VALGRIND_XXX functions, there is a dummy-looking
  578. # mov %esp, %eax. Shows up only when compiling with
  579. # gcc -fno-unit-at-a-time.
  580. return self.insns_for_copy(source, target)
  581. def _visit_push(self, line):
  582. match = self.r_unaryinsn.match(line)
  583. source = match.group(1)
  584. return self.insns_for_copy(source, self.TOP_OF_STACK_MINUS_WORD) + \
  585. [InsnStackAdjust(-self.WORD)]
  586. def _visit_pop(self, target):
  587. return [InsnStackAdjust(+self.WORD)] + \
  588. self.insns_for_copy(self.TOP_OF_STACK_MINUS_WORD, target)
  589. def _visit_prologue(self):
  590. # for the prologue of functions that use %ebp as frame pointer
  591. self.uses_frame_pointer = True
  592. self.r_localvar = self.r_localvarfp
  593. return [InsnPrologue(self.WORD)]
  594. def _visit_epilogue(self):
  595. if not self.uses_frame_pointer:
  596. raise UnrecognizedOperation('epilogue without prologue')
  597. return [InsnEpilogue(self.WORD)]
  598. def visit_leave(self, line):
  599. return self._visit_epilogue() + self._visit_pop(self.EBP)
  600. def visit_ret(self, line):
  601. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  602. def visit_jmp(self, line):
  603. tablelabels = []
  604. match = self.r_jmp_switch.match(line)
  605. if match:
  606. # this is a jmp *Label(%index), used for table-based switches.
  607. # Assume that the table is just a list of lines looking like
  608. # .long LABEL or .long 0, ending in a .text or .section .text.hot.
  609. tablelabels.append(match.group(1))
  610. elif self.r_unaryinsn_star.match(line):
  611. # maybe a jmp similar to the above, but stored in a
  612. # registry:
  613. # movl L9341(%eax), %eax
  614. # jmp *%eax
  615. operand = self.r_unaryinsn_star.match(line).group(1)
  616. def walker(insn, locs):
  617. sources = []
  618. for loc in locs:
  619. for s in insn.all_sources_of(loc):
  620. # if the source looks like 8(%eax,%edx,4)
  621. # %eax is the real source, %edx is an offset.
  622. match = self.r_jmp_source.match(s)
  623. if match and not self.r_localvar_esp.match(s):
  624. sources.append(match.group(1))
  625. else:
  626. sources.append(s)
  627. for source in sources:
  628. label_match = re.compile(self.LABEL).match(source)
  629. if label_match:
  630. tablelabels.append(label_match.group(0))
  631. return
  632. yield tuple(sources)
  633. insn = InsnStop()
  634. insn.previous_insns = [self.insns[-1]]
  635. self.walk_instructions_backwards(walker, insn, (operand,))
  636. # Remove probable tail-calls
  637. tablelabels = [label for label in tablelabels
  638. if label in self.labels]
  639. assert len(tablelabels) <= 1
  640. if tablelabels:
  641. tablelin = self.labels[tablelabels[0]].lineno + 1
  642. while not self.r_jmptable_end.match(self.lines[tablelin]):
  643. # skip empty lines
  644. if (not self.lines[tablelin].strip()
  645. or self.lines[tablelin].startswith(';')):
  646. tablelin += 1
  647. continue
  648. match = self.r_jmptable_item.match(self.lines[tablelin])
  649. if not match:
  650. raise NoPatternMatch(repr(self.lines[tablelin]))
  651. label = match.group(1)
  652. if label != '0':
  653. self.register_jump_to(label)
  654. tablelin += 1
  655. return InsnStop("jump table")
  656. if self.r_unaryinsn_star.match(line):
  657. # that looks like an indirect tail-call.
  658. # tail-calls are equivalent to RET for us
  659. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  660. try:
  661. self.conditional_jump(line)
  662. except KeyError:
  663. # label not found: check if it's a tail-call turned into a jump
  664. match = self.r_unaryinsn.match(line)
  665. target = match.group(1)
  666. assert not target.startswith('.')
  667. # tail-calls are equivalent to RET for us
  668. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  669. return InsnStop("jump")
  670. def register_jump_to(self, label, lastinsn=None):
  671. if lastinsn is None:
  672. lastinsn = self.insns[-1]
  673. if not isinstance(lastinsn, InsnStop):
  674. self.labels[label].previous_insns.append(lastinsn)
  675. def conditional_jump(self, line, je=False, jne=False):
  676. match = self.r_jump.match(line)
  677. if not match:
  678. match = self.r_jump_rel_label.match(line)
  679. if not match:
  680. raise UnrecognizedOperation(line)
  681. # j* NNNf
  682. label = match.group(1)
  683. label += ":"
  684. i = self.currentlineno + 1
  685. while True:
  686. if self.lines[i].startswith(label):
  687. label = "rel %d" % i
  688. break
  689. i += 1
  690. else:
  691. label = match.group(1)
  692. prefix = []
  693. lastinsn = None
  694. postfix = []
  695. if self.tested_for_zero is not None:
  696. if je:
  697. # generate pseudo-code...
  698. prefix = [InsnCopyLocal(self.tested_for_zero, '%tmp'),
  699. InsnSetLocal(self.tested_for_zero)]
  700. postfix = [InsnCopyLocal('%tmp', self.tested_for_zero)]
  701. lastinsn = prefix[-1]
  702. elif jne:
  703. postfix = [InsnSetLocal(self.tested_for_zero)]
  704. self.register_jump_to(label, lastinsn)
  705. return prefix + [InsnCondJump(label)] + postfix
  706. visit_jmpl = visit_jmp
  707. visit_jg = conditional_jump
  708. visit_jge = conditional_jump
  709. visit_jl = conditional_jump
  710. visit_jle = conditional_jump
  711. visit_ja = conditional_jump
  712. visit_jae = conditional_jump
  713. visit_jb = conditional_jump
  714. visit_jbe = conditional_jump
  715. visit_jp = conditional_jump
  716. visit_jnp = conditional_jump
  717. visit_js = conditional_jump
  718. visit_jns = conditional_jump
  719. visit_jo = conditional_jump
  720. visit_jno = conditional_jump
  721. visit_jc = conditional_jump
  722. visit_jnc = conditional_jump
  723. def visit_je(self, line):
  724. return self.conditional_jump(line, je=True)
  725. def visit_jne(self, line):
  726. return self.conditional_jump(line, jne=True)
  727. def _visit_test(self, line):
  728. match = self.r_binaryinsn.match(line)
  729. source = match.group("source")
  730. target = match.group("target")
  731. if source == target:
  732. self.tested_for_zero = source
  733. return []
  734. def _visit_xchg(self, line):
  735. # only support the format used in VALGRIND_DISCARD_TRANSLATIONS
  736. # which is to use a marker no-op "xchgl %ebx, %ebx"
  737. match = self.r_binaryinsn.match(line)
  738. source = match.group("source")
  739. target = match.group("target")
  740. if source == target:
  741. return []
  742. raise UnrecognizedOperation(line)
  743. def visit_call(self, line):
  744. match = self.r_unaryinsn.match(line)
  745. if match is None:
  746. assert self.r_unaryinsn_star.match(line) # indirect call
  747. return [InsnCall('<indirect>', self.currentlineno),
  748. InsnSetLocal(self.EAX)] # the result is there
  749. target = match.group(1)
  750. if self.format in ('msvc',):
  751. # On win32, the address of a foreign function must be
  752. # computed, the optimizer may store it in a register. We
  753. # could ignore this, except when the function need special
  754. # processing (not returning, __stdcall...)
  755. def find_register(target):
  756. reg = []
  757. def walker(insn, locs):
  758. sources = []
  759. for loc in locs:
  760. for s in insn.all_sources_of(loc):
  761. sources.append(s)
  762. for source in sources:
  763. m = re.match("DWORD PTR " + self.LABEL, source)
  764. if m:
  765. reg.append(m.group(1))
  766. if reg:
  767. return
  768. yield tuple(sources)
  769. insn = InsnStop()
  770. insn.previous_insns = [self.insns[-1]]
  771. self.walk_instructions_backwards(walker, insn, (target,))
  772. return reg
  773. if match and self.r_localvarfp.match(target):
  774. sources = find_register(target)
  775. if sources:
  776. target, = sources
  777. if target.endswith('@PLT'):
  778. # In -fPIC mode, all functions calls have this suffix
  779. target = target[:-4]
  780. if target in self.FUNCTIONS_NOT_RETURNING:
  781. return [InsnStop(target)]
  782. if self.format == 'mingw32' and target == '__alloca':
  783. # in functions with large stack requirements, windows
  784. # needs a call to _alloca(), to turn reserved pages
  785. # into committed memory.
  786. # With mingw32 gcc at least, %esp is not used before
  787. # this call. So we don't bother to compute the exact
  788. # stack effect.
  789. return [InsnCannotFollowEsp()]
  790. if target in self.labels:
  791. lineoffset = self.labels[target].lineno - self.currentlineno
  792. if lineoffset >= 0:
  793. assert lineoffset in (1,2)
  794. return [InsnStackAdjust(-4)]
  795. insns = [InsnCall(target, self.currentlineno),
  796. InsnSetLocal(self.EAX)] # the result is there
  797. if self.format in ('mingw32', 'msvc'):
  798. # handle __stdcall calling convention:
  799. # Stack cleanup is performed by the called function,
  800. # Function name is decorated with "@N" where N is the stack size
  801. if '@' in target and not target.startswith('@'):
  802. insns.append(InsnStackAdjust(int(target.rsplit('@', 1)[1])))
  803. # Some (intrinsic?) functions use the "fastcall" calling convention
  804. # XXX without any declaration, how can we guess the stack effect?
  805. if target in ['__alldiv', '__allrem', '__allmul', '__alldvrm',
  806. '__aulldiv', '__aullrem', '__aullmul', '__aulldvrm']:
  807. insns.append(InsnStackAdjust(16))
  808. return insns
  809. # __________ debugging output __________
  810. @classmethod
  811. def format_location(cls, loc):
  812. # A 'location' is a single number describing where a value is stored
  813. # across a call. It can be in one of the CALLEE_SAVE_REGISTERS, or
  814. # in the stack frame at an address relative to either %esp or %ebp.
  815. # The last two bits of the location number are used to tell the cases
  816. # apart; see format_location().
  817. assert loc >= 0
  818. kind = loc & LOC_MASK
  819. if kind == LOC_REG:
  820. if loc == LOC_NOWHERE:
  821. return '?'
  822. reg = (loc >> 2) - 1
  823. return '%' + cls.CALLEE_SAVE_REGISTERS[reg].replace("%", "")
  824. else:
  825. offset = loc & ~ LOC_MASK
  826. if cls.WORD == 8:
  827. offset <<= 1
  828. if kind == LOC_EBP_PLUS:
  829. result = '(%' + cls.EBP.replace("%", "") + ')'
  830. elif kind == LOC_EBP_MINUS:
  831. result = '(%' + cls.EBP.replace("%", "") + ')'
  832. offset = -offset
  833. elif kind == LOC_ESP_PLUS:
  834. result = '(%' + cls.ESP.replace("%", "") + ')'
  835. else:
  836. assert 0, kind
  837. if offset != 0:
  838. result = str(offset) + result
  839. return result
  840. @classmethod
  841. def format_callshape(cls, shape):
  842. # A 'call shape' is a tuple of locations in the sense of
  843. # format_location(). They describe where in a function frame
  844. # interesting values are stored, when this function executes a 'call'
  845. # instruction.
  846. #
  847. # shape[0] is the location that stores the fn's own return
  848. # address (not the return address for the currently
  849. # executing 'call')
  850. #
  851. # shape[1..N] is where the fn saved its own caller's value of a
  852. # certain callee save register. (where N is the number
  853. # of callee save registers.)
  854. #
  855. # shape[>N] are GC roots: where the fn has put its local GCPTR
  856. # vars
  857. #
  858. num_callee_save_regs = len(cls.CALLEE_SAVE_REGISTERS)
  859. assert isinstance(shape, tuple)
  860. # + 1 for the return address
  861. assert len(shape) >= (num_callee_save_regs + 1)
  862. result = [cls.format_location(loc) for loc in shape]
  863. return '{%s | %s | %s}' % (result[0],
  864. ', '.join(result[1:(num_callee_save_regs+1)]),
  865. ', '.join(result[(num_callee_save_regs+1):]))
  866. class FunctionGcRootTracker32(FunctionGcRootTracker):
  867. WORD = 4
  868. visit_mov = FunctionGcRootTracker._visit_mov
  869. visit_movl = FunctionGcRootTracker._visit_mov
  870. visit_pushl = FunctionGcRootTracker._visit_push
  871. visit_leal = FunctionGcRootTracker._visit_lea
  872. visit_addl = FunctionGcRootTracker._visit_add
  873. visit_subl = FunctionGcRootTracker._visit_sub
  874. visit_andl = FunctionGcRootTracker._visit_and
  875. visit_and = FunctionGcRootTracker._visit_and
  876. visit_xchgl = FunctionGcRootTracker._visit_xchg
  877. visit_testl = FunctionGcRootTracker._visit_test
  878. # used in "xor reg, reg" to create a NULL GC ptr
  879. visit_xorl = FunctionGcRootTracker.binary_insn
  880. visit_orl = FunctionGcRootTracker.binary_insn # unsure about this one
  881. # occasionally used on 32-bits to move floats around
  882. visit_movq = FunctionGcRootTracker.visit_nop
  883. def visit_pushw(self, line):
  884. return [InsnStackAdjust(-2)] # rare but not impossible
  885. def visit_popl(self, line):
  886. match = self.r_unaryinsn.match(line)
  887. target = match.group(1)
  888. return self._visit_pop(target)
  889. class FunctionGcRootTracker64(FunctionGcRootTracker):
  890. WORD = 8
  891. # Regex ignores destination
  892. r_save_xmm_register = re.compile(r"\tmovaps\s+%xmm(\d+)")
  893. def _maybe_32bit_dest(func):
  894. def wrapper(self, line):
  895. # Using a 32-bit reg as a destination in 64-bit mode zero-extends
  896. # to 64-bits, so sometimes gcc uses a 32-bit operation to copy a
  897. # statically known pointer to a register
  898. # %eax -> %rax
  899. new_line = re.sub(r"%e(ax|bx|cx|dx|di|si|bp)$", r"%r\1", line)
  900. # %r10d -> %r10
  901. new_line = re.sub(r"%r(\d+)d$", r"%r\1", new_line)
  902. return func(self, new_line)
  903. return wrapper
  904. visit_addl = FunctionGcRootTracker.visit_nop
  905. visit_subl = FunctionGcRootTracker.visit_nop
  906. visit_leal = FunctionGcRootTracker.visit_nop
  907. visit_cltq = FunctionGcRootTracker.visit_nop
  908. visit_movq = FunctionGcRootTracker._visit_mov
  909. # just a special assembler mnemonic for mov
  910. visit_movabsq = FunctionGcRootTracker._visit_mov
  911. visit_mov = _maybe_32bit_dest(FunctionGcRootTracker._visit_mov)
  912. visit_movl = visit_mov
  913. visit_xorl = _maybe_32bit_dest(FunctionGcRootTracker.binary_insn)
  914. visit_pushq = FunctionGcRootTracker._visit_push
  915. visit_addq = FunctionGcRootTracker._visit_add
  916. visit_subq = FunctionGcRootTracker._visit_sub
  917. visit_leaq = FunctionGcRootTracker._visit_lea
  918. visit_xorq = FunctionGcRootTracker.binary_insn
  919. visit_xchgq = FunctionGcRootTracker._visit_xchg
  920. visit_testq = FunctionGcRootTracker._visit_test
  921. # FIXME: similar to visit_popl for 32-bit
  922. def visit_popq(self, line):
  923. match = self.r_unaryinsn.match(line)
  924. target = match.group(1)
  925. return self._visit_pop(target)
  926. def visit_jmp(self, line):
  927. # On 64-bit, %al is used when calling varargs functions to specify an
  928. # upper-bound on the number of xmm registers used in the call. gcc
  929. # uses %al to compute an indirect jump that looks like:
  930. #
  931. # jmp *[some register]
  932. # movaps %xmm7, [stack location]
  933. # movaps %xmm6, [stack location]
  934. # movaps %xmm5, [stack location]
  935. # movaps %xmm4, [stack location]
  936. # movaps %xmm3, [stack location]
  937. # movaps %xmm2, [stack location]
  938. # movaps %xmm1, [stack location]
  939. # movaps %xmm0, [stack location]
  940. #
  941. # The jmp is always to somewhere in the block of "movaps"
  942. # instructions, according to how many xmm registers need to be saved
  943. # to the stack. The point of all this is that we can safely ignore
  944. # jmp instructions of that form.
  945. if (self.currentlineno + 8) < len(self.lines) and self.r_unaryinsn_star.match(line):
  946. matches = [self.r_save_xmm_register.match(self.lines[self.currentlineno + 1 + i]) for i in range(8)]
  947. if all(m and int(m.group(1)) == (7 - i) for i, m in enumerate(matches)):
  948. return []
  949. return FunctionGcRootTracker.visit_jmp(self, line)
  950. class ElfFunctionGcRootTracker32(FunctionGcRootTracker32):
  951. format = 'elf'
  952. function_names_prefix = ''
  953. ESP = '%esp'
  954. EBP = '%ebp'
  955. EAX = '%eax'
  956. CALLEE_SAVE_REGISTERS = ['%ebx', '%esi', '%edi', '%ebp']
  957. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  958. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  959. OPERAND = r'(?:[-\w$%+.:@"]+(?:[(][\w%,]+[)])?|[(][\w%,]+[)])'
  960. LABEL = r'([a-zA-Z_$.][a-zA-Z0-9_$@.]*)'
  961. OFFSET_LABELS = 2**30
  962. TOP_OF_STACK_MINUS_WORD = '-4(%esp)'
  963. r_functionstart = re.compile(r"\t.type\s+"+LABEL+",\s*[@]function\s*$")
  964. r_functionend = re.compile(r"\t.size\s+"+LABEL+",\s*[.]-"+LABEL+"\s*$")
  965. LOCALVAR = r"%eax|%edx|%ecx|%ebx|%esi|%edi|%ebp|-?\d*[(]%esp[)]"
  966. LOCALVARFP = LOCALVAR + r"|-?\d*[(]%ebp[)]"
  967. r_localvarnofp = re.compile(LOCALVAR)
  968. r_localvarfp = re.compile(LOCALVARFP)
  969. r_localvar_esp = re.compile(r"(-?\d*)[(]%esp[)]")
  970. r_localvar_ebp = re.compile(r"(-?\d*)[(]%ebp[)]")
  971. r_rel_label = re.compile(r"(\d+):\s*$")
  972. r_jump_rel_label = re.compile(r"\tj\w+\s+"+"(\d+)f"+"\s*$")
  973. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+[*]("+OPERAND+")\s*$")
  974. r_jmptable_item = re.compile(r"\t.long\t"+LABEL+"(-\"[A-Za-z0-9$]+\")?\s*$")
  975. r_jmptable_end = re.compile(r"\t.text|\t.section\s+.text|\t\.align|"+LABEL)
  976. r_gcroot_marker = re.compile(r"\t/[*] GCROOT ("+LOCALVARFP+") [*]/")
  977. r_gcnocollect_marker = re.compile(r"\t/[*] GC_NOCOLLECT ("+OPERAND+") [*]/")
  978. r_bottom_marker = re.compile(r"\t/[*] GC_STACK_BOTTOM [*]/")
  979. FUNCTIONS_NOT_RETURNING = {
  980. '_exit': None,
  981. '__assert_fail': None,
  982. '___assert_rtn': None,
  983. 'L___assert_rtn$stub': None,
  984. 'L___eprintf$stub': None,
  985. }
  986. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  987. FUNCTIONS_NOT_RETURNING[_name] = None
  988. def __init__(self, lines, filetag=0):
  989. match = self.r_functionstart.match(lines[0])
  990. funcname = match.group(1)
  991. match = self.r_functionend.match(lines[-1])
  992. assert funcname == match.group(1)
  993. assert funcname == match.group(2)
  994. super(ElfFunctionGcRootTracker32, self).__init__(
  995. funcname, lines, filetag)
  996. def extract_immediate(self, value):
  997. if not value.startswith('$'):
  998. return None
  999. return int(value[1:])
  1000. ElfFunctionGcRootTracker32.init_regexp()
  1001. class ElfFunctionGcRootTracker64(FunctionGcRootTracker64):
  1002. format = 'elf64'
  1003. function_names_prefix = ''
  1004. ESP = '%rsp'
  1005. EBP = '%rbp'
  1006. EAX = '%rax'
  1007. CALLEE_SAVE_REGISTERS = ['%rbx', '%r12', '%r13', '%r14', '%r15', '%rbp']
  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 = '-8(%rsp)'
  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"%rax|%rbx|%rcx|%rdx|%rdi|%rsi|%rbp|%r8|%r9|%r10|%r11|%r12|%r13|%r14|%r15|-?\d*[(]%rsp[)]"
  1017. LOCALVARFP = LOCALVAR + r"|-?\d*[(]%rbp[)]"
  1018. r_localvarnofp = re.compile(LOCALVAR)
  1019. r_localvarfp = re.compile(LOCALVARFP)
  1020. r_localvar_esp = re.compile(r"(-?\d*)[(]%rsp[)]")
  1021. r_localvar_ebp = re.compile(r"(-?\d*)[(]%rbp[)]")
  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.(?:quad|long)\t"+LABEL+"(-\"[A-Za-z0-9$]+\"|-"+LABEL+")?\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. }
  1037. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1038. FUNCTIONS_NOT_RETURNING[_name] = None
  1039. def __init__(self, lines, filetag=0):
  1040. match = self.r_functionstart.match(lines[0])
  1041. funcname = match.group(1)
  1042. match = self.r_functionend.match(lines[-1])
  1043. assert funcname == match.group(1)
  1044. assert funcname == match.group(2)
  1045. super(ElfFunctionGcRootTracker64, self).__init__(
  1046. funcname, lines, filetag)
  1047. def extract_immediate(self, value):
  1048. if not value.startswith('$'):
  1049. return None
  1050. return int(value[1:])
  1051. ElfFunctionGcRootTracker64.init_regexp()
  1052. class DarwinFunctionGcRootTracker32(ElfFunctionGcRootTracker32):
  1053. format = 'darwin'
  1054. function_names_prefix = '_'
  1055. r_functionstart = re.compile(r"_(\w+):\s*$")
  1056. OFFSET_LABELS = 0
  1057. def __init__(self, lines, filetag=0):
  1058. match = self.r_functionstart.match(lines[0])
  1059. funcname = '_' + match.group(1)
  1060. FunctionGcRootTracker32.__init__(self, funcname, lines, filetag)
  1061. class DarwinFunctionGcRootTracker64(ElfFunctionGcRootTracker64):
  1062. format = 'darwin64'
  1063. function_names_prefix = '_'
  1064. LABEL = ElfFunctionGcRootTracker64.LABEL
  1065. r_jmptable_item = re.compile(r"\t.(?:long|quad)\t"+LABEL+"(-\"?[A-Za-z0-9$]+\"?)?\s*$")
  1066. r_functionstart = re.compile(r"_(\w+):\s*$")
  1067. OFFSET_LABELS = 0
  1068. def __init__(self, lines, filetag=0):
  1069. match = self.r_functionstart.match(lines[0])
  1070. funcname = '_' + match.group(1)
  1071. FunctionGcRootTracker64.__init__(self, funcname, lines, filetag)
  1072. class Mingw32FunctionGcRootTracker(DarwinFunctionGcRootTracker32):
  1073. format = 'mingw32'
  1074. function_names_prefix = '_'
  1075. FUNCTIONS_NOT_RETURNING = {
  1076. '_exit': None,
  1077. '__assert': None,
  1078. }
  1079. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1080. FUNCTIONS_NOT_RETURNING['_' + _name] = None
  1081. class MsvcFunctionGcRootTracker(FunctionGcRootTracker32):
  1082. format = 'msvc'
  1083. function_names_prefix = '_'
  1084. ESP = 'esp'
  1085. EBP = 'ebp'
  1086. EAX = 'eax'
  1087. CALLEE_SAVE_REGISTERS = ['ebx', 'esi', 'edi', 'ebp']
  1088. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  1089. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  1090. TOP_OF_STACK_MINUS_WORD = 'DWORD PTR [esp-4]'
  1091. OPERAND = r'(?:(:?WORD|DWORD|BYTE) PTR |OFFSET )?[_\w?:@$]*(?:[-+0-9]+)?(:?\[[-+*\w0-9]+\])?'
  1092. LABEL = r'([a-zA-Z_$@.][a-zA-Z0-9_$@.]*)'
  1093. OFFSET_LABELS = 0
  1094. r_segmentstart = re.compile(r"[_A-Z]+\tSEGMENT$")
  1095. r_segmentend = re.compile(r"[_A-Z]+\tENDS$")
  1096. r_functionstart = re.compile(r"; Function compile flags: ")
  1097. r_codestart = re.compile(LABEL+r"\s+PROC\s*(:?;.+)?\n$")
  1098. r_functionend = re.compile(LABEL+r"\s+ENDP\s*$")
  1099. r_symboldefine = re.compile(r"([_A-Za-z0-9$]+) = ([-0-9]+)\s*;.+\n")
  1100. LOCALVAR = r"eax|edx|ecx|ebx|esi|edi|ebp|DWORD PTR [-+]?\d*\[esp[-+]?\d*\]"
  1101. LOCALVARFP = LOCALVAR + r"|DWORD PTR -?\d*\[ebp\]"
  1102. r_localvarnofp = re.compile(LOCALVAR)
  1103. r_localvarfp = re.compile(LOCALVARFP)
  1104. r_localvar_esp = re.compile(r"DWORD PTR ([-+]?\d+)?\[esp([-+]?\d+)?\]")
  1105. r_localvar_ebp = re.compile(r"DWORD PTR ([-+]?\d+)?\[ebp([-+]?\d+)?\]")
  1106. r_rel_label = re.compile(r"$1") # never matches
  1107. r_jump_rel_label = re.compile(r"$1") # never matches
  1108. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+DWORD PTR ("+OPERAND+")\s*$")
  1109. r_jmptable_item = re.compile(r"\tDD\t"+LABEL+"(-\"[A-Za-z0-9$]+\")?\s*$")
  1110. r_jmptable_end = re.compile(r"[^\t\n;]")
  1111. r_gcroot_marker = re.compile(r"$1") # never matches
  1112. r_gcroot_marker_var = re.compile(r"DWORD PTR .+_constant_always_one_.+pypy_asm_gcroot")
  1113. r_gcnocollect_marker = re.compile(r"\spypy_asm_gc_nocollect\(("+OPERAND+")\);")
  1114. r_bottom_marker = re.compile(r"; .+\spypy_asm_stack_bottom\(\);")
  1115. FUNCTIONS_NOT_RETURNING = {
  1116. '__exit': None,
  1117. '__assert': None,
  1118. '__wassert': None,
  1119. '__imp__abort': None,
  1120. '__imp___wassert': None,
  1121. 'DWORD PTR __imp__abort': None,
  1122. 'DWORD PTR __imp___wassert': None,
  1123. }
  1124. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1125. FUNCTIONS_NOT_RETURNING['_' + _name] = None
  1126. @classmethod
  1127. def init_regexp(cls):
  1128. super(MsvcFunctionGcRootTracker, cls).init_regexp()
  1129. cls.r_binaryinsn = re.compile(r"\t[a-z]\w*\s+(?P<target>"+cls.OPERAND+r"),\s*(?P<source>"+cls.OPERAND+r")\s*(?:;.+)?$")
  1130. cls.r_jump = re.compile(r"\tj\w+\s+(?:SHORT |DWORD PTR )?"+cls.LABEL+"\s*$")
  1131. def __init__(self, lines, filetag=0):
  1132. self.defines = {}
  1133. for i, line in enumerate(lines):
  1134. if self.r_symboldefine.match(line):
  1135. match = self.r_symboldefine.match(line)
  1136. name = match.group(1)
  1137. value = int(match.group(2))
  1138. self.defines[name] = value
  1139. continue
  1140. match = self.r_codestart.match(line)
  1141. if match:
  1142. self.skip = i
  1143. break
  1144. funcname = match.group(1)
  1145. super(MsvcFunctionGcRootTracker, self).__init__(
  1146. funcname, lines, filetag)
  1147. def replace_symbols(self, operand):
  1148. for name, value in self.defines.items():
  1149. operand = operand.replace(name, str(value))
  1150. return operand
  1151. for name in '''
  1152. push pop mov lea
  1153. xor sub add
  1154. '''.split():
  1155. locals()['visit_' + name] = getattr(FunctionGcRootTracker32,
  1156. 'visit_' + name + 'l')
  1157. visit_int = FunctionGcRootTracker32.visit_nop
  1158. # probably not GC pointers
  1159. visit_cdq = FunctionGcRootTracker32.visit_nop
  1160. def visit_npad(self, line):
  1161. # MASM has a nasty bug: it implements "npad 5" with "add eax, 0"
  1162. # which is a not no-op because it clears flags.
  1163. # I've seen this instruction appear between "test" and "jne"...
  1164. # see http://www.masm32.com/board/index.php?topic=13122
  1165. match = self.r_unaryinsn.match(line)
  1166. arg = match.group(1)
  1167. if arg == "5":
  1168. # replace with "npad 3; npad 2"
  1169. self.lines[self.currentlineno] = "\tnpad\t3\n" "\tnpad\t2\n"
  1170. return []
  1171. def extract_immediate(self, value):
  1172. try:
  1173. return int(value)
  1174. except ValueError:
  1175. return None
  1176. def _visit_gcroot_marker(self, line=None):
  1177. # two possible patterns:
  1178. # 1. mov reg, DWORD PTR _always_one_
  1179. # imul target, reg
  1180. # 2. mov reg, DWORD PTR _always_one_
  1181. # imul reg, target
  1182. assert self.lines[self.currentlineno].startswith("\tmov\t")
  1183. mov = self.r_binaryinsn.match(self.lines[self.currentlineno])
  1184. assert re.match("DWORD PTR .+_always_one_", mov.group("source"))
  1185. reg = mov.group("target")
  1186. self.lines[self.currentlineno] = ";" + self.lines[self.currentlineno]
  1187. # the 'imul' must appear in the same block; the 'reg' must not
  1188. # appear in the instructions between
  1189. imul = None
  1190. lineno = self.currentlineno + 1
  1191. stop = False
  1192. while not stop:
  1193. line = self.lines[lineno]
  1194. if line == '\n':
  1195. stop = True
  1196. elif line.startswith("\tjmp\t"):
  1197. stop = True
  1198. elif self.r_gcroot_marker_var.search(line):
  1199. stop = True
  1200. elif (line.startswith("\tmov\t%s," % (reg,)) or
  1201. line.startswith("\tmovsx\t%s," % (reg,)) or
  1202. line.startswith("\tmovzx\t%s," % (reg,))):
  1203. # mov reg, <arg>
  1204. stop = True
  1205. elif line.startswith("\txor\t%s, %s" % (reg, reg)):
  1206. # xor reg, reg
  1207. stop = True
  1208. elif line.startswith("\timul\t"):
  1209. imul = self.r_binaryinsn.match(line)
  1210. imul_arg1 = imul.group("target")
  1211. imul_arg2 = imul.group("source")
  1212. if imul_arg1 == reg or imul_arg2 == reg:
  1213. break
  1214. # the register may not appear in other instructions
  1215. elif reg in line:
  1216. assert False, (line, lineno)
  1217. lineno += 1
  1218. else:
  1219. # No imul, the returned value is not used in this function
  1220. return []
  1221. if reg == imul_arg2:
  1222. self.lines[lineno] = ";" + self.lines[lineno]
  1223. return InsnGCROOT(self.replace_symbols(imul_arg1))
  1224. else:
  1225. assert reg == imul_arg1
  1226. self.lines[lineno] = "\tmov\t%s, %s\n" % (imul_arg1, imul_arg2)
  1227. if imul_arg2.startswith('OFFSET '):
  1228. # ignore static global variables
  1229. pass
  1230. else:
  1231. self.lines[lineno] += "\t; GCROOT\n"
  1232. return []
  1233. def insns_for_copy(self, source, target):
  1234. if self.r_gcroot_marker_var.match(source):
  1235. return self._visit_gcroot_marker()
  1236. if self.lines[self.currentlineno].endswith("\t; GCROOT\n"):
  1237. insns = [InsnGCROOT(self.replace_symbols(source))]
  1238. else:
  1239. insns = []
  1240. return insns + super(MsvcFunctionGcRootTracker, self).insns_for_copy(source, target)
  1241. MsvcFunctionGcRootTracker.init_regexp()
  1242. class AssemblerParser(object):
  1243. def __init__(self, verbose=0, shuffle=False):
  1244. self.verbose = verbose
  1245. self.shuffle = shuffle
  1246. self.gcmaptable = []
  1247. def process(self, iterlines, newfile, filename='?'):
  1248. for in_function, lines in self.find_functions(iterlines):
  1249. if in_function:
  1250. tracker = self.process_function(lines, filename)
  1251. lines = tracker.lines
  1252. self.write_newfile(newfile, lines, filename.split('.')[0])
  1253. if self.verbose == 1:
  1254. sys.stderr.write('\n')
  1255. def write_newfile(self, newfile, lines, grist):
  1256. newfile.writelines(lines)
  1257. def process_function(self, lines, filename):
  1258. tracker = self.FunctionGcRootTracker(
  1259. lines, filetag=getidentifier(filename))
  1260. if self.verbose == 1:
  1261. sys.stderr.write('.')
  1262. elif self.verbose > 1:
  1263. print >> sys.stderr, '[trackgcroot:%s] %s' % (filename,
  1264. tracker.funcname)
  1265. table = tracker.computegcmaptable(self.verbose)
  1266. if self.verbose > 1:
  1267. for label, state in table:
  1268. print >> sys.stderr, label, '\t', tracker.format_callshape(state)
  1269. table = compress_gcmaptable(table)
  1270. if self.shuffle and random.random() < 0.5:
  1271. self.gcmaptable[:0] = table
  1272. else:
  1273. self.gcmaptable.extend(table)
  1274. return tracker
  1275. class ElfAssemblerParser(AssemblerParser):
  1276. format = "elf"
  1277. FunctionGcRootTracker = ElfFunctionGcRootTracker32
  1278. def find_functions(self, iterlines):
  1279. functionlines = []
  1280. in_function = False
  1281. for line in iterlines:
  1282. if self.FunctionGcRootTracker.r_functionstart.match(line):
  1283. assert not in_function, (
  1284. "missed the end of the previous function")
  1285. yield False, functionlines
  1286. in_function = True
  1287. functionlines = []
  1288. functionlines.append(line)
  1289. if self.FunctionGcRootTracker.r_functionend.match(line):
  1290. assert in_function, (
  1291. "missed the start of the current function")
  1292. yield True, functionlines
  1293. in_function = False
  1294. functionlines = []
  1295. assert not in_function, (
  1296. "missed the end of the previous function")
  1297. yield False, functionlines
  1298. class ElfAssemblerParser64(ElfAssemblerParser):
  1299. format = "elf64"
  1300. FunctionGcRootTracker = ElfFunctionGcRootTracker64
  1301. class DarwinAssemblerParser(AssemblerParser):
  1302. format = "darwin"
  1303. FunctionGcRootTracker = DarwinFunctionGcRootTracker32
  1304. r_textstart = re.compile(r"\t.text\s*$")
  1305. # see
  1306. # http://developer.apple.com/documentation/developertools/Reference/Assembler/040-Assembler_Directives/asm_directives.html
  1307. OTHERSECTIONS = ['section', 'zerofill',
  1308. 'const', 'static_const', 'cstring',
  1309. 'literal4', 'literal8', 'literal16',
  1310. 'constructor', 'desctructor',
  1311. 'symbol_stub',
  1312. 'data', 'static_data',
  1313. 'non_lazy_symbol_pointer', 'lazy_symbol_pointer',
  1314. 'dyld', 'mod_init_func', 'mod_term_func',
  1315. 'const_data'
  1316. ]
  1317. r_sectionstart = re.compile(r"\t\.("+'|'.join(OTHERSECTIONS)+").*$")
  1318. sections_doesnt_end_function = {'cstring': True, 'const': True}
  1319. def find_functions(self, iterlines):
  1320. functionlines = []
  1321. in_text = False
  1322. in_function = False
  1323. for n, line in enumerate(iterlines):
  1324. if self.r_textstart.match(line):
  1325. in_text = True
  1326. elif self.r_sectionstart.match(line):
  1327. sectionname = self.r_sectionstart.match(line).group(1)
  1328. if (in_function and
  1329. sectionname not in self.sections_doesnt_end_function):
  1330. yield in_function, functionlines
  1331. functionlines = []
  1332. in_function = False
  1333. in_text = False
  1334. elif in_text and self.FunctionGcRootTracker.r_functionstart.match(line):
  1335. yield in_function, functionlines
  1336. functionlines = []
  1337. in_function = True
  1338. functionlines.append(line)
  1339. if functionlines:
  1340. yield in_function, functionlines
  1341. class DarwinAssemblerParser64(DarwinAssemblerParser):
  1342. format = "darwin64"
  1343. FunctionGcRootTracker = DarwinFunctionGcRootTracker64
  1344. class Mingw32AssemblerParser(DarwinAssemblerParser):
  1345. format = "mingw32"
  1346. r_sectionstart = re.compile(r"^_loc()")
  1347. FunctionGcRootTracker = Mingw32FunctionGcRootTracker
  1348. class MsvcAssemblerParser(AssemblerParser):
  1349. format = "msvc"
  1350. FunctionGcRootTracker = MsvcFunctionGcRootTracker
  1351. def find_functions(self, iterlines):
  1352. functionlines = []
  1353. in_function = False
  1354. in_segment = False
  1355. ignore_public = False
  1356. self.inline_functions = {}
  1357. for line in iterlines:
  1358. if line.startswith('; File '):
  1359. filename = line[:-1].split(' ', 2)[2]
  1360. ignore_public = ('wspiapi.h' in filename.lower())
  1361. if ignore_public:
  1362. # this header define __inline functions, that are
  1363. # still marked as PUBLIC in the generated assembler
  1364. if line.startswith(';\tCOMDAT '):
  1365. funcname = line[:-1].split(' ', 1)[1]
  1366. self.inline_functions[funcname] = True
  1367. elif line.startswith('PUBLIC\t'):
  1368. funcname = line[:-1].split('\t')[1]
  1369. self.inline_functions[funcname] = True
  1370. if self.FunctionGcRootTracker.r_segmentstart.match(line):
  1371. in_segment = True
  1372. elif self.FunctionGcRootTracker.r_functionstart.match(line):
  1373. assert not in_function, (
  1374. "missed the end of the previous function")
  1375. in_function = True
  1376. if in_segment:
  1377. yield False, functionlines
  1378. functionlines = []
  1379. functionlines.append(line)
  1380. if self.FunctionGcRootTracker.r_segmentend.match(line):
  1381. yield False, functionlines
  1382. in_segment = False
  1383. functionlines = []
  1384. elif self.FunctionGcRootTracker.r_functionend.match(line):
  1385. assert in_function, (
  1386. "missed the start of the current function")
  1387. yield True, functionlines
  1388. in_function = False
  1389. functionlines = []
  1390. assert not in_function, (
  1391. "missed the end of the previous function")
  1392. yield False, functionlines
  1393. def write_newfile(self, newfile, lines, grist):
  1394. newlines = []
  1395. for line in lines:
  1396. # truncate long comments
  1397. if line.startswith(";"):
  1398. line = line[:-1][:500] + '\n'
  1399. # Workaround a bug in the .s files generated by msvc
  1400. # compiler: every string or float constant is exported
  1401. # with a name built after its value, and will conflict
  1402. # with other modules.
  1403. if line.startswith("PUBLIC\t"):
  1404. symbol = line[:-1].split()[1]
  1405. if symbol.startswith('__real@'):
  1406. line = '; ' + line
  1407. elif symbol.startswith("__mask@@"):
  1408. line = '; ' + line
  1409. elif symbol.startswith("??_C@"):
  1410. line = '; ' + line
  1411. elif symbol == "__$ArrayPad$":
  1412. line = '; ' + line
  1413. elif symbol in self.inline_functions:
  1414. line = '; ' + line
  1415. # The msvc compiler writes "fucomip ST(1)" when the correct
  1416. # syntax is "fucomip ST, ST(1)"
  1417. if line == "\tfucomip\tST(1)\n":
  1418. line = "\tfucomip\tST, ST(1)\n"
  1419. # Because we insert labels in the code, some "SHORT" jumps
  1420. # are now longer than 127 bytes. We turn them all into
  1421. # "NEAR" jumps. Note that the assembler allocates space
  1422. # for a near jump, but still generates a short jump when
  1423. # it can.
  1424. line = line.replace('\tjmp\tSHORT ', '\tjmp\t')
  1425. line = line.replace('\tjne\tSHORT ', '\tjne\t')
  1426. line = line.replace('\tje\tSHORT ', '\tje\t')
  1427. newlines.append(line)
  1428. if line == "\t.model\tflat\n":
  1429. newlines.append("\tassume fs:nothing\n")
  1430. newfile.writelines(newlines)
  1431. PARSERS = {
  1432. 'elf': ElfAssemblerParser,
  1433. 'elf64': ElfAssemblerParser64,
  1434. 'darwin': DarwinAssemblerParser,
  1435. 'darwin64': DarwinAssemblerParser64,
  1436. 'mingw32': Mingw32AssemblerParser,
  1437. 'msvc': MsvcAssemblerParser,
  1438. }
  1439. class GcRootTracker(object):
  1440. def __init__(self, verbose=0, shuffle=False, format='elf'):
  1441. self.verbose = verbose
  1442. self.shuffle = shuffle # to debug the sorting logic in asmgcroot.py
  1443. self.format = format
  1444. self.gcmaptable = []
  1445. def dump_raw_table(self, output):
  1446. print 'raw table'
  1447. for entry in self.gcmaptable:
  1448. print >> output, entry
  1449. def reload_raw_table(self, input):
  1450. firstline = input.readline()
  1451. assert firstline == 'raw table\n'
  1452. for line in input:
  1453. entry = eval(line)
  1454. assert type(entry) is tuple
  1455. self.gcmaptable.append(entry)
  1456. def dump(self, output):
  1457. def _globalname(name, disp=""):
  1458. return tracker_cls.function_names_prefix + name
  1459. def _variant(**kwargs):
  1460. txt = kwargs[self.format]
  1461. print >> output, "\t%s" % txt
  1462. if self.format in ('elf64', 'darwin64'):
  1463. word_decl = '.quad'
  1464. else:
  1465. word_decl = '.long'
  1466. tracker_cls = PARSERS[self.format].FunctionGcRootTracker
  1467. # The pypy_asm_stackwalk() function
  1468. if self.format == 'msvc':
  1469. print >> output, """\
  1470. /* See description in asmgcroot.py */
  1471. __declspec(naked)
  1472. long pypy_asm_stackwalk(void *callback)
  1473. {
  1474. __asm {
  1475. mov\tedx, DWORD PTR [esp+4]\t; 1st argument, which is the callback
  1476. mov\tecx, DWORD PTR [esp+8]\t; 2nd argument, which is gcrootanchor
  1477. mov\teax, esp\t\t; my frame top address
  1478. push\teax\t\t\t; ASM_FRAMEDATA[6]
  1479. push\tebp\t\t\t; ASM_FRAMEDATA[5]
  1480. push\tedi\t\t\t; ASM_FRAMEDATA[4]
  1481. push\tesi\t\t\t; ASM_FRAMEDATA[3]
  1482. push\tebx\t\t\t; ASM_FRAMEDATA[2]
  1483. ; Add this ASM_FRAMEDATA to the front of the circular linked
  1484. ; list. Let's call it 'self'.
  1485. mov\teax, DWORD PTR [ecx+4]\t\t; next = gcrootanchor->next
  1486. push\teax\t\t\t\t\t\t\t\t\t; self->next = next
  1487. push\tecx ; self->prev = gcrootanchor
  1488. mov\tDWORD PTR [ecx+4], esp\t\t; gcrootanchor->next = self
  1489. mov\tDWORD PTR [eax+0], esp\t\t\t\t\t; next->prev = self
  1490. call\tedx\t\t\t\t\t\t; invoke the callback
  1491. ; Detach this ASM_FRAMEDATA from the circular linked list
  1492. pop\tesi\t\t\t\t\t\t\t; prev = self->prev
  1493. pop\tedi\t\t\t\t\t\t\t; next = self->next
  1494. mov\tDWORD PTR [esi+4], edi\t\t; prev->next = next
  1495. mov\tDWORD PTR [edi+0], esi\t\t; next->prev = prev
  1496. pop\tebx\t\t\t\t; restore from ASM_FRAMEDATA[2]
  1497. pop\tesi\t\t\t\t; restore from ASM_FRAMEDATA[3]
  1498. pop\tedi\t\t\t\t; restore from ASM_FRAMEDATA[4]
  1499. pop\tebp\t\t\t\t; restore from ASM_FRAMEDATA[5]
  1500. pop\tecx\t\t\t\t; ignored ASM_FRAMEDATA[6]
  1501. ; the return value is the one of the 'call' above,
  1502. ; because %eax (and possibly %edx) are unmodified
  1503. ret
  1504. }
  1505. }
  1506. """
  1507. elif self.format in ('elf64', 'darwin64'):
  1508. if self.format == 'elf64': # gentoo patch: hardened systems
  1509. print >> output, "\t.section .note.GNU-stack,\"\",%progbits"
  1510. print >> output, "\t.text"
  1511. print >> output, "\t.globl %s" % _globalname('pypy_asm_stackwalk')
  1512. _variant(elf64='.type pypy_asm_stackwalk, @function',
  1513. darwin64='')
  1514. print >> output, "%s:" % _globalname('pypy_asm_stackwalk')
  1515. s = """\
  1516. /* See description in asmgcroot.py */
  1517. .cfi_startproc
  1518. /* %rdi is the 1st argument, which is the callback */
  1519. /* %rsi is the 2nd argument, which is gcrootanchor */
  1520. movq\t%rsp, %rax\t/* my frame top address */
  1521. pushq\t%rax\t\t/* ASM_FRAMEDATA[8] */
  1522. pushq\t%rbp\t\t/* ASM_FRAMEDATA[7] */
  1523. pushq\t%r15\t\t/* ASM_FRAMEDATA[6] */
  1524. pushq\t%r14\t\t/* ASM_FRAMEDATA[5] */
  1525. pushq\t%r13\t\t/* ASM_FRAMEDATA[4] */
  1526. pushq\t%r12\t\t/* ASM_FRAMEDATA[3] */
  1527. pushq\t%rbx\t\t/* ASM_FRAMEDATA[2] */
  1528. /* Add this ASM_FRAMEDATA to the front of the circular linked */
  1529. /* list. Let's call it 'self'. */
  1530. movq\t8(%rsi), %rax\t/* next = gcrootanchor->next */
  1531. pushq\t%rax\t\t\t\t/* self->next = next */
  1532. pushq\t%rsi\t\t\t/* self->prev = gcrootanchor */
  1533. movq\t%rsp, 8(%rsi)\t/* gcrootanchor->next = self */
  1534. movq\t%rsp, 0(%rax)\t\t\t/* next->prev = self */
  1535. .cfi_def_cfa_offset 80\t/* 9 pushes + the retaddr = 80 bytes */
  1536. /* note: the Mac OS X 16 bytes aligment must be respected. */
  1537. call\t*%rdi\t\t/* invoke the callback */
  1538. /* Detach this ASM_FRAMEDATA from the circular linked list */
  1539. popq\t%rsi\t\t/* prev = self->prev */
  1540. popq\t%rdi\t\t/* next = self->next */
  1541. movq\t%rdi, 8(%rsi)\t/* prev->next = next */
  1542. movq\t%rsi, 0(%rdi)\t/* next->prev = prev */
  1543. popq\t%rbx\t\t/* restore from ASM_FRAMEDATA[2] */
  1544. popq\t%r12\t\t/* restore from ASM_FRAMEDATA[3] */
  1545. popq\t%r13\t\t/* restore from ASM_FRAMEDATA[4] */
  1546. popq\t%r14\t\t/* restore from ASM_FRAMEDATA[5] */
  1547. popq\t%r15\t\t/* restore from ASM_FRAMEDATA[6] */
  1548. popq\t%rbp\t\t/* restore from ASM_FRAMEDATA[7] */
  1549. popq\t%rcx\t\t/* ignored ASM_FRAMEDATA[8] */
  1550. /* the return value is the one of the 'call' above, */
  1551. /* because %rax is unmodified */
  1552. ret
  1553. .cfi_endproc
  1554. """
  1555. if self.format == 'darwin64':
  1556. # obscure. gcc there seems not to support .cfi_...
  1557. # hack it out...
  1558. s = re.sub(r'([.]cfi_[^/\n]+)([/\n])',
  1559. r'/* \1 disabled on darwin */\2', s)
  1560. print >> output, s
  1561. _variant(elf64='.size pypy_asm_stackwalk, .-pypy_asm_stackwalk',
  1562. darwin64='')
  1563. else:
  1564. print >> output, "\t.text"
  1565. print >> output, "\t.globl %s" % _globalname('pypy_asm_stackwalk')
  1566. _variant(elf='.type pypy_asm_stackwalk, @function',
  1567. darwin='',
  1568. mingw32='')
  1569. print >> output, "%s:" % _globalname('pypy_asm_stackwalk')
  1570. print >> output, """\
  1571. /* See description in asmgcroot.py */
  1572. movl\t4(%esp), %edx\t/* 1st argument, which is the callback */
  1573. movl\t8(%esp), %ecx\t/* 2nd argument, which is gcrootanchor */
  1574. movl\t%esp, %eax\t/* my frame top address */
  1575. pushl\t%eax\t\t/* ASM_FRAMEDATA[6] */
  1576. pushl\t%ebp\t\t/* ASM_FRAMEDATA[5] */
  1577. pushl\t%edi\t\t/* ASM_FRAMEDATA[4] */
  1578. pushl\t%esi\t\t/* ASM_FRAMEDATA[3] */
  1579. pushl\t%ebx\t\t/* ASM_FRAMEDATA[2] */
  1580. /* Add this ASM_FRAMEDATA to the front of the circular linked */
  1581. /* list. Let's call it 'self'. */
  1582. movl\t4(%ecx), %eax\t/* next = gcrootanchor->next */
  1583. pushl\t%eax\t\t\t\t/* self->next = next */
  1584. pushl\t%ecx\t\t\t/* self->prev = gcrootanchor */
  1585. movl\t%esp, 4(%ecx)\t/* gcrootanchor->next = self */
  1586. movl\t%esp, 0(%eax)\t\t\t/* next->prev = self */
  1587. /* note: the Mac OS X 16 bytes aligment must be respected. */
  1588. call\t*%edx\t\t/* invoke the callback */
  1589. /* Detach this ASM_FRAMEDATA from the circular linked list */
  1590. popl\t%esi\t\t/* prev = self->prev */
  1591. popl\t%edi\t\t/* next = self->next */
  1592. movl\t%edi, 4(%esi)\t/* prev->next = next */
  1593. movl\t%esi, 0(%edi)\t/* next->prev = prev */
  1594. popl\t%ebx\t\t/* restore from ASM_FRAMEDATA[2] */
  1595. popl\t%esi\t\t/* restore from ASM_FRAMEDATA[3] */
  1596. popl\t%edi\t\t/* restore from ASM_FRAMEDATA[4] */
  1597. popl\t%ebp\t\t/* restore from ASM_FRAMEDATA[5] */
  1598. popl\t%ecx\t\t/* ignored ASM_FRAMEDATA[6] */
  1599. /* the return value is the one of the 'call' above, */
  1600. /* because %eax (and possibly %edx) are unmodified */
  1601. ret
  1602. """
  1603. _variant(elf='.size pypy_asm_stackwalk, .-pypy_asm_stackwalk',
  1604. darwin='',
  1605. mingw32='')
  1606. if self.format == 'msvc':
  1607. for label, state, is_range in self.gcmaptable:
  1608. label = label[1:]
  1609. print >> output, "extern void* %s;" % label
  1610. shapes = {}
  1611. shapelines = []
  1612. shapeofs = 0
  1613. # write the tables
  1614. if self.format == 'msvc':
  1615. print >> output, """\
  1616. static struct { void* addr; long shape; } __gcmap[%d] = {
  1617. """ % (len(self.gcmaptable),)
  1618. for label, state, is_range in self.gcmaptable:
  1619. label = label[1:]
  1620. try:
  1621. n = shapes[state]
  1622. except KeyError:
  1623. n = shapes[state] = shapeofs
  1624. bytes = [str(b) for b in tracker_cls.compress_callshape(state)]
  1625. shapelines.append('\t%s,\t/* %s */\n' % (
  1626. ', '.join(bytes),
  1627. shapeofs))
  1628. shapeofs += len(bytes)
  1629. if is_range:
  1630. n = ~ n
  1631. print >> output, '{ &%s, %d},' % (label, n)
  1632. print >> output, """\
  1633. };
  1634. void* __gcmapstart = __gcmap;
  1635. void* __gcmapend = __gcmap + %d;
  1636. char __gccallshapes[] = {
  1637. """ % (len(self.gcmaptable),)
  1638. output.writelines(shapelines)
  1639. print >> output, """\
  1640. };
  1641. """
  1642. else:
  1643. print >> output, """\
  1644. .data
  1645. .align 4
  1646. .globl __gcmapstart
  1647. __gcmapstart:
  1648. """.replace("__gcmapstart", _globalname("__gcmapstart"))
  1649. for label, state, is_range in self.gcmaptable:
  1650. try:
  1651. n = shapes[state]
  1652. except KeyError:
  1653. n = shapes[state] = shapeofs
  1654. bytes = [str(b) for b in tracker_cls.compress_callshape(state)]
  1655. shapelines.append('\t/*%d*/\t.byte\t%s\n' % (
  1656. shapeofs,
  1657. ', '.join(bytes)))
  1658. shapeofs += len(bytes)
  1659. if is_range:
  1660. n = ~ n
  1661. print >> output, '\t%s\t%s-%d' % (
  1662. word_decl,
  1663. label,
  1664. tracker_cls.OFFSET_LABELS)
  1665. print >> output, '\t%s\t%d' % (word_decl, n)
  1666. print >> output, """\
  1667. .globl __gcmapend
  1668. __gcmapend:
  1669. """.replace("__gcmapend", _globalname("__gcmapend"))
  1670. _variant(elf='.section\t.rodata',
  1671. elf64='.section\t.rodata',
  1672. darwin='.const',
  1673. darwin64='.const',
  1674. mingw32='')
  1675. print >> output, """\
  1676. .globl __gccallshapes
  1677. __gccallshapes:
  1678. """.replace("__gccallshapes", _globalname("__gccallshapes"))
  1679. output.writelines(shapelines)
  1680. print >> output, """\
  1681. #if defined(__linux__) && defined(__ELF__)
  1682. .section .note.GNU-stack,"",%progbits
  1683. #endif
  1684. """
  1685. def process(self, iterlines, newfile, filename='?'):
  1686. parser = PARSERS[format](verbose=self.verbose, shuffle=self.shuffle)
  1687. for in_function, lines in parser.find_functions(iterlines):
  1688. if in_function:
  1689. tracker = parser.process_function(lines, filename)
  1690. lines = tracker.lines
  1691. parser.write_newfile(newfile, lines, filename.split('.')[0])
  1692. if self.verbose == 1:
  1693. sys.stderr.write('\n')
  1694. if self.shuffle and random.random() < 0.5:
  1695. self.gcmaptable[:0] = parser.gcmaptable
  1696. else:
  1697. self.gcmaptable.extend(parser.gcmaptable)
  1698. class UnrecognizedOperation(Exception):
  1699. pass
  1700. class NoPatternMatch(Exception):
  1701. pass
  1702. # __________ table compression __________
  1703. def compress_gcmaptable(table):
  1704. # Compress ranges table[i:j] of entries with the same state
  1705. # into a single entry whose label is the start of the range.
  1706. # The last element in the table is never compressed in this
  1707. # way for debugging reasons, to avoid that a random address
  1708. # in memory gets mapped to the last element in the table
  1709. # just because it's the closest address.
  1710. # To be on the safe side, compress_gcmaptable() should be called
  1711. # after each function processed -- otherwise the result depends on
  1712. # the linker not rearranging the functions in memory, which is
  1713. # fragile (and wrong e.g. with "make profopt").
  1714. i = 0
  1715. limit = len(table) - 1 # only process entries table[:limit]
  1716. while i < len(table):
  1717. label1, state = table[i]
  1718. is_range = False
  1719. j = i + 1
  1720. while j < limit and table[j][1] == state:
  1721. is_range = True
  1722. j += 1
  1723. # now all entries in table[i:j] have the same state
  1724. yield (label1, state, is_range)
  1725. i = j
  1726. def getidentifier(s):
  1727. def mapchar(c):
  1728. if c.isalnum():
  1729. return c
  1730. else:
  1731. return '_'
  1732. if s.endswith('.s'):
  1733. s = s[:-2]
  1734. s = ''.join([mapchar(c) for c in s])
  1735. while s.endswith('__'):
  1736. s = s[:-1]
  1737. return s
  1738. if __name__ == '__main__':
  1739. verbose = 0
  1740. shuffle = False
  1741. output_raw_table = False
  1742. if sys.platform == 'darwin':
  1743. if sys.maxint > 2147483647:
  1744. format = 'darwin64'
  1745. else:
  1746. format = 'darwin'
  1747. elif sys.platform == 'win32':
  1748. format = 'mingw32'
  1749. else:
  1750. if sys.maxint > 2147483647:
  1751. format = 'elf64'
  1752. else:
  1753. format = 'elf'
  1754. while len(sys.argv) > 1:
  1755. if sys.argv[1] == '-v':
  1756. del sys.argv[1]
  1757. verbose = sys.maxint
  1758. elif sys.argv[1] == '-r':
  1759. del sys.argv[1]
  1760. shuffle = True
  1761. elif sys.argv[1] == '-t':
  1762. del sys.argv[1]
  1763. output_raw_table = True
  1764. elif sys.argv[1].startswith('-f'):
  1765. format = sys.argv[1][2:]
  1766. del sys.argv[1]
  1767. elif sys.argv[1].startswith('-'):
  1768. print >> sys.stderr, "unrecognized option:", sys.argv[1]
  1769. sys.exit(1)
  1770. else:
  1771. break
  1772. tracker = GcRootTracker(verbose=verbose, shuffle=shuffle, format=format)
  1773. for fn in sys.argv[1:]:
  1774. f = open(fn, 'r')
  1775. firstline = f.readline()
  1776. f.seek(0)
  1777. assert firstline, "file %r is empty!" % (fn,)
  1778. if firstline == 'raw table\n':
  1779. tracker.reload_raw_table(f)
  1780. f.close()
  1781. else:
  1782. assert fn.endswith('.s'), fn
  1783. lblfn = fn[:-2] + '.lbl.s'
  1784. g = open(lblfn, 'w')
  1785. try:
  1786. tracker.process(f, g, filename=fn)
  1787. except:
  1788. g.close()
  1789. os.unlink(lblfn)
  1790. raise
  1791. g.close()
  1792. f.close()
  1793. if output_raw_table:
  1794. tracker.dump_raw_table(sys.stdout)
  1795. if not output_raw_table:
  1796. tracker.dump(sys.stdout)