PageRenderTime 160ms CodeModel.GetById 73ms RepoModel.GetById 0ms app.codeStats 0ms

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

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