PageRenderTime 84ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 1ms

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

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