test_printers_common.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. # Common functions and variables for testing the Python pretty printers.
  2. #
  3. # Copyright (C) 2016-2019 Free Software Foundation, Inc.
  4. # This file is part of the GNU C Library.
  5. #
  6. # The GNU C Library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # The GNU C Library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with the GNU C Library; if not, see
  18. # <http://www.gnu.org/licenses/>.
  19. """These tests require PExpect 4.0 or newer.
  20. Exported constants:
  21. PASS, FAIL, UNSUPPORTED (int): Test exit codes, as per evaluate-test.sh.
  22. """
  23. import os
  24. import re
  25. from test_printers_exceptions import *
  26. PASS = 0
  27. FAIL = 1
  28. UNSUPPORTED = 77
  29. gdb_bin = 'gdb'
  30. gdb_options = '-q -nx'
  31. gdb_invocation = '{0} {1}'.format(gdb_bin, gdb_options)
  32. pexpect_min_version = 4
  33. gdb_min_version = (7, 8)
  34. encoding = 'utf-8'
  35. try:
  36. import pexpect
  37. except ImportError:
  38. print('PExpect 4.0 or newer must be installed to test the pretty printers.')
  39. exit(UNSUPPORTED)
  40. pexpect_version = pexpect.__version__.split('.')[0]
  41. if int(pexpect_version) < pexpect_min_version:
  42. print('PExpect 4.0 or newer must be installed to test the pretty printers.')
  43. exit(UNSUPPORTED)
  44. if not pexpect.which(gdb_bin):
  45. print('gdb 7.8 or newer must be installed to test the pretty printers.')
  46. exit(UNSUPPORTED)
  47. timeout = 5
  48. TIMEOUTFACTOR = os.environ.get('TIMEOUTFACTOR')
  49. if TIMEOUTFACTOR:
  50. timeout = int(TIMEOUTFACTOR)
  51. try:
  52. # Check the gdb version.
  53. version_cmd = '{0} --version'.format(gdb_invocation, timeout=timeout)
  54. gdb_version_out = pexpect.run(version_cmd, encoding=encoding)
  55. # The gdb version string is "GNU gdb <PKGVERSION><version>", where
  56. # PKGVERSION can be any text. We assume that there'll always be a space
  57. # between PKGVERSION and the version number for the sake of the regexp.
  58. version_match = re.search(r'GNU gdb .* ([1-9]+)\.([0-9]+)', gdb_version_out)
  59. if not version_match:
  60. print('The gdb version string (gdb -v) is incorrectly formatted.')
  61. exit(UNSUPPORTED)
  62. gdb_version = (int(version_match.group(1)), int(version_match.group(2)))
  63. if gdb_version < gdb_min_version:
  64. print('gdb 7.8 or newer must be installed to test the pretty printers.')
  65. exit(UNSUPPORTED)
  66. # Check if gdb supports Python.
  67. gdb_python_cmd = '{0} -ex "python import os" -batch'.format(gdb_invocation,
  68. timeout=timeout)
  69. gdb_python_error = pexpect.run(gdb_python_cmd, encoding=encoding)
  70. if gdb_python_error:
  71. print('gdb must have python support to test the pretty printers.')
  72. print('gdb output: {!r}'.format(gdb_python_error))
  73. exit(UNSUPPORTED)
  74. # If everything's ok, spawn the gdb process we'll use for testing.
  75. gdb = pexpect.spawn(gdb_invocation, echo=False, timeout=timeout,
  76. encoding=encoding)
  77. gdb_prompt = u'\(gdb\)'
  78. gdb.expect(gdb_prompt)
  79. except pexpect.ExceptionPexpect as exception:
  80. print('Error: {0}'.format(exception))
  81. exit(FAIL)
  82. def test(command, pattern=None):
  83. """Sends 'command' to gdb and expects the given 'pattern'.
  84. If 'pattern' is None, simply consumes everything up to and including
  85. the gdb prompt.
  86. Args:
  87. command (string): The command we'll send to gdb.
  88. pattern (raw string): A pattern the gdb output should match.
  89. Returns:
  90. string: The string that matched 'pattern', or an empty string if
  91. 'pattern' was None.
  92. """
  93. match = ''
  94. gdb.sendline(command)
  95. if pattern:
  96. # PExpect does a non-greedy match for '+' and '*'. Since it can't look
  97. # ahead on the gdb output stream, if 'pattern' ends with a '+' or a '*'
  98. # we may end up matching only part of the required output.
  99. # To avoid this, we'll consume 'pattern' and anything that follows it
  100. # up to and including the gdb prompt, then extract 'pattern' later.
  101. index = gdb.expect([u'{0}.+{1}'.format(pattern, gdb_prompt),
  102. pexpect.TIMEOUT])
  103. if index == 0:
  104. # gdb.after now contains the whole match. Extract the text that
  105. # matches 'pattern'.
  106. match = re.match(pattern, gdb.after, re.DOTALL).group()
  107. elif index == 1:
  108. # We got a timeout exception. Print information on what caused it
  109. # and bail out.
  110. error = ('Response does not match the expected pattern.\n'
  111. 'Command: {0}\n'
  112. 'Expected pattern: {1}\n'
  113. 'Response: {2}'.format(command, pattern, gdb.before))
  114. raise pexpect.TIMEOUT(error)
  115. else:
  116. # Consume just the the gdb prompt.
  117. gdb.expect(gdb_prompt)
  118. return match
  119. def init_test(test_bin, printer_files, printer_names):
  120. """Loads the test binary file and the required pretty printers to gdb.
  121. Args:
  122. test_bin (string): The name of the test binary file.
  123. pretty_printers (list of strings): A list with the names of the pretty
  124. printer files.
  125. """
  126. # Load all the pretty printer files. We're assuming these are safe.
  127. for printer_file in printer_files:
  128. test('source {0}'.format(printer_file))
  129. # Disable all the pretty printers.
  130. test('disable pretty-printer', r'0 of [0-9]+ printers enabled')
  131. # Enable only the required printers.
  132. for printer in printer_names:
  133. test('enable pretty-printer {0}'.format(printer),
  134. r'[1-9][0-9]* of [1-9]+ printers enabled')
  135. # Finally, load the test binary.
  136. test('file {0}'.format(test_bin))
  137. # Disable lock elision.
  138. test('set environment GLIBC_TUNABLES glibc.elision.enable=0')
  139. def go_to_main():
  140. """Executes a gdb 'start' command, which takes us to main."""
  141. test('start', r'main')
  142. def get_line_number(file_name, string):
  143. """Returns the number of the line in which 'string' appears within a file.
  144. Args:
  145. file_name (string): The name of the file we'll search through.
  146. string (string): The string we'll look for.
  147. Returns:
  148. int: The number of the line in which 'string' appears, starting from 1.
  149. """
  150. number = -1
  151. with open(file_name) as src_file:
  152. for i, line in enumerate(src_file):
  153. if string in line:
  154. number = i + 1
  155. break
  156. if number == -1:
  157. raise NoLineError(file_name, string)
  158. return number
  159. def break_at(file_name, string, temporary=True, thread=None):
  160. """Places a breakpoint on the first line in 'file_name' containing 'string'.
  161. 'string' is usually a comment like "Stop here". Notice this may fail unless
  162. the comment is placed inline next to actual code, e.g.:
  163. ...
  164. /* Stop here */
  165. ...
  166. may fail, while:
  167. ...
  168. some_func(); /* Stop here */
  169. ...
  170. will succeed.
  171. If 'thread' isn't None, the breakpoint will be set for all the threads.
  172. Otherwise, it'll be set only for 'thread'.
  173. Args:
  174. file_name (string): The name of the file we'll place the breakpoint in.
  175. string (string): A string we'll look for inside the file.
  176. We'll place a breakpoint on the line which contains it.
  177. temporary (bool): Whether the breakpoint should be automatically deleted
  178. after we reach it.
  179. thread (int): The number of the thread we'll place the breakpoint for,
  180. as seen by gdb. If specified, it should be greater than zero.
  181. """
  182. if not thread:
  183. thread_str = ''
  184. else:
  185. thread_str = 'thread {0}'.format(thread)
  186. if temporary:
  187. command = 'tbreak'
  188. break_type = 'Temporary breakpoint'
  189. else:
  190. command = 'break'
  191. break_type = 'Breakpoint'
  192. line_number = str(get_line_number(file_name, string))
  193. test('{0} {1}:{2} {3}'.format(command, file_name, line_number, thread_str),
  194. r'{0} [0-9]+ at 0x[a-f0-9]+: file {1}, line {2}\.'.format(break_type,
  195. file_name,
  196. line_number))
  197. def continue_cmd(thread=None):
  198. """Executes a gdb 'continue' command.
  199. If 'thread' isn't None, the command will be applied to all the threads.
  200. Otherwise, it'll be applied only to 'thread'.
  201. Args:
  202. thread (int): The number of the thread we'll apply the command to,
  203. as seen by gdb. If specified, it should be greater than zero.
  204. """
  205. if not thread:
  206. command = 'continue'
  207. else:
  208. command = 'thread apply {0} continue'.format(thread)
  209. test(command)
  210. def next_cmd(count=1, thread=None):
  211. """Executes a gdb 'next' command.
  212. If 'thread' isn't None, the command will be applied to all the threads.
  213. Otherwise, it'll be applied only to 'thread'.
  214. Args:
  215. count (int): The 'count' argument of the 'next' command.
  216. thread (int): The number of the thread we'll apply the command to,
  217. as seen by gdb. If specified, it should be greater than zero.
  218. """
  219. if not thread:
  220. command = 'next'
  221. else:
  222. command = 'thread apply {0} next'
  223. test('{0} {1}'.format(command, count))
  224. def select_thread(thread):
  225. """Selects the thread indicated by 'thread'.
  226. Args:
  227. thread (int): The number of the thread we'll switch to, as seen by gdb.
  228. This should be greater than zero.
  229. """
  230. if thread > 0:
  231. test('thread {0}'.format(thread))
  232. def get_current_thread_lwpid():
  233. """Gets the current thread's Lightweight Process ID.
  234. Returns:
  235. string: The current thread's LWP ID.
  236. """
  237. # It's easier to get the LWP ID through the Python API than the gdb CLI.
  238. command = 'python print(gdb.selected_thread().ptid[1])'
  239. return test(command, r'[0-9]+')
  240. def set_scheduler_locking(mode):
  241. """Executes the gdb 'set scheduler-locking' command.
  242. Args:
  243. mode (bool): Whether the scheduler locking mode should be 'on'.
  244. """
  245. modes = {
  246. True: 'on',
  247. False: 'off'
  248. }
  249. test('set scheduler-locking {0}'.format(modes[mode]))
  250. def test_printer(var, to_string, children=None, is_ptr=True):
  251. """ Tests the output of a pretty printer.
  252. For a variable called 'var', this tests whether its associated printer
  253. outputs the expected 'to_string' and children (if any).
  254. Args:
  255. var (string): The name of the variable we'll print.
  256. to_string (raw string): The expected output of the printer's 'to_string'
  257. method.
  258. children (map {raw string->raw string}): A map with the expected output
  259. of the printer's children' method.
  260. is_ptr (bool): Whether 'var' is a pointer, and thus should be
  261. dereferenced.
  262. """
  263. if is_ptr:
  264. var = '*{0}'.format(var)
  265. test('print {0}'.format(var), to_string)
  266. if children:
  267. for name, value in children.items():
  268. # Children are shown as 'name = value'.
  269. test('print {0}'.format(var), r'{0} = {1}'.format(name, value))
  270. def check_debug_symbol(symbol):
  271. """ Tests whether a given debugging symbol exists.
  272. If the symbol doesn't exist, raises a DebugError.
  273. Args:
  274. symbol (string): The symbol we're going to check for.
  275. """
  276. try:
  277. test('ptype {0}'.format(symbol), r'type = {0}'.format(symbol))
  278. except pexpect.TIMEOUT:
  279. # The symbol doesn't exist.
  280. raise DebugError(symbol)