gdb.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. #
  2. # Copyright 2021 Espressif Systems (Shanghai) PTE LTD
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import re
  18. import time
  19. from . import ESPCoreDumpError
  20. try:
  21. import typing
  22. except ImportError:
  23. pass
  24. from pygdbmi.gdbcontroller import DEFAULT_GDB_TIMEOUT_SEC, GdbController
  25. class EspGDB(object):
  26. def __init__(self, gdb_path, gdb_cmds, core_filename, prog_filename, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC):
  27. # type: (str, typing.List[str], str, str, int) -> None
  28. """
  29. Start GDB and initialize a GdbController instance
  30. """
  31. gdb_args = ['--quiet', # inhibit dumping info at start-up
  32. '--nx', # inhibit window interface
  33. '--nw', # ignore .gdbinit
  34. '--interpreter=mi2', # use GDB/MI v2
  35. '--core=%s' % core_filename] # core file
  36. for c in gdb_cmds:
  37. if c:
  38. gdb_args += ['-ex', c]
  39. gdb_args.append(prog_filename)
  40. self.p = GdbController(gdb_path=gdb_path, gdb_args=gdb_args)
  41. self.timeout = timeout_sec
  42. # Consume initial output by issuing a dummy command
  43. self._gdbmi_run_cmd_get_responses(cmd='-data-list-register-values x pc',
  44. resp_message=None, resp_type='console', multiple=True,
  45. done_message='done', done_type='result')
  46. def __del__(self):
  47. try:
  48. self.p.exit()
  49. except IndexError:
  50. logging.warning('Attempt to terminate the GDB process failed, because it is already terminated. Skip')
  51. def _gdbmi_run_cmd_get_responses(self, cmd, resp_message, resp_type, multiple=True,
  52. done_message=None, done_type=None):
  53. # type: (str, typing.Optional[str], str, bool, typing.Optional[str], typing.Optional[str]) -> list
  54. self.p.write(cmd, read_response=False)
  55. t_end = time.time() + self.timeout
  56. filtered_response_list = []
  57. all_responses = []
  58. while time.time() < t_end:
  59. more_responses = self.p.get_gdb_response(timeout_sec=0, raise_error_on_timeout=False)
  60. filtered_response_list += filter(lambda rsp: rsp['message'] == resp_message and rsp['type'] == resp_type,
  61. more_responses)
  62. all_responses += more_responses
  63. if filtered_response_list and not multiple:
  64. break
  65. if done_message and done_type and self._gdbmi_filter_responses(more_responses, done_message, done_type):
  66. break
  67. if not filtered_response_list and not multiple:
  68. raise ESPCoreDumpError("Couldn't find response with message '{}', type '{}' in responses '{}'".format(
  69. resp_message, resp_type, str(all_responses)
  70. ))
  71. return filtered_response_list
  72. def _gdbmi_run_cmd_get_one_response(self, cmd, resp_message, resp_type):
  73. # type: ( str, typing.Optional[str], str) -> dict
  74. return self._gdbmi_run_cmd_get_responses(cmd, resp_message, resp_type, multiple=False)[0]
  75. def _gdbmi_data_evaluate_expression(self, expr): # type: (str) -> str
  76. """ Get the value of an expression, similar to the 'print' command """
  77. return self._gdbmi_run_cmd_get_one_response("-data-evaluate-expression \"%s\"" % expr,
  78. 'done', 'result')['payload']['value']
  79. def get_freertos_task_name(self, tcb_addr): # type: (int) -> str
  80. """ Get FreeRTOS task name given the TCB address """
  81. try:
  82. val = self._gdbmi_data_evaluate_expression('(char*)((TCB_t *)0x%x)->pcTaskName' % tcb_addr)
  83. except (ESPCoreDumpError, KeyError):
  84. # KeyError is raised when "value" is not in "payload"
  85. return ''
  86. # Value is of form '0x12345678 "task_name"', extract the actual name
  87. result = re.search(r"\"([^']*)\"$", val)
  88. if result:
  89. return result.group(1)
  90. return ''
  91. def run_cmd(self, gdb_cmd): # type: (str) -> str
  92. """ Execute a generic GDB console command via MI2
  93. """
  94. filtered_responses = self._gdbmi_run_cmd_get_responses(cmd="-interpreter-exec console \"%s\"" % gdb_cmd,
  95. resp_message=None, resp_type='console', multiple=True,
  96. done_message='done', done_type='result')
  97. return ''.join([x['payload'] for x in filtered_responses]) \
  98. .replace('\\n', '\n') \
  99. .replace('\\t', '\t') \
  100. .rstrip('\n')
  101. def get_thread_info(self): # type: () -> (typing.List[dict], str)
  102. """ Get information about all threads known to GDB, and the current thread ID """
  103. result = self._gdbmi_run_cmd_get_one_response('-thread-info', 'done', 'result')['payload']
  104. current_thread_id = result['current-thread-id']
  105. threads = result['threads']
  106. return threads, current_thread_id
  107. def switch_thread(self, thr_id): # type: (int) -> None
  108. """ Tell GDB to switch to a specific thread, given its ID """
  109. self._gdbmi_run_cmd_get_one_response('-thread-select %s' % thr_id, 'done', 'result')
  110. @staticmethod
  111. def _gdbmi_filter_responses(responses, resp_message, resp_type):
  112. return list(filter(lambda rsp: rsp['message'] == resp_message and rsp['type'] == resp_type, responses))
  113. @staticmethod
  114. def gdb2freertos_thread_id(gdb_target_id): # type: (str) -> int
  115. """ Convert GDB 'target ID' to the FreeRTOS TCB address """
  116. return int(gdb_target_id.replace('process ', ''), 0)