PageRenderTime 34ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 1ms

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

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