PageRenderTime 51ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

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

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