PageRenderTime 75ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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

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