PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/varialus/jyjy
Python | 2033 lines | 1880 code | 66 blank | 87 comment | 183 complexity | 2952b5dcd162bbcb07413af3b4fce814 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. #! /usr/bin/env python
  2. import autopath
  3. import re, sys, os, random
  4. from pypy.translator.c.gcc.instruction import Insn, Label, InsnCall, InsnRet
  5. from pypy.translator.c.gcc.instruction import InsnFunctionStart, InsnStop
  6. from pypy.translator.c.gcc.instruction import InsnSetLocal, InsnCopyLocal
  7. from pypy.translator.c.gcc.instruction import InsnPrologue, InsnEpilogue
  8. from pypy.translator.c.gcc.instruction import InsnGCROOT, InsnCondJump
  9. from pypy.translator.c.gcc.instruction import InsnStackAdjust
  10. from pypy.translator.c.gcc.instruction import InsnCannotFollowEsp
  11. from pypy.translator.c.gcc.instruction import LocalVar, somenewvalue
  12. from pypy.translator.c.gcc.instruction import frameloc_esp, frameloc_ebp
  13. from pypy.translator.c.gcc.instruction import LOC_REG, LOC_NOWHERE, LOC_MASK
  14. from pypy.translator.c.gcc.instruction import LOC_EBP_PLUS, LOC_EBP_MINUS
  15. from pypy.translator.c.gcc.instruction import LOC_ESP_PLUS
  16. class FunctionGcRootTracker(object):
  17. skip = 0
  18. COMMENT = "([#;].*)?"
  19. @classmethod
  20. def init_regexp(cls):
  21. cls.r_label = re.compile(cls.LABEL+"[:]\s*$")
  22. cls.r_globl = re.compile(r"\t[.]globl\t"+cls.LABEL+"\s*$")
  23. cls.r_globllabel = re.compile(cls.LABEL+r"=[.][+]%d\s*$"%cls.OFFSET_LABELS)
  24. cls.r_insn = re.compile(r"\t([a-z]\w*)\s")
  25. cls.r_unaryinsn = re.compile(r"\t[a-z]\w*\s+("+cls.OPERAND+")\s*" + cls.COMMENT + "$")
  26. cls.r_binaryinsn = re.compile(r"\t[a-z]\w*\s+(?P<source>"+cls.OPERAND+"),\s*(?P<target>"+cls.OPERAND+")\s*$")
  27. cls.r_jump = re.compile(r"\tj\w+\s+"+cls.LABEL+"\s*" + cls.COMMENT + "$")
  28. cls.r_jmp_switch = re.compile(r"\tjmp\t[*]"+cls.LABEL+"[(]")
  29. cls.r_jmp_source = re.compile(r"\d*[(](%[\w]+)[,)]")
  30. def __init__(self, funcname, lines, filetag=0):
  31. self.funcname = funcname
  32. self.lines = lines
  33. self.uses_frame_pointer = False
  34. self.r_localvar = self.r_localvarnofp
  35. self.filetag = filetag
  36. # a "stack bottom" function is either pypy_main_function() or a
  37. # callback from C code. In both cases they are identified by
  38. # the presence of pypy_asm_stack_bottom().
  39. self.is_stack_bottom = False
  40. def computegcmaptable(self, verbose=0):
  41. if self.funcname in ['main', '_main']:
  42. return [] # don't analyze main(), its prologue may contain
  43. # strange instructions
  44. self.findlabels()
  45. self.parse_instructions()
  46. try:
  47. self.trim_unreachable_instructions()
  48. self.find_noncollecting_calls()
  49. if not self.list_collecting_call_insns():
  50. return []
  51. self.findframesize()
  52. self.fixlocalvars()
  53. self.trackgcroots()
  54. self.extend_calls_with_labels()
  55. finally:
  56. if verbose > 2:
  57. self.dump()
  58. return self.gettable()
  59. def replace_symbols(self, operand):
  60. return operand
  61. def gettable(self):
  62. """Returns a list [(label_after_call, callshape_tuple)]
  63. See format_callshape() for more details about callshape_tuple.
  64. """
  65. table = []
  66. for insn in self.list_collecting_call_insns():
  67. if not hasattr(insn, 'framesize'):
  68. continue # calls that never end up reaching a RET
  69. if self.is_stack_bottom:
  70. retaddr = LOC_NOWHERE # end marker for asmgcroot.py
  71. elif self.uses_frame_pointer:
  72. retaddr = frameloc_ebp(self.WORD, self.WORD)
  73. else:
  74. retaddr = frameloc_esp(insn.framesize, self.WORD)
  75. shape = [retaddr]
  76. # the first gcroots are always the ones corresponding to
  77. # the callee-saved registers
  78. for reg in self.CALLEE_SAVE_REGISTERS:
  79. shape.append(LOC_NOWHERE)
  80. gcroots = []
  81. for localvar, tag in insn.gcroots.items():
  82. if isinstance(localvar, LocalVar):
  83. loc = localvar.getlocation(insn.framesize,
  84. self.uses_frame_pointer,
  85. self.WORD)
  86. elif localvar in self.REG2LOC:
  87. loc = self.REG2LOC[localvar]
  88. else:
  89. assert False, "%s: %s" % (self.funcname,
  90. localvar)
  91. assert isinstance(loc, int)
  92. if tag is None:
  93. gcroots.append(loc)
  94. else:
  95. regindex = self.CALLEE_SAVE_REGISTERS.index(tag)
  96. shape[1 + regindex] = loc
  97. if LOC_NOWHERE in shape and not self.is_stack_bottom:
  98. reg = self.CALLEE_SAVE_REGISTERS[shape.index(LOC_NOWHERE) - 1]
  99. raise AssertionError("cannot track where register %s is saved"
  100. % (reg,))
  101. gcroots.sort()
  102. shape.extend(gcroots)
  103. table.append((insn.global_label, tuple(shape)))
  104. return table
  105. def findlabels(self):
  106. self.labels = {} # {name: Label()}
  107. for lineno, line in enumerate(self.lines):
  108. match = self.r_label.match(line)
  109. label = None
  110. if match:
  111. label = match.group(1)
  112. else:
  113. # labels used by: j* NNNf
  114. match = self.r_rel_label.match(line)
  115. if match:
  116. label = "rel %d" % lineno
  117. if label:
  118. assert label not in self.labels, "duplicate label: %s" % label
  119. self.labels[label] = Label(label, lineno)
  120. def trim_unreachable_instructions(self):
  121. reached = set([self.insns[0]])
  122. prevlen = 0
  123. while len(reached) > prevlen:
  124. prevlen = len(reached)
  125. for insn in self.insns:
  126. if insn not in reached:
  127. for previnsn in insn.previous_insns:
  128. if previnsn in reached:
  129. # this instruction is reachable too
  130. reached.add(insn)
  131. break
  132. # now kill all unreachable instructions
  133. i = 0
  134. while i < len(self.insns):
  135. if self.insns[i] in reached:
  136. i += 1
  137. else:
  138. del self.insns[i]
  139. def find_noncollecting_calls(self):
  140. cannot_collect = {}
  141. for line in self.lines:
  142. match = self.r_gcnocollect_marker.search(line)
  143. if match:
  144. name = match.group(1)
  145. cannot_collect[name] = True
  146. #
  147. self.cannot_collect = dict.fromkeys(
  148. [self.function_names_prefix + name for name in cannot_collect])
  149. def append_instruction(self, insn):
  150. # Add the instruction to the list, and link it to the previous one.
  151. previnsn = self.insns[-1]
  152. self.insns.append(insn)
  153. if (isinstance(insn, (InsnSetLocal, InsnCopyLocal)) and
  154. insn.target == self.tested_for_zero):
  155. self.tested_for_zero = None
  156. try:
  157. lst = insn.previous_insns
  158. except AttributeError:
  159. lst = insn.previous_insns = []
  160. if not isinstance(previnsn, InsnStop):
  161. lst.append(previnsn)
  162. def parse_instructions(self):
  163. self.insns = [InsnFunctionStart(self.CALLEE_SAVE_REGISTERS, self.WORD)]
  164. self.tested_for_zero = None
  165. ignore_insns = False
  166. for lineno, line in enumerate(self.lines):
  167. if lineno < self.skip:
  168. continue
  169. self.currentlineno = lineno
  170. insn = []
  171. match = self.r_insn.match(line)
  172. if self.r_bottom_marker.match(line):
  173. self.is_stack_bottom = True
  174. elif match:
  175. if not ignore_insns:
  176. opname = match.group(1)
  177. #
  178. try:
  179. cf = self.OPS_WITH_PREFIXES_CHANGING_FLAGS[opname]
  180. except KeyError:
  181. cf = self.find_missing_changing_flags(opname)
  182. if cf:
  183. self.tested_for_zero = None
  184. #
  185. try:
  186. meth = getattr(self, 'visit_' + opname)
  187. except AttributeError:
  188. self.find_missing_visit_method(opname)
  189. meth = getattr(self, 'visit_' + opname)
  190. line = line.rsplit(';', 1)[0]
  191. insn = meth(line)
  192. elif self.r_gcroot_marker.match(line):
  193. insn = self._visit_gcroot_marker(line)
  194. elif line == '\t/* ignore_in_trackgcroot */\n':
  195. ignore_insns = True
  196. elif line == '\t/* end_ignore_in_trackgcroot */\n':
  197. ignore_insns = False
  198. else:
  199. match = self.r_label.match(line)
  200. if match:
  201. insn = self.labels[match.group(1)]
  202. if isinstance(insn, list):
  203. for i in insn:
  204. self.append_instruction(i)
  205. else:
  206. self.append_instruction(insn)
  207. del self.currentlineno
  208. @classmethod
  209. def find_missing_visit_method(cls, opname):
  210. # only for operations that are no-ops as far as we are concerned
  211. prefix = opname
  212. while prefix not in cls.IGNORE_OPS_WITH_PREFIXES:
  213. prefix = prefix[:-1]
  214. if not prefix:
  215. raise UnrecognizedOperation(opname)
  216. setattr(cls, 'visit_' + opname, cls.visit_nop)
  217. @classmethod
  218. def find_missing_changing_flags(cls, opname):
  219. prefix = opname
  220. while prefix and prefix not in cls.OPS_WITH_PREFIXES_CHANGING_FLAGS:
  221. prefix = prefix[:-1]
  222. cf = cls.OPS_WITH_PREFIXES_CHANGING_FLAGS.get(prefix, False)
  223. cls.OPS_WITH_PREFIXES_CHANGING_FLAGS[opname] = cf
  224. return cf
  225. def list_collecting_call_insns(self):
  226. return [insn for insn in self.insns if isinstance(insn, InsnCall)
  227. if insn.name not in self.cannot_collect]
  228. def findframesize(self):
  229. # the 'framesize' attached to an instruction is the number of bytes
  230. # in the frame at this point. This doesn't count the return address
  231. # which is the word immediately following the frame in memory.
  232. # The 'framesize' is set to an odd value if it is only an estimate
  233. # (see InsnCannotFollowEsp).
  234. def walker(insn, size_delta):
  235. check = deltas.setdefault(insn, size_delta)
  236. assert check == size_delta, (
  237. "inconsistent frame size at instruction %s" % (insn,))
  238. if isinstance(insn, InsnStackAdjust):
  239. size_delta -= insn.delta
  240. if not hasattr(insn, 'framesize'):
  241. yield size_delta # continue walking backwards
  242. for insn in self.insns:
  243. if isinstance(insn, (InsnRet, InsnEpilogue, InsnGCROOT)):
  244. deltas = {}
  245. self.walk_instructions_backwards(walker, insn, 0)
  246. size_at_insn = []
  247. for insn1, delta1 in deltas.items():
  248. if hasattr(insn1, 'framesize'):
  249. size_at_insn.append(insn1.framesize + delta1)
  250. if not size_at_insn:
  251. continue
  252. size_at_insn = size_at_insn[0]
  253. for insn1, delta1 in deltas.items():
  254. size_at_insn1 = size_at_insn - delta1
  255. if hasattr(insn1, 'framesize'):
  256. assert insn1.framesize == size_at_insn1, (
  257. "inconsistent frame size at instruction %s" %
  258. (insn1,))
  259. else:
  260. insn1.framesize = size_at_insn1
  261. def fixlocalvars(self):
  262. def fixvar(localvar):
  263. if localvar is None:
  264. return None
  265. elif isinstance(localvar, (list, tuple)):
  266. return [fixvar(var) for var in localvar]
  267. match = self.r_localvar_esp.match(localvar)
  268. if match:
  269. if localvar == self.TOP_OF_STACK_MINUS_WORD:
  270. # for pushl and popl, by
  271. hint = None # default ebp addressing is
  272. else: # a bit nicer
  273. hint = 'esp'
  274. ofs_from_esp = int(match.group(1) or '0')
  275. if self.format == 'msvc':
  276. ofs_from_esp += int(match.group(2) or '0')
  277. localvar = ofs_from_esp - insn.framesize
  278. assert localvar != 0 # that's the return address
  279. return LocalVar(localvar, hint=hint)
  280. elif self.uses_frame_pointer:
  281. match = self.r_localvar_ebp.match(localvar)
  282. if match:
  283. ofs_from_ebp = int(match.group(1) or '0')
  284. if self.format == 'msvc':
  285. ofs_from_ebp += int(match.group(2) or '0')
  286. localvar = ofs_from_ebp - self.WORD
  287. assert localvar != 0 # that's the return address
  288. return LocalVar(localvar, hint='ebp')
  289. return localvar
  290. for insn in self.insns:
  291. if not hasattr(insn, 'framesize'):
  292. continue
  293. for name in insn._locals_:
  294. localvar = getattr(insn, name)
  295. setattr(insn, name, fixvar(localvar))
  296. def trackgcroots(self):
  297. def walker(insn, loc):
  298. source = insn.source_of(loc, tag)
  299. if source is somenewvalue:
  300. pass # done
  301. else:
  302. yield source
  303. for insn in self.insns:
  304. for loc, tag in insn.requestgcroots(self).items():
  305. self.walk_instructions_backwards(walker, insn, loc)
  306. def dump(self):
  307. for insn in self.insns:
  308. size = getattr(insn, 'framesize', '?')
  309. print >> sys.stderr, '%4s %s' % (size, insn)
  310. def walk_instructions_backwards(self, walker, initial_insn, initial_state):
  311. pending = []
  312. seen = {}
  313. def schedule(insn, state):
  314. for previnsn in insn.previous_insns:
  315. key = previnsn, state
  316. if key not in seen:
  317. seen[key] = True
  318. pending.append(key)
  319. schedule(initial_insn, initial_state)
  320. while pending:
  321. insn, state = pending.pop()
  322. for prevstate in walker(insn, state):
  323. schedule(insn, prevstate)
  324. def extend_calls_with_labels(self):
  325. # walk backwards, because inserting the global labels in self.lines
  326. # is going to invalidate the lineno of all the InsnCall objects
  327. # after the current one.
  328. for call in self.list_collecting_call_insns()[::-1]:
  329. if hasattr(call, 'framesize'):
  330. self.create_global_label(call)
  331. def create_global_label(self, call):
  332. # we need a globally-declared label just after the call.
  333. # Reuse one if it is already there (e.g. from a previous run of this
  334. # script); otherwise invent a name and add the label to tracker.lines.
  335. label = None
  336. # this checks for a ".globl NAME" followed by "NAME:"
  337. match = self.r_globl.match(self.lines[call.lineno+1])
  338. if match:
  339. label1 = match.group(1)
  340. match = self.r_globllabel.match(self.lines[call.lineno+2])
  341. if match:
  342. label2 = match.group(1)
  343. if label1 == label2:
  344. label = label2
  345. if label is None:
  346. k = call.lineno
  347. if self.format == 'msvc':
  348. # Some header files (ws2tcpip.h) define STDCALL functions
  349. funcname = self.funcname.split('@')[0]
  350. else:
  351. funcname = self.funcname
  352. while 1:
  353. label = '__gcmap_%s__%s_%d' % (self.filetag, funcname, k)
  354. if label not in self.labels:
  355. break
  356. k += 1
  357. self.labels[label] = None
  358. if self.format == 'msvc':
  359. self.lines.insert(call.lineno+1, '%s::\n' % (label,))
  360. self.lines.insert(call.lineno+1, 'PUBLIC\t%s\n' % (label,))
  361. else:
  362. # These global symbols are not directly labels pointing to the
  363. # code location because such global labels in the middle of
  364. # functions confuse gdb. Instead, we add to the global symbol's
  365. # value a big constant, which is subtracted again when we need
  366. # the original value for gcmaptable.s. That's a hack.
  367. self.lines.insert(call.lineno+1, '%s=.+%d\n' % (label,
  368. self.OFFSET_LABELS))
  369. self.lines.insert(call.lineno+1, '\t.globl\t%s\n' % (label,))
  370. call.global_label = label
  371. @classmethod
  372. def compress_callshape(cls, shape):
  373. # For a single shape, this turns the list of integers into a list of
  374. # bytes and reverses the order of the entries. The length is
  375. # encoded by inserting a 0 marker after the gc roots coming from
  376. # shape[N:] and before the N values coming from shape[N-1] to
  377. # shape[0] (for N == 5 on 32-bit or 7 on 64-bit platforms).
  378. # In practice it seems that shapes contain many integers
  379. # whose value is up to a few thousands, which the algorithm below
  380. # compresses down to 2 bytes. Very small values compress down to a
  381. # single byte.
  382. # Callee-save regs plus ret addr
  383. min_size = len(cls.CALLEE_SAVE_REGISTERS) + 1
  384. assert len(shape) >= min_size
  385. shape = list(shape)
  386. assert 0 not in shape[min_size:]
  387. shape.insert(min_size, 0)
  388. result = []
  389. for loc in shape:
  390. assert loc >= 0
  391. flag = 0
  392. while loc >= 0x80:
  393. result.append(int(loc & 0x7F) | flag)
  394. flag = 0x80
  395. loc >>= 7
  396. result.append(int(loc) | flag)
  397. result.reverse()
  398. return result
  399. @classmethod
  400. def decompress_callshape(cls, bytes):
  401. # For tests. This logic is copied in asmgcroot.py.
  402. result = []
  403. n = 0
  404. while n < len(bytes):
  405. value = 0
  406. while True:
  407. b = bytes[n]
  408. n += 1
  409. value += b
  410. if b < 0x80:
  411. break
  412. value = (value - 0x80) << 7
  413. result.append(value)
  414. result.reverse()
  415. assert result[5] == 0
  416. del result[5]
  417. return result
  418. # ____________________________________________________________
  419. BASE_FUNCTIONS_NOT_RETURNING = {
  420. 'abort': None,
  421. 'pypy_debug_catch_fatal_exception': None,
  422. 'RPyAbort': None,
  423. 'RPyAssertFailed': None,
  424. }
  425. def _visit_gcroot_marker(self, line):
  426. match = self.r_gcroot_marker.match(line)
  427. loc = match.group(1)
  428. return InsnGCROOT(self.replace_symbols(loc))
  429. def visit_nop(self, line):
  430. return []
  431. IGNORE_OPS_WITH_PREFIXES = dict.fromkeys([
  432. 'cmp', 'test', 'set', 'sahf', 'lahf', 'cld', 'std',
  433. 'rep', 'movs', 'movhp', 'lods', 'stos', 'scas', 'cwde', 'prefetch',
  434. # floating-point operations cannot produce GC pointers
  435. 'f',
  436. 'cvt', 'ucomi', 'comi', 'subs', 'subp' , 'adds', 'addp', 'xorp',
  437. 'movap', 'movd', 'movlp', 'movup', 'sqrt', 'rsqrt', 'movhpd',
  438. 'mins', 'minp', 'maxs', 'maxp', 'unpck', 'pxor', 'por', # sse2
  439. 'shufps', 'shufpd',
  440. # arithmetic operations should not produce GC pointers
  441. 'inc', 'dec', 'not', 'neg', 'or', 'and', 'sbb', 'adc',
  442. 'shl', 'shr', 'sal', 'sar', 'rol', 'ror', 'mul', 'imul', 'div', 'idiv',
  443. 'bswap', 'bt', 'rdtsc', 'rounds',
  444. 'pabs', 'pack', 'padd', 'palign', 'pand', 'pavg', 'pcmp', 'pextr',
  445. 'phadd', 'phsub', 'pinsr', 'pmadd', 'pmax', 'pmin', 'pmovmsk',
  446. 'pmul', 'por', 'psadb', 'pshuf', 'psign', 'psll', 'psra', 'psrl',
  447. 'psub', 'punpck', 'pxor',
  448. # all vectors don't produce pointers
  449. 'v',
  450. # sign-extending moves should not produce GC pointers
  451. 'cbtw', 'cwtl', 'cwtd', 'cltd', 'cltq', 'cqto',
  452. # zero-extending moves should not produce GC pointers
  453. 'movz',
  454. # locked operations should not move GC pointers, at least so far
  455. 'lock', 'pause',
  456. ])
  457. # a partial list is hopefully good enough for now; it's all to support
  458. # only one corner case, tested in elf64/track_zero.s
  459. OPS_WITH_PREFIXES_CHANGING_FLAGS = dict.fromkeys([
  460. 'cmp', 'test', 'lahf', 'cld', 'std', 'rep',
  461. 'ucomi', 'comi',
  462. 'add', 'sub', 'xor',
  463. 'inc', 'dec', 'not', 'neg', 'or', 'and', 'sbb', 'adc',
  464. 'shl', 'shr', 'sal', 'sar', 'rol', 'ror', 'mul', 'imul', 'div', 'idiv',
  465. 'bt', 'call', 'int',
  466. 'jmp', # not really changing flags, but we shouldn't assume
  467. # anything about the operations on the following lines
  468. ], True)
  469. visit_movb = visit_nop
  470. visit_movw = visit_nop
  471. visit_addb = visit_nop
  472. visit_addw = visit_nop
  473. visit_subb = visit_nop
  474. visit_subw = visit_nop
  475. visit_xorb = visit_nop
  476. visit_xorw = visit_nop
  477. def _visit_add(self, line, sign=+1):
  478. match = self.r_binaryinsn.match(line)
  479. source = match.group("source")
  480. target = match.group("target")
  481. if target == self.ESP:
  482. count = self.extract_immediate(source)
  483. if count is None:
  484. # strange instruction - I've seen 'subl %eax, %esp'
  485. return InsnCannotFollowEsp()
  486. return InsnStackAdjust(sign * count)
  487. elif self.r_localvar.match(target):
  488. return InsnSetLocal(target, [source, target])
  489. else:
  490. return []
  491. def _visit_sub(self, line):
  492. return self._visit_add(line, sign=-1)
  493. def unary_insn(self, line):
  494. match = self.r_unaryinsn.match(line)
  495. target = match.group(1)
  496. if self.r_localvar.match(target):
  497. return InsnSetLocal(target)
  498. else:
  499. return []
  500. def binary_insn(self, line):
  501. match = self.r_binaryinsn.match(line)
  502. if not match:
  503. raise UnrecognizedOperation(line)
  504. source = match.group("source")
  505. target = match.group("target")
  506. if self.r_localvar.match(target):
  507. return InsnSetLocal(target, [source])
  508. elif target == self.ESP:
  509. raise UnrecognizedOperation(line)
  510. else:
  511. return []
  512. # The various cmov* operations
  513. for name in '''
  514. e ne g ge l le a ae b be p np s ns o no
  515. '''.split():
  516. locals()['visit_cmov' + name] = binary_insn
  517. locals()['visit_cmov' + name + 'l'] = binary_insn
  518. def _visit_and(self, line):
  519. match = self.r_binaryinsn.match(line)
  520. target = match.group("target")
  521. if target == self.ESP:
  522. # only for andl $-16, %esp used to align the stack in main().
  523. # main() should not be seen at all. But on e.g. MSVC we see
  524. # the instruction somewhere else too...
  525. return InsnCannotFollowEsp()
  526. else:
  527. return self.binary_insn(line)
  528. def _visit_lea(self, line):
  529. match = self.r_binaryinsn.match(line)
  530. target = match.group("target")
  531. if target == self.ESP:
  532. # only for leal -12(%ebp), %esp in function epilogues
  533. source = match.group("source")
  534. match = self.r_localvar_ebp.match(source)
  535. if match:
  536. if not self.uses_frame_pointer:
  537. raise UnrecognizedOperation('epilogue without prologue')
  538. ofs_from_ebp = int(match.group(1) or '0')
  539. assert ofs_from_ebp <= 0
  540. framesize = self.WORD - ofs_from_ebp
  541. else:
  542. match = self.r_localvar_esp.match(source)
  543. # leal 12(%esp), %esp
  544. if match:
  545. return InsnStackAdjust(int(match.group(1)))
  546. framesize = None # strange instruction
  547. return InsnEpilogue(framesize)
  548. else:
  549. return self.binary_insn(line)
  550. def insns_for_copy(self, source, target):
  551. source = self.replace_symbols(source)
  552. target = self.replace_symbols(target)
  553. if target == self.ESP:
  554. raise UnrecognizedOperation('%s -> %s' % (source, target))
  555. elif self.r_localvar.match(target):
  556. if self.r_localvar.match(source):
  557. # eg, movl %eax, %ecx: possibly copies a GC root
  558. return [InsnCopyLocal(source, target)]
  559. else:
  560. # eg, movl (%eax), %edi or mov %esp, %edi: load a register
  561. # from "outside". If it contains a pointer to a GC root,
  562. # it will be announced later with the GCROOT macro.
  563. return [InsnSetLocal(target, [source])]
  564. else:
  565. # eg, movl %ebx, (%edx) or mov %ebp, %esp: does not write into
  566. # a general register
  567. return []
  568. def _visit_mov(self, line):
  569. match = self.r_binaryinsn.match(line)
  570. source = match.group("source")
  571. target = match.group("target")
  572. if source == self.ESP and target == self.EBP:
  573. return self._visit_prologue()
  574. elif source == self.EBP and target == self.ESP:
  575. return self._visit_epilogue()
  576. if source == self.ESP and self.funcname.startswith('VALGRIND_'):
  577. return [] # in VALGRIND_XXX functions, there is a dummy-looking
  578. # mov %esp, %eax. Shows up only when compiling with
  579. # gcc -fno-unit-at-a-time.
  580. return self.insns_for_copy(source, target)
  581. def _visit_push(self, line):
  582. match = self.r_unaryinsn.match(line)
  583. source = match.group(1)
  584. return self.insns_for_copy(source, self.TOP_OF_STACK_MINUS_WORD) + \
  585. [InsnStackAdjust(-self.WORD)]
  586. def _visit_pop(self, target):
  587. return [InsnStackAdjust(+self.WORD)] + \
  588. self.insns_for_copy(self.TOP_OF_STACK_MINUS_WORD, target)
  589. def _visit_prologue(self):
  590. # for the prologue of functions that use %ebp as frame pointer
  591. self.uses_frame_pointer = True
  592. self.r_localvar = self.r_localvarfp
  593. return [InsnPrologue(self.WORD)]
  594. def _visit_epilogue(self):
  595. if not self.uses_frame_pointer:
  596. raise UnrecognizedOperation('epilogue without prologue')
  597. return [InsnEpilogue(self.WORD)]
  598. def visit_leave(self, line):
  599. return self._visit_epilogue() + self._visit_pop(self.EBP)
  600. def visit_ret(self, line):
  601. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  602. def visit_jmp(self, line):
  603. tablelabels = []
  604. match = self.r_jmp_switch.match(line)
  605. if match:
  606. # this is a jmp *Label(%index), used for table-based switches.
  607. # Assume that the table is just a list of lines looking like
  608. # .long LABEL or .long 0, ending in a .text or .section .text.hot.
  609. tablelabels.append(match.group(1))
  610. elif self.r_unaryinsn_star.match(line):
  611. # maybe a jmp similar to the above, but stored in a
  612. # registry:
  613. # movl L9341(%eax), %eax
  614. # jmp *%eax
  615. operand = self.r_unaryinsn_star.match(line).group(1)
  616. def walker(insn, locs):
  617. sources = []
  618. for loc in locs:
  619. for s in insn.all_sources_of(loc):
  620. # if the source looks like 8(%eax,%edx,4)
  621. # %eax is the real source, %edx is an offset.
  622. match = self.r_jmp_source.match(s)
  623. if match and not self.r_localvar_esp.match(s):
  624. sources.append(match.group(1))
  625. else:
  626. sources.append(s)
  627. for source in sources:
  628. label_match = re.compile(self.LABEL).match(source)
  629. if label_match:
  630. tablelabels.append(label_match.group(0))
  631. return
  632. yield tuple(sources)
  633. insn = InsnStop()
  634. insn.previous_insns = [self.insns[-1]]
  635. self.walk_instructions_backwards(walker, insn, (operand,))
  636. # Remove probable tail-calls
  637. tablelabels = [label for label in tablelabels
  638. if label in self.labels]
  639. assert len(tablelabels) <= 1
  640. if tablelabels:
  641. tablelin = self.labels[tablelabels[0]].lineno + 1
  642. while not self.r_jmptable_end.match(self.lines[tablelin]):
  643. # skip empty lines
  644. if (not self.lines[tablelin].strip()
  645. or self.lines[tablelin].startswith(';')):
  646. tablelin += 1
  647. continue
  648. match = self.r_jmptable_item.match(self.lines[tablelin])
  649. if not match:
  650. raise NoPatternMatch(repr(self.lines[tablelin]))
  651. label = match.group(1)
  652. if label != '0':
  653. self.register_jump_to(label)
  654. tablelin += 1
  655. return InsnStop("jump table")
  656. if self.r_unaryinsn_star.match(line):
  657. # that looks like an indirect tail-call.
  658. # tail-calls are equivalent to RET for us
  659. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  660. try:
  661. self.conditional_jump(line)
  662. except KeyError:
  663. # label not found: check if it's a tail-call turned into a jump
  664. match = self.r_unaryinsn.match(line)
  665. target = match.group(1)
  666. assert not target.startswith('.')
  667. # tail-calls are equivalent to RET for us
  668. return InsnRet(self.CALLEE_SAVE_REGISTERS)
  669. return InsnStop("jump")
  670. def register_jump_to(self, label, lastinsn=None):
  671. if lastinsn is None:
  672. lastinsn = self.insns[-1]
  673. if not isinstance(lastinsn, InsnStop):
  674. self.labels[label].previous_insns.append(lastinsn)
  675. def conditional_jump(self, line, je=False, jne=False):
  676. match = self.r_jump.match(line)
  677. if not match:
  678. match = self.r_jump_rel_label.match(line)
  679. if not match:
  680. raise UnrecognizedOperation(line)
  681. # j* NNNf
  682. label = match.group(1)
  683. label += ":"
  684. i = self.currentlineno + 1
  685. while True:
  686. if self.lines[i].startswith(label):
  687. label = "rel %d" % i
  688. break
  689. i += 1
  690. else:
  691. label = match.group(1)
  692. prefix = []
  693. lastinsn = None
  694. postfix = []
  695. if self.tested_for_zero is not None:
  696. if je:
  697. # generate pseudo-code...
  698. prefix = [InsnCopyLocal(self.tested_for_zero, '%tmp'),
  699. InsnSetLocal(self.tested_for_zero)]
  700. postfix = [InsnCopyLocal('%tmp', self.tested_for_zero)]
  701. lastinsn = prefix[-1]
  702. elif jne:
  703. postfix = [InsnSetLocal(self.tested_for_zero)]
  704. self.register_jump_to(label, lastinsn)
  705. return prefix + [InsnCondJump(label)] + postfix
  706. visit_jmpl = visit_jmp
  707. visit_jg = conditional_jump
  708. visit_jge = conditional_jump
  709. visit_jl = conditional_jump
  710. visit_jle = conditional_jump
  711. visit_ja = conditional_jump
  712. visit_jae = conditional_jump
  713. visit_jb = conditional_jump
  714. visit_jbe = conditional_jump
  715. visit_jp = conditional_jump
  716. visit_jnp = conditional_jump
  717. visit_js = conditional_jump
  718. visit_jns = conditional_jump
  719. visit_jo = conditional_jump
  720. visit_jno = conditional_jump
  721. visit_jc = conditional_jump
  722. visit_jnc = conditional_jump
  723. def visit_je(self, line):
  724. return self.conditional_jump(line, je=True)
  725. def visit_jne(self, line):
  726. return self.conditional_jump(line, jne=True)
  727. def _visit_test(self, line):
  728. match = self.r_binaryinsn.match(line)
  729. source = match.group("source")
  730. target = match.group("target")
  731. if source == target:
  732. self.tested_for_zero = source
  733. return []
  734. def _visit_xchg(self, line):
  735. # only support the format used in VALGRIND_DISCARD_TRANSLATIONS
  736. # which is to use a marker no-op "xchgl %ebx, %ebx"
  737. match = self.r_binaryinsn.match(line)
  738. source = match.group("source")
  739. target = match.group("target")
  740. if source == target:
  741. return []
  742. raise UnrecognizedOperation(line)
  743. def visit_call(self, line):
  744. match = self.r_unaryinsn.match(line)
  745. if match is None:
  746. assert self.r_unaryinsn_star.match(line) # indirect call
  747. return [InsnCall('<indirect>', self.currentlineno),
  748. InsnSetLocal(self.EAX)] # the result is there
  749. target = match.group(1)
  750. if self.format in ('msvc',):
  751. # On win32, the address of a foreign function must be
  752. # computed, the optimizer may store it in a register. We
  753. # could ignore this, except when the function need special
  754. # processing (not returning, __stdcall...)
  755. def find_register(target):
  756. reg = []
  757. def walker(insn, locs):
  758. sources = []
  759. for loc in locs:
  760. for s in insn.all_sources_of(loc):
  761. sources.append(s)
  762. for source in sources:
  763. m = re.match("DWORD PTR " + self.LABEL, source)
  764. if m:
  765. reg.append(m.group(1))
  766. if reg:
  767. return
  768. yield tuple(sources)
  769. insn = InsnStop()
  770. insn.previous_insns = [self.insns[-1]]
  771. self.walk_instructions_backwards(walker, insn, (target,))
  772. return reg
  773. if match and self.r_localvarfp.match(target):
  774. sources = find_register(target)
  775. if sources:
  776. target, = sources
  777. if target.endswith('@PLT'):
  778. # In -fPIC mode, all functions calls have this suffix
  779. target = target[:-4]
  780. if target in self.FUNCTIONS_NOT_RETURNING:
  781. return [InsnStop(target)]
  782. if self.format == 'mingw32' and target == '__alloca':
  783. # in functions with large stack requirements, windows
  784. # needs a call to _alloca(), to turn reserved pages
  785. # into committed memory.
  786. # With mingw32 gcc at least, %esp is not used before
  787. # this call. So we don't bother to compute the exact
  788. # stack effect.
  789. return [InsnCannotFollowEsp()]
  790. if target in self.labels:
  791. lineoffset = self.labels[target].lineno - self.currentlineno
  792. if lineoffset >= 0:
  793. assert lineoffset in (1,2)
  794. return [InsnStackAdjust(-4)]
  795. insns = [InsnCall(target, self.currentlineno),
  796. InsnSetLocal(self.EAX)] # the result is there
  797. if self.format in ('mingw32', 'msvc'):
  798. # handle __stdcall calling convention:
  799. # Stack cleanup is performed by the called function,
  800. # Function name is decorated with "@N" where N is the stack size
  801. if '@' in target and not target.startswith('@'):
  802. insns.append(InsnStackAdjust(int(target.rsplit('@', 1)[1])))
  803. # Some (intrinsic?) functions use the "fastcall" calling convention
  804. # XXX without any declaration, how can we guess the stack effect?
  805. if target in ['__alldiv', '__allrem', '__allmul', '__alldvrm',
  806. '__aulldiv', '__aullrem', '__aullmul', '__aulldvrm']:
  807. insns.append(InsnStackAdjust(16))
  808. return insns
  809. # __________ debugging output __________
  810. @classmethod
  811. def format_location(cls, loc):
  812. # A 'location' is a single number describing where a value is stored
  813. # across a call. It can be in one of the CALLEE_SAVE_REGISTERS, or
  814. # in the stack frame at an address relative to either %esp or %ebp.
  815. # The last two bits of the location number are used to tell the cases
  816. # apart; see format_location().
  817. assert loc >= 0
  818. kind = loc & LOC_MASK
  819. if kind == LOC_REG:
  820. if loc == LOC_NOWHERE:
  821. return '?'
  822. reg = (loc >> 2) - 1
  823. return '%' + cls.CALLEE_SAVE_REGISTERS[reg].replace("%", "")
  824. else:
  825. offset = loc & ~ LOC_MASK
  826. if cls.WORD == 8:
  827. offset <<= 1
  828. if kind == LOC_EBP_PLUS:
  829. result = '(%' + cls.EBP.replace("%", "") + ')'
  830. elif kind == LOC_EBP_MINUS:
  831. result = '(%' + cls.EBP.replace("%", "") + ')'
  832. offset = -offset
  833. elif kind == LOC_ESP_PLUS:
  834. result = '(%' + cls.ESP.replace("%", "") + ')'
  835. else:
  836. assert 0, kind
  837. if offset != 0:
  838. result = str(offset) + result
  839. return result
  840. @classmethod
  841. def format_callshape(cls, shape):
  842. # A 'call shape' is a tuple of locations in the sense of
  843. # format_location(). They describe where in a function frame
  844. # interesting values are stored, when this function executes a 'call'
  845. # instruction.
  846. #
  847. # shape[0] is the location that stores the fn's own return
  848. # address (not the return address for the currently
  849. # executing 'call')
  850. #
  851. # shape[1..N] is where the fn saved its own caller's value of a
  852. # certain callee save register. (where N is the number
  853. # of callee save registers.)
  854. #
  855. # shape[>N] are GC roots: where the fn has put its local GCPTR
  856. # vars
  857. #
  858. num_callee_save_regs = len(cls.CALLEE_SAVE_REGISTERS)
  859. assert isinstance(shape, tuple)
  860. # + 1 for the return address
  861. assert len(shape) >= (num_callee_save_regs + 1)
  862. result = [cls.format_location(loc) for loc in shape]
  863. return '{%s | %s | %s}' % (result[0],
  864. ', '.join(result[1:(num_callee_save_regs+1)]),
  865. ', '.join(result[(num_callee_save_regs+1):]))
  866. class FunctionGcRootTracker32(FunctionGcRootTracker):
  867. WORD = 4
  868. visit_mov = FunctionGcRootTracker._visit_mov
  869. visit_movl = FunctionGcRootTracker._visit_mov
  870. visit_pushl = FunctionGcRootTracker._visit_push
  871. visit_leal = FunctionGcRootTracker._visit_lea
  872. visit_addl = FunctionGcRootTracker._visit_add
  873. visit_subl = FunctionGcRootTracker._visit_sub
  874. visit_andl = FunctionGcRootTracker._visit_and
  875. visit_and = FunctionGcRootTracker._visit_and
  876. visit_xchgl = FunctionGcRootTracker._visit_xchg
  877. visit_testl = FunctionGcRootTracker._visit_test
  878. # used in "xor reg, reg" to create a NULL GC ptr
  879. visit_xorl = FunctionGcRootTracker.binary_insn
  880. visit_orl = FunctionGcRootTracker.binary_insn # unsure about this one
  881. # occasionally used on 32-bits to move floats around
  882. visit_movq = FunctionGcRootTracker.visit_nop
  883. def visit_pushw(self, line):
  884. return [InsnStackAdjust(-2)] # rare but not impossible
  885. def visit_popl(self, line):
  886. match = self.r_unaryinsn.match(line)
  887. target = match.group(1)
  888. return self._visit_pop(target)
  889. class FunctionGcRootTracker64(FunctionGcRootTracker):
  890. WORD = 8
  891. # Regex ignores destination
  892. r_save_xmm_register = re.compile(r"\tmovaps\s+%xmm(\d+)")
  893. def _maybe_32bit_dest(func):
  894. def wrapper(self, line):
  895. # Using a 32-bit reg as a destination in 64-bit mode zero-extends
  896. # to 64-bits, so sometimes gcc uses a 32-bit operation to copy a
  897. # statically known pointer to a register
  898. # %eax -> %rax
  899. new_line = re.sub(r"%e(ax|bx|cx|dx|di|si|bp)$", r"%r\1", line)
  900. # %r10d -> %r10
  901. new_line = re.sub(r"%r(\d+)d$", r"%r\1", new_line)
  902. return func(self, new_line)
  903. return wrapper
  904. visit_addl = FunctionGcRootTracker.visit_nop
  905. visit_subl = FunctionGcRootTracker.visit_nop
  906. visit_leal = FunctionGcRootTracker.visit_nop
  907. visit_cltq = FunctionGcRootTracker.visit_nop
  908. visit_movq = FunctionGcRootTracker._visit_mov
  909. # just a special assembler mnemonic for mov
  910. visit_movabsq = FunctionGcRootTracker._visit_mov
  911. visit_mov = _maybe_32bit_dest(FunctionGcRootTracker._visit_mov)
  912. visit_movl = visit_mov
  913. visit_xorl = _maybe_32bit_dest(FunctionGcRootTracker.binary_insn)
  914. visit_pushq = FunctionGcRootTracker._visit_push
  915. visit_addq = FunctionGcRootTracker._visit_add
  916. visit_subq = FunctionGcRootTracker._visit_sub
  917. visit_leaq = FunctionGcRootTracker._visit_lea
  918. visit_xorq = FunctionGcRootTracker.binary_insn
  919. visit_xchgq = FunctionGcRootTracker._visit_xchg
  920. visit_testq = FunctionGcRootTracker._visit_test
  921. # FIXME: similar to visit_popl for 32-bit
  922. def visit_popq(self, line):
  923. match = self.r_unaryinsn.match(line)
  924. target = match.group(1)
  925. return self._visit_pop(target)
  926. def visit_jmp(self, line):
  927. # On 64-bit, %al is used when calling varargs functions to specify an
  928. # upper-bound on the number of xmm registers used in the call. gcc
  929. # uses %al to compute an indirect jump that looks like:
  930. #
  931. # jmp *[some register]
  932. # movaps %xmm7, [stack location]
  933. # movaps %xmm6, [stack location]
  934. # movaps %xmm5, [stack location]
  935. # movaps %xmm4, [stack location]
  936. # movaps %xmm3, [stack location]
  937. # movaps %xmm2, [stack location]
  938. # movaps %xmm1, [stack location]
  939. # movaps %xmm0, [stack location]
  940. #
  941. # The jmp is always to somewhere in the block of "movaps"
  942. # instructions, according to how many xmm registers need to be saved
  943. # to the stack. The point of all this is that we can safely ignore
  944. # jmp instructions of that form.
  945. if (self.currentlineno + 8) < len(self.lines) and self.r_unaryinsn_star.match(line):
  946. matches = [self.r_save_xmm_register.match(self.lines[self.currentlineno + 1 + i]) for i in range(8)]
  947. if all(m and int(m.group(1)) == (7 - i) for i, m in enumerate(matches)):
  948. return []
  949. return FunctionGcRootTracker.visit_jmp(self, line)
  950. class ElfFunctionGcRootTracker32(FunctionGcRootTracker32):
  951. format = 'elf'
  952. function_names_prefix = ''
  953. ESP = '%esp'
  954. EBP = '%ebp'
  955. EAX = '%eax'
  956. CALLEE_SAVE_REGISTERS = ['%ebx', '%esi', '%edi', '%ebp']
  957. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  958. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  959. OPERAND = r'(?:[-\w$%+.:@"]+(?:[(][\w%,]+[)])?|[(][\w%,]+[)])'
  960. LABEL = r'([a-zA-Z_$.][a-zA-Z0-9_$@.]*)'
  961. OFFSET_LABELS = 2**30
  962. TOP_OF_STACK_MINUS_WORD = '-4(%esp)'
  963. r_functionstart = re.compile(r"\t.type\s+"+LABEL+",\s*[@]function\s*$")
  964. r_functionend = re.compile(r"\t.size\s+"+LABEL+",\s*[.]-"+LABEL+"\s*$")
  965. LOCALVAR = r"%eax|%edx|%ecx|%ebx|%esi|%edi|%ebp|-?\d*[(]%esp[)]"
  966. LOCALVARFP = LOCALVAR + r"|-?\d*[(]%ebp[)]"
  967. r_localvarnofp = re.compile(LOCALVAR)
  968. r_localvarfp = re.compile(LOCALVARFP)
  969. r_localvar_esp = re.compile(r"(-?\d*)[(]%esp[)]")
  970. r_localvar_ebp = re.compile(r"(-?\d*)[(]%ebp[)]")
  971. r_rel_label = re.compile(r"(\d+):\s*$")
  972. r_jump_rel_label = re.compile(r"\tj\w+\s+"+"(\d+)f"+"\s*$")
  973. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+[*]("+OPERAND+")\s*$")
  974. r_jmptable_item = re.compile(r"\t.long\t"+LABEL+"(-\"[A-Za-z0-9$]+\")?\s*$")
  975. r_jmptable_end = re.compile(r"\t.text|\t.section\s+.text|\t\.align|"+LABEL)
  976. r_gcroot_marker = re.compile(r"\t/[*] GCROOT ("+LOCALVARFP+") [*]/")
  977. r_gcnocollect_marker = re.compile(r"\t/[*] GC_NOCOLLECT ("+OPERAND+") [*]/")
  978. r_bottom_marker = re.compile(r"\t/[*] GC_STACK_BOTTOM [*]/")
  979. FUNCTIONS_NOT_RETURNING = {
  980. '_exit': None,
  981. '__assert_fail': None,
  982. '___assert_rtn': None,
  983. 'L___assert_rtn$stub': None,
  984. 'L___eprintf$stub': None,
  985. }
  986. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  987. FUNCTIONS_NOT_RETURNING[_name] = None
  988. def __init__(self, lines, filetag=0):
  989. match = self.r_functionstart.match(lines[0])
  990. funcname = match.group(1)
  991. match = self.r_functionend.match(lines[-1])
  992. assert funcname == match.group(1)
  993. assert funcname == match.group(2)
  994. super(ElfFunctionGcRootTracker32, self).__init__(
  995. funcname, lines, filetag)
  996. def extract_immediate(self, value):
  997. if not value.startswith('$'):
  998. return None
  999. return int(value[1:])
  1000. ElfFunctionGcRootTracker32.init_regexp()
  1001. class ElfFunctionGcRootTracker64(FunctionGcRootTracker64):
  1002. format = 'elf64'
  1003. function_names_prefix = ''
  1004. ESP = '%rsp'
  1005. EBP = '%rbp'
  1006. EAX = '%rax'
  1007. CALLEE_SAVE_REGISTERS = ['%rbx', '%r12', '%r13', '%r14', '%r15', '%rbp']
  1008. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  1009. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  1010. OPERAND = r'(?:[-\w$%+.:@"]+(?:[(][\w%,]+[)])?|[(][\w%,]+[)])'
  1011. LABEL = r'([a-zA-Z_$.][a-zA-Z0-9_$@.]*)'
  1012. OFFSET_LABELS = 2**30
  1013. TOP_OF_STACK_MINUS_WORD = '-8(%rsp)'
  1014. r_functionstart = re.compile(r"\t.type\s+"+LABEL+",\s*[@]function\s*$")
  1015. r_functionend = re.compile(r"\t.size\s+"+LABEL+",\s*[.]-"+LABEL+"\s*$")
  1016. LOCALVAR = r"%rax|%rbx|%rcx|%rdx|%rdi|%rsi|%rbp|%r8|%r9|%r10|%r11|%r12|%r13|%r14|%r15|-?\d*[(]%rsp[)]"
  1017. LOCALVARFP = LOCALVAR + r"|-?\d*[(]%rbp[)]"
  1018. r_localvarnofp = re.compile(LOCALVAR)
  1019. r_localvarfp = re.compile(LOCALVARFP)
  1020. r_localvar_esp = re.compile(r"(-?\d*)[(]%rsp[)]")
  1021. r_localvar_ebp = re.compile(r"(-?\d*)[(]%rbp[)]")
  1022. r_rel_label = re.compile(r"(\d+):\s*$")
  1023. r_jump_rel_label = re.compile(r"\tj\w+\s+"+"(\d+)f"+"\s*$")
  1024. r_unaryinsn_star= re.compile(r"\t[a-z]\w*\s+[*]("+OPERAND+")\s*$")
  1025. r_jmptable_item = re.compile(r"\t.(?:quad|long)\t"+LABEL+"(-\"[A-Za-z0-9$]+\"|-"+LABEL+")?\s*$")
  1026. r_jmptable_end = re.compile(r"\t.text|\t.section\s+.text|\t\.align|"+LABEL)
  1027. r_gcroot_marker = re.compile(r"\t/[*] GCROOT ("+LOCALVARFP+") [*]/")
  1028. r_gcnocollect_marker = re.compile(r"\t/[*] GC_NOCOLLECT ("+OPERAND+") [*]/")
  1029. r_bottom_marker = re.compile(r"\t/[*] GC_STACK_BOTTOM [*]/")
  1030. FUNCTIONS_NOT_RETURNING = {
  1031. '_exit': None,
  1032. '__assert_fail': None,
  1033. '___assert_rtn': None,
  1034. 'L___assert_rtn$stub': None,
  1035. 'L___eprintf$stub': None,
  1036. }
  1037. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1038. FUNCTIONS_NOT_RETURNING[_name] = None
  1039. def __init__(self, lines, filetag=0):
  1040. match = self.r_functionstart.match(lines[0])
  1041. funcname = match.group(1)
  1042. match = self.r_functionend.match(lines[-1])
  1043. assert funcname == match.group(1)
  1044. assert funcname == match.group(2)
  1045. super(ElfFunctionGcRootTracker64, self).__init__(
  1046. funcname, lines, filetag)
  1047. def extract_immediate(self, value):
  1048. if not value.startswith('$'):
  1049. return None
  1050. return int(value[1:])
  1051. ElfFunctionGcRootTracker64.init_regexp()
  1052. class DarwinFunctionGcRootTracker32(ElfFunctionGcRootTracker32):
  1053. format = 'darwin'
  1054. function_names_prefix = '_'
  1055. r_functionstart = re.compile(r"_(\w+):\s*$")
  1056. OFFSET_LABELS = 0
  1057. def __init__(self, lines, filetag=0):
  1058. match = self.r_functionstart.match(lines[0])
  1059. funcname = '_' + match.group(1)
  1060. FunctionGcRootTracker32.__init__(self, funcname, lines, filetag)
  1061. class DarwinFunctionGcRootTracker64(ElfFunctionGcRootTracker64):
  1062. format = 'darwin64'
  1063. function_names_prefix = '_'
  1064. LABEL = ElfFunctionGcRootTracker64.LABEL
  1065. r_jmptable_item = re.compile(r"\t.(?:long|quad)\t"+LABEL+"(-\"?[A-Za-z0-9$]+\"?)?\s*$")
  1066. r_functionstart = re.compile(r"_(\w+):\s*$")
  1067. OFFSET_LABELS = 0
  1068. def __init__(self, lines, filetag=0):
  1069. match = self.r_functionstart.match(lines[0])
  1070. funcname = '_' + match.group(1)
  1071. FunctionGcRootTracker64.__init__(self, funcname, lines, filetag)
  1072. class Mingw32FunctionGcRootTracker(DarwinFunctionGcRootTracker32):
  1073. format = 'mingw32'
  1074. function_names_prefix = '_'
  1075. FUNCTIONS_NOT_RETURNING = {
  1076. '_exit': None,
  1077. '__assert': None,
  1078. }
  1079. for _name in FunctionGcRootTracker.BASE_FUNCTIONS_NOT_RETURNING:
  1080. FUNCTIONS_NOT_RETURNING['_' + _name] = None
  1081. class MsvcFunctionGcRootTracker(FunctionGcRootTracker32):
  1082. format = 'msvc'
  1083. function_names_prefix = '_'
  1084. ESP = 'esp'
  1085. EBP = 'ebp'
  1086. EAX = 'eax'
  1087. CALLEE_SAVE_REGISTERS = ['ebx', 'esi', 'edi', 'ebp']
  1088. REG2LOC = dict((_reg, LOC_REG | ((_i+1)<<2))
  1089. for _i, _reg in enumerate(CALLEE_SAVE_REGISTERS))
  1090. TOP_OF_STACK_MINUS_WORD = 'DWORD PTR [esp-4]'
  1091. OPERAND = r'(?:(:?WORD|DWORD|BYTE) PTR |OFFSET )?[_\w?:@$]*(?:[-+0-9]+)?(:?\[[-+*\w0-9]+\])?'
  1092. LABEL = r'([a-zA-Z_$@.][a-zA-Z0-9_$@.]*)'
  1093. OFFS

Large files files are truncated, but you can click here to view the full file