gdb.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #
  2. # Copyright 2021 Espressif Systems (Shanghai) CO., 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 pygdbmi.gdbcontroller import DEFAULT_GDB_TIMEOUT_SEC, GdbController
  20. from . import ESPCoreDumpError
  21. class EspGDB(object):
  22. def __init__(self, gdb_path, gdb_cmds, core_filename, prog_filename, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC):
  23. """
  24. Start GDB and initialize a GdbController instance
  25. """
  26. gdb_args = ['--quiet', # inhibit dumping info at start-up
  27. '--nx', # inhibit window interface
  28. '--nw', # ignore .gdbinit
  29. '--interpreter=mi2', # use GDB/MI v2
  30. '--core=%s' % core_filename] # core file
  31. for c in gdb_cmds:
  32. if c:
  33. gdb_args += ['-ex', c]
  34. gdb_args.append(prog_filename)
  35. self.p = GdbController(gdb_path=gdb_path, gdb_args=gdb_args)
  36. self.timeout = timeout_sec
  37. # Consume initial output by issuing a dummy command
  38. self._gdbmi_run_cmd_get_responses(cmd='-data-list-register-values x pc',
  39. resp_message=None, resp_type='console', multiple=True,
  40. done_message='done', done_type='result')
  41. def __del__(self):
  42. try:
  43. self.p.exit()
  44. except IndexError:
  45. logging.warning('Attempt to terminate the GDB process failed, because it is already terminated. Skip')
  46. def _gdbmi_run_cmd_get_responses(self, cmd, resp_message, resp_type, multiple=True,
  47. done_message=None, done_type=None):
  48. self.p.write(cmd, read_response=False)
  49. t_end = time.time() + self.timeout
  50. filtered_response_list = []
  51. all_responses = []
  52. while time.time() < t_end:
  53. more_responses = self.p.get_gdb_response(timeout_sec=0, raise_error_on_timeout=False)
  54. filtered_response_list += filter(lambda rsp: rsp['message'] == resp_message and rsp['type'] == resp_type,
  55. more_responses)
  56. all_responses += more_responses
  57. if filtered_response_list and not multiple:
  58. break
  59. if done_message and done_type and self._gdbmi_filter_responses(more_responses, done_message, done_type):
  60. break
  61. if not filtered_response_list and not multiple:
  62. raise ESPCoreDumpError("Couldn't find response with message '{}', type '{}' in responses '{}'".format(
  63. resp_message, resp_type, str(all_responses)
  64. ))
  65. return filtered_response_list
  66. def _gdbmi_run_cmd_get_one_response(self, cmd, resp_message, resp_type):
  67. return self._gdbmi_run_cmd_get_responses(cmd, resp_message, resp_type, multiple=False)[0]
  68. def _gdbmi_data_evaluate_expression(self, expr):
  69. """ Get the value of an expression, similar to the 'print' command """
  70. return self._gdbmi_run_cmd_get_one_response("-data-evaluate-expression \"%s\"" % expr,
  71. 'done', 'result')['payload']['value']
  72. def get_freertos_task_name(self, tcb_addr):
  73. """ Get FreeRTOS task name given the TCB address """
  74. try:
  75. val = self._gdbmi_data_evaluate_expression('(char*)((TCB_t *)0x%x)->pcTaskName' % tcb_addr)
  76. except (ESPCoreDumpError, KeyError):
  77. # KeyError is raised when "value" is not in "payload"
  78. return ''
  79. # Value is of form '0x12345678 "task_name"', extract the actual name
  80. result = re.search(r"\"([^']*)\"$", val)
  81. if result:
  82. return result.group(1)
  83. return ''
  84. def run_cmd(self, gdb_cmd):
  85. """ Execute a generic GDB console command via MI2
  86. """
  87. filtered_responses = self._gdbmi_run_cmd_get_responses(cmd="-interpreter-exec console \"%s\"" % gdb_cmd,
  88. resp_message=None, resp_type='console', multiple=True,
  89. done_message='done', done_type='result')
  90. return ''.join([x['payload'] for x in filtered_responses]) \
  91. .replace('\\n', '\n') \
  92. .replace('\\t', '\t') \
  93. .rstrip('\n')
  94. def get_thread_info(self):
  95. """ Get information about all threads known to GDB, and the current thread ID """
  96. result = self._gdbmi_run_cmd_get_one_response('-thread-info', 'done', 'result')['payload']
  97. current_thread_id = result['current-thread-id']
  98. threads = result['threads']
  99. return threads, current_thread_id
  100. def switch_thread(self, thr_id):
  101. """ Tell GDB to switch to a specific thread, given its ID """
  102. self._gdbmi_run_cmd_get_one_response('-thread-select %s' % thr_id, 'done', 'result')
  103. @staticmethod
  104. def _gdbmi_filter_responses(responses, resp_message, resp_type):
  105. return list(filter(lambda rsp: rsp['message'] == resp_message and rsp['type'] == resp_type, responses))
  106. @staticmethod
  107. def gdb2freertos_thread_id(gdb_target_id):
  108. """ Convert GDB 'target ID' to the FreeRTOS TCB address """
  109. return int(gdb_target_id.replace('process ', ''), 0)