PageRenderTime 65ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 1ms

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

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