PageRenderTime 64ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/buck_golemon/pypy
Python | 2039 lines | 1883 code | 67 blank | 89 comment | 183 complexity | 8660d53123cacbab91a710dfb07b8dbe MD5 | raw file
Possible License(s): Apache-2.0
  1. #! /usr/bin/env python
  2. import re, sys, os, random
  3. sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
  4. from rpython.translator.c.gcc.instruction import Insn, Label, InsnCall, InsnRet
  5. from rpython.translator.c.gcc.instruction import InsnFunctionStart, InsnStop
  6. from rpython.translator.c.gcc.instruction import InsnSetLocal, InsnCopyLocal
  7. from rpython.translator.c.gcc.instruction import InsnPrologue, InsnEpilogue
  8. from rpython.translator.c.gcc.instruction import InsnGCROOT, InsnCondJump
  9. from rpython.translator.c.gcc.instruction import InsnStackAdjust
  10. from rpython.translator.c.gcc.instruction import InsnCannotFollowEsp
  11. from rpython.translator.c.gcc.instruction import LocalVar, somenewvalue
  12. from rpython.translator.c.gcc.instruction import frameloc_esp, frameloc_ebp
  13. from rpython.translator.c.gcc.instruction import LOC_REG, LOC_NOWHERE, LOC_MASK
  14. from rpython.translator.c.gcc.instruction import LOC_EBP_PLUS, LOC_EBP_MINUS
  15. from rpython.translator.c.gcc.instruction import LOC_ESP_PLUS
  16. class FunctionGcRootTracker(object):
  17. skip = 0
  18. COMMENT = "([#;].*)?"
  19. @classmethod
  20. def init_regexp(cls):
  21. cls.r_label = re.compile(cls.LABEL+"[:]\s*$")
  22. cls.r_globl = re.compile(r"\t[.]globl\t"+cls.LABEL+"\s*$")
  23. cls.r_globllabel = re.compile(cls.LABEL+r"=[.][+]%d\s*$"%cls.OFFSET_LABELS)
  24. cls.r_insn = re.compile(r"\t([a-z]\w*)\s")
  25. cls.r_unaryinsn = re.compile(r"\t[a-z]\w*\s+("+cls.OPERAND+")\s*" + cls.COMMENT + "$")
  26. cls.r_binaryinsn = re.compile(r"\t[a-z]\w*\s+(?P<source>"+cls.OPERAND+"),\s*(?P<target>"+cls.OPERAND+")\s*$")
  27. cls.r_jump = re.compile(r"\tj\w+\s+"+cls.LABEL+"\s*" + cls.COMMENT + "$")
  28. cls.r_jmp_switch = re.compile(r"\tjmp\t[*]"+cls.LABEL+"[(]")
  29. cls.r_jmp_source = re.compile(r"\d*[(](%[\w]+)[,)]")
  30. def __init__(self, funcname, lines, filetag=0):
  31. self.funcname = funcname
  32. self.lines = lines
  33. self.uses_frame_pointer = False
  34. self.r_localvar = self.r_localvarnofp
  35. self.filetag = filetag
  36. # a "stack bottom" function is either pypy_main_function() or a
  37. # callback from C code. In both cases they are identified by
  38. # the presence of pypy_asm_stack_bottom().
  39. self.is_stack_bottom = False
  40. def computegcmaptable(self, verbose=0):
  41. if self.funcname in ['main', '_main']:
  42. return [] # don't analyze main(), its prologue may contain
  43. # strange instructions
  44. self.findlabels()
  45. self.parse_instructions()
  46. try:
  47. self.trim_unreachable_instructions()
  48. self.find_noncollecting_calls()
  49. if not self.list_collecting_call_insns():
  50. return []
  51. self.findframesize()
  52. self.fixlocalvars()
  53. self.trackgcroots()
  54. self.extend_calls_with_labels()
  55. finally:
  56. if verbose > 2:
  57. self.dump()
  58. return self.gettable()
  59. def replace_symbols(self, operand):
  60. return operand
  61. def gettable(self):
  62. """Returns a list [(label_after_call, callshape_tuple)]
  63. See format_callshape() for more details about callshape_tuple.
  64. """
  65. table = []
  66. for insn in self.list_collecting_call_insns():
  67. if not hasattr(insn, 'framesize'):
  68. continue # calls that never end up reaching a RET
  69. if self.is_stack_bottom:
  70. retaddr = LOC_NOWHERE # end marker for asmgcroot.py
  71. elif self.uses_frame_pointer:
  72. retaddr = frameloc_ebp(self.WORD, self.WORD)
  73. else:
  74. retaddr = frameloc_esp(insn.framesize, self.WORD)
  75. shape = [retaddr]
  76. # the first gcroots are always the ones corresponding to
  77. # the callee-saved registers
  78. for reg in self.CALLEE_SAVE_REGISTERS:
  79. shape.append(LOC_NOWHERE)
  80. gcroots = []
  81. for localvar, tag in insn.gcroots.items():
  82. if isinstance(localvar, LocalVar):
  83. loc = localvar.getlocation(insn.framesize,
  84. self.uses_frame_pointer,
  85. self.WORD)
  86. elif localvar in self.REG2LOC:
  87. loc = self.REG2LOC[localvar]
  88. else:
  89. assert False, "%s: %s" % (self.funcname,
  90. localvar)
  91. assert isinstance(loc, int)
  92. if tag is None:
  93. gcroots.append(loc)
  94. else:
  95. regindex = self.CALLEE_SAVE_REGISTERS.index(tag)
  96. shape[1 + regindex] = loc
  97. if LOC_NOWHERE in shape and not self.is_stack_bottom:
  98. reg = self.CALLEE_SAVE_REGISTERS[shape.index(LOC_NOWHERE) - 1]
  99. raise AssertionError("cannot track where register %s is saved"
  100. % (reg,))
  101. gcroots.sort()
  102. shape.extend(gcroots)
  103. table.append((insn.global_label, tuple(shape)))
  104. return table
  105. def findlabels(self):
  106. self.labels = {} # {name: Label()}
  107. for lineno, line in enumerate(self.lines):
  108. match = self.r_label.match(line)
  109. label = None
  110. if match:
  111. label = match.group(1)
  112. else:
  113. # labels used by: j* NNNf
  114. match = self.r_rel_label.match(line)
  115. if match:
  116. label = "rel %d" % lineno
  117. if label:
  118. assert label not in self.labels, "duplicate label: %s" % label
  119. self.labels[label] = Label(label, lineno)
  120. def trim_unreachable_instructions(self):
  121. reached = set([self.insns[0]])
  122. prevlen = 0
  123. while len(reached) > prevlen:
  124. prevlen = len(reached)
  125. for insn in self.insns:
  126. if insn not in reached:
  127. for previnsn in insn.previous_insns:
  128. if previnsn in reached:
  129. # this instruction is reachable too
  130. reached.add(insn)
  131. break
  132. # now kill all unreachable instructions
  133. i = 0
  134. while i < len(self.insns):
  135. if self.insns[i] in reached:
  136. i += 1
  137. else:
  138. del self.insns[i]
  139. def find_noncollecting_calls(self):
  140. cannot_collect = {}
  141. for line in self.lines:
  142. match = self.r_gcnocollect_marker.search(line)
  143. if match:
  144. name = match.group(1)
  145. cannot_collect[name] = True
  146. #
  147. self.cannot_collect = dict.fromkeys(
  148. [self.function_names_prefix + name for name in cannot_collect])
  149. def append_instruction(self, insn):
  150. # Add the instruction to the list, and link it to the previous one.
  151. previnsn = self.insns[-1]
  152. self.insns.append(insn)
  153. if (isinstance(insn, (InsnSetLocal, InsnCopyLocal)) and
  154. insn.target == self.tested_for_zero):
  155. self.tested_for_zero = None
  156. try:
  157. lst = insn.previous_insns
  158. except AttributeError:
  159. lst = insn.previous_insns = []
  160. if not isinstance(previnsn, InsnStop):
  161. lst.append(previnsn)
  162. def parse_instructions(self):
  163. self.insns = [InsnFunctionStart(self.CALLEE_SAVE_REGISTERS, self.WORD)]
  164. self.tested_for_zero = None
  165. ignore_insns = False
  166. for lineno, line in enumerate(self.lines):
  167. if lineno < self.skip:
  168. continue
  169. self.currentlineno = lineno
  170. insn = []
  171. 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', 'movhlp', 'movlhp',
  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. '__stack_chk_fail': None,
  989. }
  990. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  991. FUNCTIONS_NOT_RETURNING[_name] = None
  992. def __init__(self, lines, filetag=0):
  993. match = self.r_functionstart.match(lines[0])
  994. funcname = match.group(1)
  995. match = self.r_functionend.match(lines[-1])
  996. assert funcname == match.group(1)
  997. assert funcname == match.group(2)
  998. super(ElfFunctionGcRootTracker32, self).__init__(
  999. funcname, lines, filetag)
  1000. def extract_immediate(self, value):
  1001. if not value.startswith('$'):
  1002. return None
  1003. return int(value[1:])
  1004. ElfFunctionGcRootTracker32.init_regexp()
  1005. class ElfFunctionGcRootTracker64(FunctionGcRootTracker64):
  1006. format = 'elf64'
  1007. function_names_prefix = ''
  1008. ESP = '%rsp'
  1009. EBP = '%rbp'
  1010. EAX = '%rax'
  1011. CALLEE_SAVE_REGISTERS = ['%rbx', '%r12', '%r13', '%r14', '%r15', '%rbp']
  1012. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  1013. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  1014. OPERAND = r'(?:[-\w$%+.:@"]+(?:[(][\w%,]+[)])?|[(][\w%,]+[)])'
  1015. LABEL = r'([a-zA-Z_$.][a-zA-Z0-9_$@.]*)'
  1016. OFFSET_LABELS = 2**30
  1017. TOP_OF_STACK_MINUS_WORD = '-8(%rsp)'
  1018. r_functionstart = re.compile(r"\t.type\s+"+LABEL+",\s*[@]function\s*$")
  1019. r_functionend = re.compile(r"\t.size\s+"+LABEL+",\s*[.]-"+LABEL+"\s*$")
  1020. LOCALVAR = r"%rax|%rbx|%rcx|%rdx|%rdi|%rsi|%rbp|%r8|%r9|%r10|%r11|%r12|%r13|%r14|%r15|-?\d*[(]%rsp[)]"
  1021. LOCALVARFP = LOCALVAR + r"|-?\d*[(]%rbp[)]"
  1022. r_localvarnofp = re.compile(LOCALVAR)
  1023. r_localvarfp = re.compile(LOCALVARFP)
  1024. r_localvar_esp = re.compile(r"(-?\d*)[(]%rsp[)]")
  1025. r_localvar_ebp = re.compile(r"(-?\d*)[(]%rbp[)]")
  1026. r_rel_label = re.compile(r"(\d+):\s*$")
  1027. r_jump_rel_label = re.compile(r"\tj\w+\s+"+"(\d+)f"+"\s*$")
  1028. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+[*]("+OPERAND+")\s*$")
  1029. r_jmptable_item = re.compile(r"\t.(?:quad|long)\t"+LABEL+"(-\"[A-Za-z0-9$]+\"|-"+LABEL+")?\s*$")
  1030. r_jmptable_end = re.compile(r"\t.text|\t.section\s+.text|\t\.align|"+LABEL)
  1031. r_gcroot_marker = re.compile(r"\t/[*] GCROOT ("+LOCALVARFP+") [*]/")
  1032. r_gcnocollect_marker = re.compile(r"\t/[*] GC_NOCOLLECT ("+OPERAND+") [*]/")
  1033. r_bottom_marker = re.compile(r"\t/[*] GC_STACK_BOTTOM [*]/")
  1034. FUNCTIONS_NOT_RETURNING = {
  1035. '_exit': None,
  1036. '__assert_fail': None,
  1037. '___assert_rtn': None,
  1038. 'L___assert_rtn$stub': None,
  1039. 'L___eprintf$stub': None,
  1040. '__stack_chk_fail': None,
  1041. }
  1042. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1043. FUNCTIONS_NOT_RETURNING[_name] = None
  1044. def __init__(self, lines, filetag=0):
  1045. match = self.r_functionstart.match(lines[0])
  1046. funcname = match.group(1)
  1047. match = self.r_functionend.match(lines[-1])
  1048. assert funcname == match.group(1)
  1049. assert funcname == match.group(2)
  1050. super(ElfFunctionGcRootTracker64, self).__init__(
  1051. funcname, lines, filetag)
  1052. def extract_immediate(self, value):
  1053. if not value.startswith('$'):
  1054. return None
  1055. return int(value[1:])
  1056. ElfFunctionGcRootTracker64.init_regexp()
  1057. class DarwinFunctionGcRootTracker32(ElfFunctionGcRootTracker32):
  1058. format = 'darwin'
  1059. function_names_prefix = '_'
  1060. r_functionstart = re.compile(r"_(\w+):\s*$")
  1061. OFFSET_LABELS = 0
  1062. def __init__(self, lines, filetag=0):
  1063. match = self.r_functionstart.match(lines[0])
  1064. funcname = '_' + match.group(1)
  1065. FunctionGcRootTracker32.__init__(self, funcname, lines, filetag)
  1066. class DarwinFunctionGcRootTracker64(ElfFunctionGcRootTracker64):
  1067. format = 'darwin64'
  1068. function_names_prefix = '_'
  1069. LABEL = ElfFunctionGcRootTracker64.LABEL
  1070. r_jmptable_item = re.compile(r"\t.(?:long|quad)\t"+LABEL+"(-\"?[A-Za-z0-9$]+\"?)?\s*$")
  1071. r_functionstart = re.compile(r"_(\w+):\s*$")
  1072. OFFSET_LABELS = 0
  1073. def __init__(self, lines, filetag=0):
  1074. match = self.r_functionstart.match(lines[0])
  1075. funcname = '_' + match.group(1)
  1076. FunctionGcRootTracker64.__init__(self, funcname, lines, filetag)
  1077. class Mingw32FunctionGcRootTracker(DarwinFunctionGcRootTracker32):
  1078. format = 'mingw32'
  1079. function_names_prefix = '_'
  1080. FUNCTIONS_NOT_RETURNING = {
  1081. '_exit': None,
  1082. '__assert': None,
  1083. }
  1084. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1085. FUNCTIONS_NOT_RETURNING['_' + _name] = None
  1086. class MsvcFunctionGcRootTracker(FunctionGcRootTracker32):
  1087. format = 'msvc'
  1088. function_names_prefix = '_'
  1089. ESP = 'esp'
  1090. EBP = 'ebp'
  1091. EAX = 'eax'
  1092. CALLEE_SAVE_REGISTERS = ['ebx', 'esi', 'edi', 'ebp']
  1093. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  1094. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  1095. TOP_OF_STACK_MINUS_WORD = 'DWORD PTR [esp-4]'
  1096. OPERAND = r'(?:(:?WORD|DWORD|BYTE) PTR |OFFSET )?[_\w?:@$]*(?:[-+0-9]+)?(:?\[[-+*\w0-9]+\])?'
  1097. LABEL = r'([a-zA-Z_$@.][a-zA-Z0-9_$@.]*)'
  1098. OFFSET_LABELS = 0
  1099. r_segmentstart = re.compile(r"[_A-Z]+\tSEGMENT$")
  1100. r_segmentend = re.compile(r"[_A-Z]+\tENDS$")
  1101. r_functionstart = re.compile(r"; Function compile flags: ")
  1102. r_codestart = re.compile(LABEL+r"\s+PROC\s*(:?;.+)?\n$")
  1103. r_functionend = re.compile(LABEL+r"\s+ENDP\s*$")
  1104. r_symboldefine = re.compile(r"([_A-Za-z0-9$]+) = ([-0-9]+)\s*;.+\n")
  1105. LOCALVAR = r"eax|edx|ecx|ebx|esi|edi|ebp|DWORD PTR [-+]?\d*\[esp[-+]?\d*\]"
  1106. LOCALVARFP = LOCALVAR + r"|DWORD PTR -?\d*\[ebp\]"
  1107. r_localvarnofp = re.compile(LOCALVAR)
  1108. r_localvarfp = re.compile(LOCALVARFP)
  1109. r_localvar_esp = re.compile(r"DWORD PTR ([-+]?\d+)?\[esp([-+]?\d+)?\]")
  1110. r_localvar_ebp = re.compile(r"DWORD PTR ([-+]?\d+)?\[ebp([-+]?\d+)?\]")
  1111. r_rel_label = re.compile(r"$1") # never matches
  1112. r_jump_rel_label = re.compile(r"$1") # never matches
  1113. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+DWORD PTR ("+OPERAND+")\s*$")
  1114. r_jmptable_item = re.compile(r"\tDD\t"+LABEL+"(-\"[A-Za-z0-9$]+\")?\s*$")
  1115. r_jmptable_end = re.compile(r"[^\t\n;]")
  1116. r_gcroot_marker = re.compile(r"$1") # never matches
  1117. r_gcroot_marker_var = re.compile(r"DWORD PTR .+_constant_always_one_.+pypy_asm_gcroot")
  1118. r_gcnocollect_marker = re.compile(r"\spypy_asm_gc_nocollect\(("+OPERAND+")\);")
  1119. r_bottom_marker = re.compile(r"; .+\spypy_asm_stack_bottom\(\);")
  1120. FUNCTIONS_NOT_RETURNING = {
  1121. '__exit': None,
  1122. '__assert': None,
  1123. '__wassert': None,
  1124. '__imp__abort': None,
  1125. '__imp___wassert': None,
  1126. 'DWORD PTR __imp__abort': None,
  1127. 'DWORD PTR __imp___wassert': None,
  1128. }
  1129. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1130. FUNCTIONS_NOT_RETURNING['_' + _name] = None
  1131. @classmethod
  1132. def init_regexp(cls):
  1133. super(MsvcFunctionGcRootTracker, cls).init_regexp()
  1134. cls.r_binaryinsn = re.compile(r"\t[a-z]\w*\s+(?P<target>"+cls.OPERAND+r"),\s*(?P<source>"+cls.OPERAND+r")\s*(?:;.+)?$")
  1135. cls.r_jump = re.compile(r"\tj\w+\s+(?:SHORT |DWORD PTR )?"+cls.LABEL+"\s*$")
  1136. def __init__(self, lines, filetag=0):
  1137. self.defines = {}
  1138. for i, line in enumerate(lines):
  1139. if self.r_symboldefine.match(line):
  1140. match = self.r_symboldefine.match(line)
  1141. name = match.group(1)
  1142. value = int(match.group(2))
  1143. self.defines[name] = value
  1144. continue
  1145. match = self.r_codestart.match(line)
  1146. if match:
  1147. self.skip = i
  1148. break
  1149. funcname = match.group(1)
  1150. super(MsvcFunctionGcRootTracker, self).__init__(
  1151. funcname, lines, filetag)
  1152. def replace_symbols(self, operand):
  1153. for name, value in self.defines.items():
  1154. operand = operand.replace(name, str(value))
  1155. return operand
  1156. for name in '''
  1157. push pop mov lea
  1158. xor sub add
  1159. '''.split():
  1160. locals()['visit_' + name] = getattr(FunctionGcRootTracker32,
  1161. 'visit_' + name + 'l')
  1162. visit_int = FunctionGcRootTracker32.visit_nop
  1163. # probably not GC pointers
  1164. visit_cdq = FunctionGcRootTracker32.visit_nop
  1165. def visit_npad(self, line):
  1166. # MASM has a nasty bug: it implements "npad 5" with "add eax, 0"
  1167. # which is a not no-op because it clears flags.
  1168. # I've seen this instruction appear between "test" and "jne"...
  1169. # see http://www.masm32.com/board/index.php?topic=13122
  1170. match = self.r_unaryinsn.match(line)
  1171. arg = match.group(1)
  1172. if arg == "5":
  1173. # replace with "npad 3; npad 2"
  1174. self.lines[self.currentlineno] = "\tnpad\t3\n" "\tnpad\t2\n"
  1175. return []
  1176. def extract_immediate(self, value):
  1177. try:
  1178. return int(value)
  1179. except ValueError:
  1180. return None
  1181. def _visit_gcroot_marker(self, line=None):
  1182. # two possible patterns:
  1183. # 1. mov reg, DWORD PTR _always_one_
  1184. # imul target, reg
  1185. # 2. mov reg, DWORD PTR _always_one_
  1186. # imul reg, target
  1187. assert self.lines[self.currentlineno].startswith("\tmov\t")
  1188. mov = self.r_binaryinsn.match(self.lines[self.currentlineno])
  1189. assert re.match("DWORD PTR .+_always_one_", mov.group("source"))
  1190. reg = mov.group("target")
  1191. self.lines[self.currentlineno] = ";" + self.lines[self.currentlineno]
  1192. # the 'imul' must appear in the same block; the 'reg' must not
  1193. # appear in the instructions between
  1194. imul = None
  1195. lineno = self.currentlineno + 1
  1196. stop = False
  1197. while not stop:
  1198. line = self.lines[lineno]
  1199. if line == '\n':
  1200. stop = True
  1201. elif line.startswith("\tjmp\t"):
  1202. stop = True
  1203. elif self.r_gcroot_marker_var.search(line):
  1204. stop = True
  1205. elif (line.startswith("\tmov\t%s," % (reg,)) or
  1206. line.startswith("\tmovsx\t%s," % (reg,)) or
  1207. line.startswith("\tmovzx\t%s," % (reg,))):
  1208. # mov reg, <arg>
  1209. stop = True
  1210. elif line.startswith("\txor\t%s, %s" % (reg, reg)):
  1211. # xor reg, reg
  1212. stop = True
  1213. elif line.startswith("\timul\t"):
  1214. imul = self.r_binaryinsn.match(line)
  1215. imul_arg1 = imul.group("target")
  1216. imul_arg2 = imul.group("source")
  1217. if imul_arg1 == reg or imul_arg2 == reg:
  1218. break
  1219. # the register may not appear in other instructions
  1220. elif reg in line:
  1221. assert False, (line, lineno)
  1222. lineno += 1
  1223. else:
  1224. # No imul, the returned value is not used in this function
  1225. return []
  1226. if reg == imul_arg2:
  1227. self.lines[lineno] = ";" + self.lines[lineno]
  1228. return InsnGCROOT(self.replace_symbols(imul_arg1))
  1229. else:
  1230. assert reg == imul_arg1
  1231. self.lines[lineno] = "\tmov\t%s, %s\n" % (imul_arg1, imul_arg2)
  1232. if imul_arg2.startswith('OFFSET '):
  1233. # ignore static global variables
  1234. pass
  1235. else:
  1236. self.lines[lineno] += "\t; GCROOT\n"
  1237. return []
  1238. def insns_for_copy(self, source, target):
  1239. if self.r_gcroot_marker_var.match(source):
  1240. return self._visit_gcroot_marker()
  1241. if self.lines[self.currentlineno].endswith("\t; GCROOT\n"):
  1242. insns = [InsnGCROOT(self.replace_symbols(source))]
  1243. else:
  1244. insns = []
  1245. return insns + super(MsvcFunctionGcRootTracker, self).insns_for_copy(source, target)
  1246. MsvcFunctionGcRootTracker.init_regexp()
  1247. class AssemblerParser(object):
  1248. def __init__(self, verbose=0, shuffle=False):
  1249. self.verbose = verbose
  1250. self.shuffle = shuffle
  1251. self.gcmaptable = []
  1252. def process(self, iterlines, newfile, filename='?'):
  1253. for in_function, lines in self.find_functions(iterlines):
  1254. if in_function:
  1255. tracker = self.process_function(lines, filename)
  1256. lines = tracker.lines
  1257. self.write_newfile(newfile, lines, filename.split('.')[0])
  1258. if self.verbose == 1:
  1259. sys.stderr.write('\n')
  1260. def write_newfile(self, newfile, lines, grist):
  1261. newfile.writelines(lines)
  1262. def process_function(self, lines, filename):
  1263. tracker = self.FunctionGcRootTracker(
  1264. lines, filetag=getidentifier(filename))
  1265. if self.verbose == 1:
  1266. sys.stderr.write('.')
  1267. elif self.verbose > 1:
  1268. print >> sys.stderr, '[trackgcroot:%s] %s' % (filename,
  1269. tracker.funcname)
  1270. table = tracker.computegcmaptable(self.verbose)
  1271. if self.verbose > 1:
  1272. for label, state in table:
  1273. print >> sys.stderr, label, '\t', tracker.format_callshape(state)
  1274. table = compress_gcmaptable(table)
  1275. if self.shuffle and random.random() < 0.5:
  1276. self.gcmaptable[:0] = table
  1277. else:
  1278. self.gcmaptable.extend(table)
  1279. return tracker
  1280. class ElfAssemblerParser(AssemblerParser):
  1281. format = "elf"
  1282. FunctionGcRootTracker = ElfFunctionGcRootTracker32
  1283. def find_functions(self, iterlines):
  1284. functionlines = []
  1285. in_function = False
  1286. for line in iterlines:
  1287. if self.FunctionGcRootTracker.r_functionstart.match(line):
  1288. assert not in_function, (
  1289. "missed the end of the previous function")
  1290. yield False, functionlines
  1291. in_function = True
  1292. functionlines = []
  1293. functionlines.append(line)
  1294. if self.FunctionGcRootTracker.r_functionend.match(line):
  1295. assert in_function, (
  1296. "missed the start of the current function")
  1297. yield True, functionlines
  1298. in_function = False
  1299. functionlines = []
  1300. assert not in_function, (
  1301. "missed the end of the previous function")
  1302. yield False, functionlines
  1303. class ElfAssemblerParser64(ElfAssemblerParser):
  1304. format = "elf64"
  1305. FunctionGcRootTracker = ElfFunctionGcRootTracker64
  1306. class DarwinAssemblerParser(AssemblerParser):
  1307. format = "darwin"
  1308. FunctionGcRootTracker = DarwinFunctionGcRootTracker32
  1309. r_textstart = re.compile(r"\t.text\s*$")
  1310. # see
  1311. # http://developer.apple.com/documentation/developertools/Reference/Assembler/040-Assembler_Directives/asm_directives.html
  1312. OTHERSECTIONS = ['section', 'zerofill',
  1313. 'const', 'static_const', 'cstring',
  1314. 'literal4', 'literal8', 'literal16',
  1315. 'constructor', 'desctructor',
  1316. 'symbol_stub',
  1317. 'data', 'static_data',
  1318. 'non_lazy_symbol_pointer', 'lazy_symbol_pointer',
  1319. 'dyld', 'mod_init_func', 'mod_term_func',
  1320. 'const_data'
  1321. ]
  1322. r_sectionstart = re.compile(r"\t\.("+'|'.join(OTHERSECTIONS)+").*$")
  1323. sections_doesnt_end_function = {'cstring': True, 'const': True}
  1324. def find_functions(self, iterlines):
  1325. functionlines = []
  1326. in_text = False
  1327. in_function = False
  1328. for n, line in enumerate(iterlines):
  1329. if self.r_textstart.match(line):
  1330. in_text = True
  1331. elif self.r_sectionstart.match(line):
  1332. sectionname = self.r_sectionstart.match(line).group(1)
  1333. if (in_function and
  1334. sectionname not in self.sections_doesnt_end_function):
  1335. yield in_function, functionlines
  1336. functionlines = []
  1337. in_function = False
  1338. in_text = False
  1339. elif in_text and self.FunctionGcRootTracker.r_functionstart.match(line):
  1340. yield in_function, functionlines
  1341. functionlines = []
  1342. in_function = True
  1343. functionlines.append(line)
  1344. if functionlines:
  1345. yield in_function, functionlines
  1346. class DarwinAssemblerParser64(DarwinAssemblerParser):
  1347. format = "darwin64"
  1348. FunctionGcRootTracker = DarwinFunctionGcRootTracker64
  1349. class Mingw32AssemblerParser(DarwinAssemblerParser):
  1350. format = "mingw32"
  1351. r_sectionstart = re.compile(r"^_loc()")
  1352. FunctionGcRootTracker = Mingw32FunctionGcRootTracker
  1353. class MsvcAssemblerParser(AssemblerParser):
  1354. format = "msvc"
  1355. FunctionGcRootTracker = MsvcFunctionGcRootTracker
  1356. def find_functions(self, iterlines):
  1357. functionlines = []
  1358. in_function = False
  1359. in_segment = False
  1360. ignore_public = False
  1361. self.inline_functions = {}
  1362. for line in iterlines:
  1363. if line.startswith('; File '):
  1364. filename = line[:-1].split(' ', 2)[2]
  1365. ignore_public = ('wspiapi.h' in filename.lower())
  1366. if ignore_public:
  1367. # this header define __inline functions, that are
  1368. # still marked as PUBLIC in the generated assembler
  1369. if line.startswith(';\tCOMDAT '):
  1370. funcname = line[:-1].split(' ', 1)[1]
  1371. self.inline_functions[funcname] = True
  1372. elif line.startswith('PUBLIC\t'):
  1373. funcname = line[:-1].split('\t')[1]
  1374. self.inline_functions[funcname] = True
  1375. if self.FunctionGcRootTracker.r_segmentstart.match(line):
  1376. in_segment = True
  1377. elif self.FunctionGcRootTracker.r_functionstart.match(line):
  1378. assert not in_function, (
  1379. "missed the end of the previous function")
  1380. in_function = True
  1381. if in_segment:
  1382. yield False, functionlines
  1383. functionlines = []
  1384. functionlines.append(line)
  1385. if self.FunctionGcRootTracker.r_segmentend.match(line):
  1386. yield False, functionlines
  1387. in_segment = False
  1388. functionlines = []
  1389. elif self.FunctionGcRootTracker.r_functionend.match(line):
  1390. assert in_function, (
  1391. "missed the start of the current function")
  1392. yield True, functionlines
  1393. in_function = False
  1394. functionlines = []
  1395. assert not in_function, (
  1396. "missed the end of the previous function")
  1397. yield False, functionlines
  1398. def write_newfile(self, newfile, lines, grist):
  1399. newlines = []
  1400. for line in lines:
  1401. # truncate long comments
  1402. if line.startswith(";"):
  1403. line = line[:-1][:500] + '\n'
  1404. # Workaround a bug in the .s files generated by msvc
  1405. # compiler: every string or float constant is exported
  1406. # with a name built after its value, and will conflict
  1407. # with other modules.
  1408. if line.startswith("PUBLIC\t"):
  1409. symbol = line[:-1].split()[1]
  1410. if symbol.startswith('__real@'):
  1411. line = '; ' + line
  1412. elif symbol.startswith("__mask@@"):
  1413. line = '; ' + line
  1414. elif symbol.startswith("??_C@"):
  1415. line = '; ' + line
  1416. elif symbol == "__$ArrayPad$":
  1417. line = '; ' + line
  1418. elif symbol in self.inline_functions:
  1419. line = '; ' + line
  1420. # The msvc compiler writes "fucomip ST(1)" when the correct
  1421. # syntax is "fucomip ST, ST(1)"
  1422. if line == "\tfucomip\tST(1)\n":
  1423. line = "\tfucomip\tST, ST(1)\n"
  1424. # Because we insert labels in the code, some "SHORT" jumps
  1425. # are now longer than 127 bytes. We turn them all into
  1426. # "NEAR" jumps. Note that the assembler allocates space
  1427. # for a near jump, but still generates a short jump when
  1428. # it can.
  1429. line = line.replace('\tjmp\tSHORT ', '\tjmp\t')
  1430. line = line.replace('\tjne\tSHORT ', '\tjne\t')
  1431. line = line.replace('\tje\tSHORT ', '\tje\t')
  1432. newlines.append(line)
  1433. if line == "\t.model\tflat\n":
  1434. newlines.append("\tassume fs:nothing\n")
  1435. newfile.writelines(newlines)
  1436. PARSERS = {
  1437. 'elf': ElfAssemblerParser,
  1438. 'elf64': ElfAssemblerParser64,
  1439. 'darwin': DarwinAssemblerParser,
  1440. 'darwin64': DarwinAssemblerParser64,
  1441. 'mingw32': Mingw32AssemblerParser,
  1442. 'msvc': MsvcAssemblerParser,
  1443. }
  1444. class GcRootTracker(object):
  1445. def __init__(self, verbose=0, shuffle=False, format='elf'):
  1446. self.verbose = verbose
  1447. self.shuffle = shuffle # to debug the sorting logic in asmgcroot.py
  1448. self.format = format
  1449. self.gcmaptable = []
  1450. def dump_raw_table(self, output):
  1451. print 'raw table'
  1452. for entry in self.gcmaptable:
  1453. print >> output, entry
  1454. def reload_raw_table(self, input):
  1455. firstline = input.readline()
  1456. assert firstline == 'raw table\n'
  1457. for line in input:
  1458. entry = eval(line)
  1459. assert type(entry) is tuple
  1460. self.gcmaptable.append(entry)
  1461. def dump(self, output):
  1462. def _globalname(name, disp=""):
  1463. return tracker_cls.function_names_prefix + name
  1464. def _variant(**kwargs):
  1465. txt = kwargs[self.format]
  1466. print >> output, "\t%s" % txt
  1467. if self.format in ('elf64', 'darwin64'):
  1468. word_decl = '.quad'
  1469. else:
  1470. word_decl = '.long'
  1471. tracker_cls = PARSERS[self.format].FunctionGcRootTracker
  1472. # The pypy_asm_stackwalk() function
  1473. if self.format == 'msvc':
  1474. print >> output, """\
  1475. /* See description in asmgcroot.py */
  1476. __declspec(naked)
  1477. long pypy_asm_stackwalk(void *callback)
  1478. {
  1479. __asm {
  1480. mov\tedx, DWORD PTR [esp+4]\t; 1st argument, which is the callback
  1481. mov\tecx, DWORD PTR [esp+8]\t; 2nd argument, which is gcrootanchor
  1482. mov\teax, esp\t\t; my frame top address
  1483. push\teax\t\t\t; ASM_FRAMEDATA[6]
  1484. push\tebp\t\t\t; ASM_FRAMEDATA[5]
  1485. push\tedi\t\t\t; ASM_FRAMEDATA[4]
  1486. push\tesi\t\t\t; ASM_FRAMEDATA[3]
  1487. push\tebx\t\t\t; ASM_FRAMEDATA[2]
  1488. ; Add this ASM_FRAMEDATA to the front of the circular linked
  1489. ; list. Let's call it 'self'.
  1490. mov\teax, DWORD PTR [ecx+4]\t\t; next = gcrootanchor->next
  1491. push\teax\t\t\t\t\t\t\t\t\t; self->next = next
  1492. push\tecx ; self->prev = gcrootanchor
  1493. mov\tDWORD PTR [ecx+4], esp\t\t; gcrootanchor->next = self
  1494. mov\tDWORD PTR [eax+0], esp\t\t\t\t\t; next->prev = self
  1495. call\tedx\t\t\t\t\t\t; invoke the callback
  1496. ; Detach this ASM_FRAMEDATA from the circular linked list
  1497. pop\tesi\t\t\t\t\t\t\t; prev = self->prev
  1498. pop\tedi\t\t\t\t\t\t\t; next = self->next
  1499. mov\tDWORD PTR [esi+4], edi\t\t; prev->next = next
  1500. mov\tDWORD PTR [edi+0], esi\t\t; next->prev = prev
  1501. pop\tebx\t\t\t\t; restore from ASM_FRAMEDATA[2]
  1502. pop\tesi\t\t\t\t; restore from ASM_FRAMEDATA[3]
  1503. pop\tedi\t\t\t\t; restore from ASM_FRAMEDATA[4]
  1504. pop\tebp\t\t\t\t; restore from ASM_FRAMEDATA[5]
  1505. pop\tecx\t\t\t\t; ignored ASM_FRAMEDATA[6]
  1506. ; the return value is the one of the 'call' above,
  1507. ; because %eax (and possibly %edx) are unmodified
  1508. ret
  1509. }
  1510. }
  1511. """
  1512. elif self.format in ('elf64', 'darwin64'):
  1513. if self.format == 'elf64': # gentoo patch: hardened systems
  1514. print >> output, "\t.section .note.GNU-stack,\"\",%progbits"
  1515. print >> output, "\t.text"
  1516. print >> output, "\t.globl %s" % _globalname('pypy_asm_stackwalk')
  1517. _variant(elf64='.type pypy_asm_stackwalk, @function',
  1518. darwin64='')
  1519. print >> output, "%s:" % _globalname('pypy_asm_stackwalk')
  1520. s = """\
  1521. /* See description in asmgcroot.py */
  1522. .cfi_startproc
  1523. /* %rdi is the 1st argument, which is the callback */
  1524. /* %rsi is the 2nd argument, which is gcrootanchor */
  1525. movq\t%rsp, %rax\t/* my frame top address */
  1526. pushq\t%rax\t\t/* ASM_FRAMEDATA[8] */
  1527. pushq\t%rbp\t\t/* ASM_FRAMEDATA[7] */
  1528. pushq\t%r15\t\t/* ASM_FRAMEDATA[6] */
  1529. pushq\t%r14\t\t/* ASM_FRAMEDATA[5] */
  1530. pushq\t%r13\t\t/* ASM_FRAMEDATA[4] */
  1531. pushq\t%r12\t\t/* ASM_FRAMEDATA[3] */
  1532. pushq\t%rbx\t\t/* ASM_FRAMEDATA[2] */
  1533. /* Add this ASM_FRAMEDATA to the front of the circular linked */
  1534. /* list. Let's call it 'self'. */
  1535. movq\t8(%rsi), %rax\t/* next = gcrootanchor->next */
  1536. pushq\t%rax\t\t\t\t/* self->next = next */
  1537. pushq\t%rsi\t\t\t/* self->prev = gcrootanchor */
  1538. movq\t%rsp, 8(%rsi)\t/* gcrootanchor->next = self */
  1539. movq\t%rsp, 0(%rax)\t\t\t/* next->prev = self */
  1540. .cfi_def_cfa_offset 80\t/* 9 pushes + the retaddr = 80 bytes */
  1541. /* note: the Mac OS X 16 bytes aligment must be respected. */
  1542. call\t*%rdi\t\t/* invoke the callback */
  1543. /* Detach this ASM_FRAMEDATA from the circular linked list */
  1544. popq\t%rsi\t\t/* prev = self->prev */
  1545. popq\t%rdi\t\t/* next = self->next */
  1546. movq\t%rdi, 8(%rsi)\t/* prev->next = next */
  1547. movq\t%rsi, 0(%rdi)\t/* next->prev = prev */
  1548. popq\t%rbx\t\t/* restore from ASM_FRAMEDATA[2] */
  1549. popq\t%r12\t\t/* restore from ASM_FRAMEDATA[3] */
  1550. popq\t%r13\t\t/* restore from ASM_FRAMEDATA[4] */
  1551. popq\t%r14\t\t/* restore from ASM_FRAMEDATA[5] */
  1552. popq\t%r15\t\t/* restore from ASM_FRAMEDATA[6] */
  1553. popq\t%rbp\t\t/* restore from ASM_FRAMEDATA[7] */
  1554. popq\t%rcx\t\t/* ignored ASM_FRAMEDATA[8] */
  1555. /* the return value is the one of the 'call' above, */
  1556. /* because %rax is unmodified */
  1557. ret
  1558. .cfi_endproc
  1559. """
  1560. if self.format == 'darwin64':
  1561. # obscure. gcc there seems not to support .cfi_...
  1562. # hack it out...
  1563. s = re.sub(r'([.]cfi_[^/\n]+)([/\n])',
  1564. r'/* \1 disabled on darwin */\2', s)
  1565. print >> output, s
  1566. _variant(elf64='.size pypy_asm_stackwalk, .-pypy_asm_stackwalk',
  1567. darwin64='')
  1568. else:
  1569. print >> output, "\t.text"
  1570. print >> output, "\t.globl %s" % _globalname('pypy_asm_stackwalk')
  1571. _variant(elf='.type pypy_asm_stackwalk, @function',
  1572. darwin='',
  1573. mingw32='')
  1574. print >> output, "%s:" % _globalname('pypy_asm_stackwalk')
  1575. print >> output, """\
  1576. /* See description in asmgcroot.py */
  1577. movl\t4(%esp), %edx\t/* 1st argument, which is the callback */
  1578. movl\t8(%esp), %ecx\t/* 2nd argument, which is gcrootanchor */
  1579. movl\t%esp, %eax\t/* my frame top address */
  1580. pushl\t%eax\t\t/* ASM_FRAMEDATA[6] */
  1581. pushl\t%ebp\t\t/* ASM_FRAMEDATA[5] */
  1582. pushl\t%edi\t\t/* ASM_FRAMEDATA[4] */
  1583. pushl\t%esi\t\t/* ASM_FRAMEDATA[3] */
  1584. pushl\t%ebx\t\t/* ASM_FRAMEDATA[2] */
  1585. /* Add this ASM_FRAMEDATA to the front of the circular linked */
  1586. /* list. Let's call it 'self'. */
  1587. movl\t4(%ecx), %eax\t/* next = gcrootanchor->next */
  1588. pushl\t%eax\t\t\t\t/* self->next = next */
  1589. pushl\t%ecx\t\t\t/* self->prev = gcrootanchor */
  1590. movl\t%esp, 4(%ecx)\t/* gcrootanchor->next = self */
  1591. movl\t%esp, 0(%eax)\t\t\t/* next->prev = self */
  1592. /* note: the Mac OS X 16 bytes aligment must be respected. */
  1593. call\t*%edx\t\t/* invoke the callback */
  1594. /* Detach this ASM_FRAMEDATA from the circular linked list */
  1595. popl\t%esi\t\t/* prev = self->prev */
  1596. popl\t%edi\t\t/* next = self->next */
  1597. movl\t%edi, 4(%esi)\t/* prev->next = next */
  1598. movl\t%esi, 0(%edi)\t/* next->prev = prev */
  1599. popl\t%ebx\t\t/* restore from ASM_FRAMEDATA[2] */
  1600. popl\t%esi\t\t/* restore from ASM_FRAMEDATA[3] */
  1601. popl\t%edi\t\t/* restore from ASM_FRAMEDATA[4] */
  1602. popl\t%ebp\t\t/* restore from ASM_FRAMEDATA[5] */
  1603. popl\t%ecx\t\t/* ignored ASM_FRAMEDATA[6] */
  1604. /* the return value is the one of the 'call' above, */
  1605. /* because %eax (and possibly %edx) are unmodified */
  1606. ret
  1607. """
  1608. _variant(elf='.size pypy_asm_stackwalk, .-pypy_asm_stackwalk',
  1609. darwin='',
  1610. mingw32='')
  1611. if self.format == 'msvc':
  1612. for label, state, is_range in self.gcmaptable:
  1613. label = label[1:]
  1614. print >> output, "extern void* %s;" % label
  1615. shapes = {}
  1616. shapelines = []
  1617. shapeofs = 0
  1618. # write the tables
  1619. if self.format == 'msvc':
  1620. print >> output, """\
  1621. static struct { void* addr; long shape; } __gcmap[%d] = {
  1622. """ % (len(self.gcmaptable),)
  1623. for label, state, is_range in self.gcmaptable:
  1624. label = label[1:]
  1625. try:
  1626. n = shapes[state]
  1627. except KeyError:
  1628. n = shapes[state] = shapeofs
  1629. bytes = [str(b) for b in tracker_cls.compress_callshape(state)]
  1630. shapelines.append('\t%s,\t/* %s */\n' % (
  1631. ', '.join(bytes),
  1632. shapeofs))
  1633. shapeofs += len(bytes)
  1634. if is_range:
  1635. n = ~ n
  1636. print >> output, '{ &%s, %d},' % (label, n)
  1637. print >> output, """\
  1638. };
  1639. void* __gcmapstart = __gcmap;
  1640. void* __gcmapend = __gcmap + %d;
  1641. char __gccallshapes[] = {
  1642. """ % (len(self.gcmaptable),)
  1643. output.writelines(shapelines)
  1644. print >> output, """\
  1645. };
  1646. """
  1647. else:
  1648. print >> output, """\
  1649. .data
  1650. .align 4
  1651. .globl __gcmapstart
  1652. __gcmapstart:
  1653. """.replace("__gcmapstart", _globalname("__gcmapstart"))
  1654. for label, state, is_range in self.gcmaptable:
  1655. try:
  1656. n = shapes[state]
  1657. except KeyError:
  1658. n = shapes[state] = shapeofs
  1659. bytes = [str(b) for b in tracker_cls.compress_callshape(state)]
  1660. shapelines.append('\t/*%d*/\t.byte\t%s\n' % (
  1661. shapeofs,
  1662. ', '.join(bytes)))
  1663. shapeofs += len(bytes)
  1664. if is_range:
  1665. n = ~ n
  1666. print >> output, '\t%s\t%s-%d' % (
  1667. word_decl,
  1668. label,
  1669. tracker_cls.OFFSET_LABELS)
  1670. print >> output, '\t%s\t%d' % (word_decl, n)
  1671. print >> output, """\
  1672. .globl __gcmapend
  1673. __gcmapend:
  1674. """.replace("__gcmapend", _globalname("__gcmapend"))
  1675. _variant(elf='.section\t.rodata',
  1676. elf64='.section\t.rodata',
  1677. darwin='.const',
  1678. darwin64='.const',
  1679. mingw32='')
  1680. print >> output, """\
  1681. .globl __gccallshapes
  1682. __gccallshapes:
  1683. """.replace("__gccallshapes", _globalname("__gccallshapes"))
  1684. output.writelines(shapelines)
  1685. print >> output, """\
  1686. #if defined(__linux__) && defined(__ELF__)
  1687. .section .note.GNU-stack,"",%progbits
  1688. #endif
  1689. """
  1690. def process(self, iterlines, newfile, filename='?'):
  1691. parser = PARSERS[format](verbose=self.verbose, shuffle=self.shuffle)
  1692. for in_function, lines in parser.find_functions(iterlines):
  1693. if in_function:
  1694. tracker = parser.process_function(lines, filename)
  1695. lines = tracker.lines
  1696. parser.write_newfile(newfile, lines, filename.split('.')[0])
  1697. if self.verbose == 1:
  1698. sys.stderr.write('\n')
  1699. if self.shuffle and random.random() < 0.5:
  1700. self.gcmaptable[:0] = parser.gcmaptable
  1701. else:
  1702. self.gcmaptable.extend(parser.gcmaptable)
  1703. class UnrecognizedOperation(Exception):
  1704. pass
  1705. class NoPatternMatch(Exception):
  1706. pass
  1707. # __________ table compression __________
  1708. def compress_gcmaptable(table):
  1709. # Compress ranges table[i:j] of entries with the same state
  1710. # into a single entry whose label is the start of the range.
  1711. # The last element in the table is never compressed in this
  1712. # way for debugging reasons, to avoid that a random address
  1713. # in memory gets mapped to the last element in the table
  1714. # just because it's the closest address.
  1715. # To be on the safe side, compress_gcmaptable() should be called
  1716. # after each function processed -- otherwise the result depends on
  1717. # the linker not rearranging the functions in memory, which is
  1718. # fragile (and wrong e.g. with "make profopt").
  1719. i = 0
  1720. limit = len(table) - 1 # only process entries table[:limit]
  1721. while i < len(table):
  1722. label1, state = table[i]
  1723. is_range = False
  1724. j = i + 1
  1725. while j < limit and table[j][1] == state:
  1726. is_range = True
  1727. j += 1
  1728. # now all entries in table[i:j] have the same state
  1729. yield (label1, state, is_range)
  1730. i = j
  1731. def getidentifier(s):
  1732. def mapchar(c):
  1733. if c.isalnum():
  1734. return c
  1735. else:
  1736. return '_'
  1737. if s.endswith('.s'):
  1738. s = s[:-2]
  1739. s = ''.join([mapchar(c) for c in s])
  1740. while s.endswith('__'):
  1741. s = s[:-1]
  1742. return s
  1743. if __name__ == '__main__':
  1744. verbose = 0
  1745. shuffle = False
  1746. output_raw_table = False
  1747. if sys.platform == 'darwin':
  1748. if sys.maxint > 2147483647:
  1749. format = 'darwin64'
  1750. else:
  1751. format = 'darwin'
  1752. elif sys.platform == 'win32':
  1753. format = 'mingw32'
  1754. else:
  1755. if sys.maxint > 2147483647:
  1756. format = 'elf64'
  1757. else:
  1758. format = 'elf'
  1759. while len(sys.argv) > 1:
  1760. if sys.argv[1] == '-v':
  1761. del sys.argv[1]
  1762. verbose = sys.maxint
  1763. elif sys.argv[1] == '-r':
  1764. del sys.argv[1]
  1765. shuffle = True
  1766. elif sys.argv[1] == '-t':
  1767. del sys.argv[1]
  1768. output_raw_table = True
  1769. elif sys.argv[1].startswith('-f'):
  1770. format = sys.argv[1][2:]
  1771. del sys.argv[1]
  1772. elif sys.argv[1].startswith('-'):
  1773. print >> sys.stderr, "unrecognized option:", sys.argv[1]
  1774. sys.exit(1)
  1775. else:
  1776. break
  1777. tracker = GcRootTracker(verbose=verbose, shuffle=shuffle, format=format)
  1778. for fn in sys.argv[1:]:
  1779. f = open(fn, 'r')
  1780. firstline = f.readline()
  1781. f.seek(0)
  1782. assert firstline, "file %r is empty!" % (fn,)
  1783. if firstline == 'raw table\n':
  1784. tracker.reload_raw_table(f)
  1785. f.close()
  1786. else:
  1787. assert fn.endswith('.s'), fn
  1788. lblfn = fn[:-2] + '.lbl.s'
  1789. g = open(lblfn, 'w')
  1790. try:
  1791. tracker.process(f, g, filename=fn)
  1792. except:
  1793. g.close()
  1794. os.unlink(lblfn)
  1795. raise
  1796. g.close()
  1797. f.close()
  1798. if output_raw_table:
  1799. tracker.dump_raw_table(sys.stdout)
  1800. if not output_raw_table:
  1801. tracker.dump(sys.stdout)