PageRenderTime 30ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

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

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