debug_ext.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. # SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import json
  4. import os
  5. import re
  6. import shlex
  7. import shutil
  8. import subprocess
  9. import sys
  10. import threading
  11. import time
  12. from base64 import b64decode
  13. from textwrap import indent
  14. from threading import Thread
  15. from typing import Any, Dict, List, Optional
  16. from click import INT
  17. from click.core import Context
  18. from esp_coredump import CoreDump
  19. from idf_py_actions.constants import OPENOCD_TAGET_CONFIG, OPENOCD_TAGET_CONFIG_DEFAULT
  20. from idf_py_actions.errors import FatalError
  21. from idf_py_actions.serial_ext import BAUD_RATE, PORT
  22. from idf_py_actions.tools import (PropertyDict, ensure_build_directory, generate_hints, get_default_serial_port,
  23. get_sdkconfig_value, yellow_print)
  24. PYTHON = sys.executable
  25. ESP_ROM_INFO_FILE = 'roms.json'
  26. GDBINIT_PYTHON_TEMPLATE = '''
  27. # Add Python GDB extensions
  28. python
  29. import sys
  30. sys.path = {sys_path}
  31. import freertos_gdb
  32. end
  33. '''
  34. GDBINIT_PYTHON_NOT_SUPPORTED = '''
  35. # Python scripting is not supported in this copy of GDB.
  36. # Please make sure that your Python distribution contains Python shared library.
  37. '''
  38. GDBINIT_BOOTLOADER_ADD_SYMBOLS = '''
  39. # Load bootloader symbols
  40. set confirm off
  41. add-symbol-file {boot_elf}
  42. set confirm on
  43. '''
  44. GDBINIT_BOOTLOADER_NOT_FOUND = '''
  45. # Bootloader elf was not found
  46. '''
  47. GDBINIT_APP_ADD_SYMBOLS = '''
  48. # Load application file
  49. file {app_elf}
  50. '''
  51. GDBINIT_CONNECT = '''
  52. # Connect to the default openocd-esp port and break on app_main()
  53. target remote :3333
  54. monitor reset halt
  55. flushregs
  56. thbreak app_main
  57. continue
  58. '''
  59. GDBINIT_MAIN = '''
  60. source {py_extensions}
  61. source {symbols}
  62. source {connect}
  63. '''
  64. def get_openocd_arguments(target: str) -> str:
  65. default_args = OPENOCD_TAGET_CONFIG_DEFAULT.format(target=target)
  66. return str(OPENOCD_TAGET_CONFIG.get(target, default_args))
  67. def action_extensions(base_actions: Dict, project_path: str) -> Dict:
  68. OPENOCD_OUT_FILE = 'openocd_out.txt'
  69. GDBGUI_OUT_FILE = 'gdbgui_out.txt'
  70. # Internal dictionary of currently active processes, threads and their output files
  71. processes: Dict = {'threads_to_join': [], 'allow_hints': True}
  72. def _print_hints(file_name: str) -> None:
  73. if not processes['allow_hints']:
  74. return
  75. for hint in generate_hints(file_name):
  76. if sys.stderr.isatty():
  77. yellow_print(hint)
  78. else:
  79. # Hints go to stderr. Flush stdout, so hints are printed last.
  80. sys.stdout.flush()
  81. print(hint, file=sys.stderr)
  82. def _check_openocd_errors(fail_if_openocd_failed: Dict, target: str, ctx: Context) -> None:
  83. if fail_if_openocd_failed:
  84. if 'openocd' in processes and processes['openocd'] is not None:
  85. p = processes['openocd']
  86. name = processes['openocd_outfile_name']
  87. # watch OpenOCD (for 5x500ms) to check if it hasn't terminated or outputs an error
  88. for _ in range(5):
  89. if p.poll() is not None:
  90. print('OpenOCD exited with {}'.format(p.poll()))
  91. break
  92. with open(name, 'r') as f:
  93. content = f.read()
  94. if re.search(r'Listening on port \d+ for gdb connections', content):
  95. # expect OpenOCD has started successfully - stop watching
  96. return
  97. time.sleep(0.5)
  98. # OpenOCD exited or is not listening -> print full log and terminate
  99. with open(name, 'r') as f:
  100. print(f.read())
  101. raise FatalError('Action "{}" failed due to errors in OpenOCD'.format(target), ctx)
  102. def _terminate_async_target(target: str) -> None:
  103. if target in processes and processes[target] is not None:
  104. try:
  105. if target + '_outfile' in processes:
  106. processes[target + '_outfile'].close()
  107. p = processes[target]
  108. if p.poll() is None:
  109. p.terminate()
  110. # waiting 10x100ms for the process to terminate gracefully
  111. for _ in range(10):
  112. if p.poll() is not None:
  113. break
  114. time.sleep(0.1)
  115. else:
  116. p.kill()
  117. if target + '_outfile_name' in processes:
  118. _print_hints(processes[target + '_outfile_name'])
  119. except Exception as e:
  120. print(e)
  121. print('Failed to close/kill {}'.format(target))
  122. processes[target] = None # to indicate this has ended
  123. def _get_espcoredump_instance(ctx: Context,
  124. args: PropertyDict,
  125. gdb_timeout_sec: int = None,
  126. core: str = None,
  127. save_core: str = None) -> CoreDump:
  128. ensure_build_directory(args, ctx.info_name)
  129. project_desc = get_project_desc(args, ctx)
  130. coredump_to_flash_config = get_sdkconfig_value(project_desc['config_file'],
  131. 'CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH')
  132. coredump_to_flash = coredump_to_flash_config.rstrip().endswith('y') if coredump_to_flash_config else False
  133. prog = os.path.join(project_desc['build_dir'], project_desc['app_elf'])
  134. args.port = args.port or get_default_serial_port()
  135. espcoredump_kwargs = dict()
  136. espcoredump_kwargs['port'] = args.port
  137. espcoredump_kwargs['baud'] = args.baud
  138. espcoredump_kwargs['gdb_timeout_sec'] = gdb_timeout_sec
  139. # for reproducible builds
  140. extra_gdbinit_file = project_desc.get('debug_prefix_map_gdbinit', None)
  141. if extra_gdbinit_file:
  142. espcoredump_kwargs['extra_gdbinit_file'] = extra_gdbinit_file
  143. core_format = None
  144. if core:
  145. espcoredump_kwargs['core'] = core
  146. espcoredump_kwargs['chip'] = get_sdkconfig_value(project_desc['config_file'], 'CONFIG_IDF_TARGET')
  147. core_format = get_core_file_format(core)
  148. elif coredump_to_flash:
  149. # If the core dump is read from flash, we don't need to specify the --core-format argument at all.
  150. # The format will be determined automatically
  151. pass
  152. else:
  153. print('Path to core dump file is not provided. '
  154. "Core dump can't be read from flash since this option is not enabled in menuconfig")
  155. sys.exit(1)
  156. if core_format:
  157. espcoredump_kwargs['core_format'] = core_format
  158. if save_core:
  159. espcoredump_kwargs['save_core'] = save_core
  160. espcoredump_kwargs['prog'] = prog
  161. return CoreDump(**espcoredump_kwargs)
  162. def get_core_file_format(core_file: str) -> str:
  163. bin_v1 = 1
  164. bin_v2 = 2
  165. elf_crc32 = 256
  166. elf_sha256 = 257
  167. with open(core_file, 'rb') as f:
  168. coredump_bytes = f.read(16)
  169. if coredump_bytes.startswith(b'\x7fELF'):
  170. return 'elf'
  171. core_version = int.from_bytes(coredump_bytes[4:7], 'little')
  172. if core_version in [bin_v1, bin_v2, elf_crc32, elf_sha256]:
  173. # esp-coredump will determine automatically the core format (ELF or BIN)
  174. return 'raw'
  175. with open(core_file) as c:
  176. coredump_str = c.read()
  177. try:
  178. b64decode(coredump_str)
  179. except Exception:
  180. print('The format of the provided core-file is not recognized. '
  181. 'Please ensure that the core-format matches one of the following: ELF (“elf”), '
  182. 'raw (raw) or base64-encoded (b64) binary')
  183. sys.exit(1)
  184. else:
  185. return 'b64'
  186. def is_gdb_with_python(gdb: str) -> bool:
  187. # execute simple python command to check is it supported
  188. return subprocess.run([gdb, '--batch-silent', '--ex', 'python import os'],
  189. stderr=subprocess.DEVNULL).returncode == 0
  190. def get_normalized_path(path: str) -> str:
  191. if os.name == 'nt':
  192. return os.path.normpath(path).replace('\\', '\\\\')
  193. return path
  194. def get_rom_if_condition_str(date_addr: int, date_str: str) -> str:
  195. r = []
  196. for i in range(0, len(date_str), 4):
  197. value = hex(int.from_bytes(bytes(date_str[i:i + 4], 'utf-8'), 'little'))
  198. r.append(f'(*(int*) {hex(date_addr + i)}) == {value}')
  199. return 'if ' + ' && '.join(r)
  200. def generate_gdbinit_rom_add_symbols(target: str) -> str:
  201. base_ident = ' '
  202. rom_elfs_dir = os.getenv('ESP_ROM_ELF_DIR')
  203. if not rom_elfs_dir:
  204. raise FatalError('ESP_ROM_ELF_DIR environment variable is not defined. Please try to run IDF "install" and "export" scripts.')
  205. with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), ESP_ROM_INFO_FILE), 'r') as f:
  206. roms = json.load(f)
  207. if target not in roms:
  208. msg_body = f'Target "{target}" was not found in "{ESP_ROM_INFO_FILE}". Please check IDF integrity.'
  209. if os.getenv('ESP_IDF_GDB_TESTING'):
  210. raise FatalError(msg_body)
  211. print(f'Warning: {msg_body}')
  212. return f'# {msg_body}'
  213. r = ['', f'# Load {target} ROM ELF symbols']
  214. r.append('define target hookpost-remote')
  215. r.append('set confirm off')
  216. # Since GDB does not have 'else if' statement than we use nested 'if..else' instead.
  217. for i, k in enumerate(roms[target], 1):
  218. indent_str = base_ident * i
  219. rom_file = get_normalized_path(os.path.join(rom_elfs_dir, f'{target}_rev{k["rev"]}_rom.elf'))
  220. build_date_addr = int(k['build_date_str_addr'], base=16)
  221. r.append(indent(f'# if $_streq((char *) {hex(build_date_addr)}, "{k["build_date_str"]}")', indent_str))
  222. r.append(indent(get_rom_if_condition_str(build_date_addr, k['build_date_str']), indent_str))
  223. r.append(indent(f'add-symbol-file {rom_file}', indent_str + base_ident))
  224. r.append(indent('else', indent_str))
  225. if i == len(roms[target]):
  226. # In case no one known ROM ELF fits - print error and exit with error code 1
  227. indent_str += base_ident
  228. msg_body = f'unknown {target} ROM revision.'
  229. if os.getenv('ESP_IDF_GDB_TESTING'):
  230. r.append(indent(f'echo Error: {msg_body}\\n', indent_str))
  231. r.append(indent('quit 1', indent_str))
  232. else:
  233. r.append(indent(f'echo Warning: {msg_body}\\n', indent_str))
  234. # Close 'else' operators
  235. for i in range(len(roms[target]), 0, -1):
  236. r.append(indent('end', base_ident * i))
  237. r.append('set confirm on')
  238. r.append('end')
  239. r.append('')
  240. return os.linesep.join(r)
  241. raise FatalError(f'{ESP_ROM_INFO_FILE} file not found. Please check IDF integrity.')
  242. def generate_gdbinit_files(gdb: str, gdbinit: Optional[str], project_desc: Dict[str, Any]) -> None:
  243. app_elf = get_normalized_path(os.path.join(project_desc['build_dir'], project_desc['app_elf']))
  244. if not os.path.exists(app_elf):
  245. raise FatalError('ELF file not found. You need to build & flash the project before running debug targets')
  246. # Recreate empty 'gdbinit' directory
  247. gdbinit_dir = os.path.join(project_desc['build_dir'], 'gdbinit')
  248. if os.path.isfile(gdbinit_dir):
  249. os.remove(gdbinit_dir)
  250. elif os.path.isdir(gdbinit_dir):
  251. shutil.rmtree(gdbinit_dir)
  252. os.mkdir(gdbinit_dir)
  253. # Prepare gdbinit for Python GDB extensions import
  254. py_extensions = os.path.join(gdbinit_dir, 'py_extensions')
  255. with open(py_extensions, 'w') as f:
  256. if is_gdb_with_python(gdb):
  257. f.write(GDBINIT_PYTHON_TEMPLATE.format(sys_path=sys.path))
  258. else:
  259. f.write(GDBINIT_PYTHON_NOT_SUPPORTED)
  260. # Prepare gdbinit for related ELFs symbols load
  261. symbols = os.path.join(gdbinit_dir, 'symbols')
  262. with open(symbols, 'w') as f:
  263. boot_elf = get_normalized_path(project_desc['bootloader_elf']) if 'bootloader_elf' in project_desc else None
  264. if boot_elf and os.path.exists(boot_elf):
  265. f.write(GDBINIT_BOOTLOADER_ADD_SYMBOLS.format(boot_elf=boot_elf))
  266. else:
  267. f.write(GDBINIT_BOOTLOADER_NOT_FOUND)
  268. f.write(generate_gdbinit_rom_add_symbols(project_desc['target']))
  269. f.write(GDBINIT_APP_ADD_SYMBOLS.format(app_elf=app_elf))
  270. # Generate the gdbinit for target connect if no custom gdbinit is present
  271. if not gdbinit:
  272. gdbinit = os.path.join(gdbinit_dir, 'connect')
  273. with open(gdbinit, 'w') as f:
  274. f.write(GDBINIT_CONNECT)
  275. with open(os.path.join(gdbinit_dir, 'gdbinit'), 'w') as f:
  276. f.write(GDBINIT_MAIN.format(py_extensions=py_extensions, symbols=symbols, connect=gdbinit))
  277. def debug_cleanup() -> None:
  278. print('cleaning up debug targets')
  279. for t in processes['threads_to_join']:
  280. if threading.currentThread() != t:
  281. t.join()
  282. _terminate_async_target('openocd')
  283. _terminate_async_target('gdbgui')
  284. _terminate_async_target('gdb')
  285. def post_debug(action: str, ctx: Context, args: PropertyDict, **kwargs: str) -> None:
  286. """ Deal with asynchronous targets, such as openocd running in background """
  287. if kwargs['block'] == 1:
  288. for target in ['openocd', 'gdbgui']:
  289. if target in processes and processes[target] is not None:
  290. break
  291. else:
  292. return
  293. try:
  294. p = processes[target]
  295. name = processes[target + '_outfile_name']
  296. pos = 0
  297. while True:
  298. with open(name, 'r') as f:
  299. f.seek(pos)
  300. for line in f:
  301. print(line.rstrip())
  302. pos = f.tell()
  303. if p.poll() is not None:
  304. print('"{}" exited with {}'.format(target, p.poll()))
  305. break
  306. time.sleep(0.5)
  307. except KeyboardInterrupt:
  308. print('Terminated -> exiting debug utility targets')
  309. _terminate_async_target('openocd')
  310. _terminate_async_target('gdbgui')
  311. def get_project_desc(args: PropertyDict, ctx: Context) -> Any:
  312. desc_path = os.path.join(args.build_dir, 'project_description.json')
  313. if not os.path.exists(desc_path):
  314. ensure_build_directory(args, ctx.info_name)
  315. with open(desc_path, 'r') as f:
  316. project_desc = json.load(f)
  317. return project_desc
  318. def openocd(action: str, ctx: Context, args: PropertyDict, openocd_scripts: Optional[str],
  319. openocd_commands: str) -> None:
  320. """
  321. Execute openocd as external tool
  322. """
  323. if os.getenv('OPENOCD_SCRIPTS') is None:
  324. raise FatalError('OPENOCD_SCRIPTS not found in the environment: Please run export.sh/export.bat', ctx)
  325. openocd_arguments = os.getenv('OPENOCD_COMMANDS') if openocd_commands is None else openocd_commands
  326. project_desc = get_project_desc(args, ctx)
  327. if openocd_arguments is None:
  328. # use default value if commands not defined in the environment nor command line
  329. target = project_desc['target']
  330. openocd_arguments = get_openocd_arguments(target)
  331. print('Note: OpenOCD cfg not found (via env variable OPENOCD_COMMANDS nor as a --openocd-commands argument)\n'
  332. 'OpenOCD arguments default to: "{}"'.format(openocd_arguments))
  333. # script directory is taken from the environment by OpenOCD, update only if command line arguments to override
  334. if openocd_scripts is not None:
  335. openocd_arguments += ' -s {}'.format(openocd_scripts)
  336. local_dir = project_desc['build_dir']
  337. args = ['openocd'] + shlex.split(openocd_arguments)
  338. openocd_out_name = os.path.join(local_dir, OPENOCD_OUT_FILE)
  339. openocd_out = open(openocd_out_name, 'w')
  340. try:
  341. process = subprocess.Popen(args, stdout=openocd_out, stderr=subprocess.STDOUT, bufsize=1)
  342. except Exception as e:
  343. print(e)
  344. raise FatalError(
  345. 'Error starting openocd. Please make sure it is installed and is present in executable paths', ctx)
  346. processes['openocd'] = process
  347. processes['openocd_outfile'] = openocd_out
  348. processes['openocd_outfile_name'] = openocd_out_name
  349. print('OpenOCD started as a background task {}'.format(process.pid))
  350. def get_gdb_args(project_desc: Dict[str, Any]) -> List:
  351. gdbinit = os.path.join(project_desc['build_dir'], 'gdbinit', 'gdbinit')
  352. args = ['-x={}'.format(gdbinit)]
  353. debug_prefix_gdbinit = project_desc.get('debug_prefix_map_gdbinit')
  354. if debug_prefix_gdbinit:
  355. args.append('-ix={}'.format(debug_prefix_gdbinit))
  356. return args
  357. def gdbui(action: str, ctx: Context, args: PropertyDict, gdbgui_port: Optional[str], gdbinit: Optional[str],
  358. require_openocd: bool) -> None:
  359. """
  360. Asynchronous GDB-UI target
  361. """
  362. project_desc = get_project_desc(args, ctx)
  363. local_dir = project_desc['build_dir']
  364. gdb = project_desc['monitor_toolprefix'] + 'gdb'
  365. generate_gdbinit_files(gdb, gdbinit, project_desc)
  366. # this is a workaround for gdbgui
  367. # gdbgui is using shlex.split for the --gdb-args option. When the input is:
  368. # - '"-x=foo -x=bar"', would return ['foo bar']
  369. # - '-x=foo', would return ['-x', 'foo'] and mess up the former option '--gdb-args'
  370. # so for one item, use extra double quotes. for more items, use no extra double quotes.
  371. gdb_args_list = get_gdb_args(project_desc)
  372. gdb_args = '"{}"'.format(' '.join(gdb_args_list)) if len(gdb_args_list) == 1 else ' '.join(gdb_args_list)
  373. args = ['gdbgui', '-g', gdb, '--gdb-args', gdb_args]
  374. print(args)
  375. if gdbgui_port is not None:
  376. args += ['--port', gdbgui_port]
  377. gdbgui_out_name = os.path.join(local_dir, GDBGUI_OUT_FILE)
  378. gdbgui_out = open(gdbgui_out_name, 'w')
  379. env = os.environ.copy()
  380. # The only known solution for https://github.com/cs01/gdbgui/issues/359 is to set the following environment
  381. # variable. The greenlet package cannot be downgraded for compatibility with other requirements (gdbgui,
  382. # pygdbmi).
  383. env['PURE_PYTHON'] = '1'
  384. try:
  385. process = subprocess.Popen(args, stdout=gdbgui_out, stderr=subprocess.STDOUT, bufsize=1, env=env)
  386. except (OSError, subprocess.CalledProcessError) as e:
  387. print(e)
  388. if sys.version_info[:2] >= (3, 11):
  389. raise SystemExit('Unfortunately, gdbgui is supported only with Python 3.10 or older. '
  390. 'See: https://github.com/espressif/esp-idf/issues/10116. '
  391. 'Please use "idf.py gdb" or debug in Eclipse/Vscode instead.')
  392. raise FatalError('Error starting gdbgui. Please make sure gdbgui has been installed with '
  393. '"install.{sh,bat,ps1,fish} --enable-gdbgui" and can be started.', ctx)
  394. processes['gdbgui'] = process
  395. processes['gdbgui_outfile'] = gdbgui_out
  396. processes['gdbgui_outfile_name'] = gdbgui_out_name
  397. print('gdbgui started as a background task {}'.format(process.pid))
  398. _check_openocd_errors(fail_if_openocd_failed, action, ctx)
  399. def global_callback(ctx: Context, global_args: PropertyDict, tasks: List) -> None:
  400. def move_to_front(task_name: str) -> None:
  401. for index, task in enumerate(tasks):
  402. if task.name == task_name:
  403. tasks.insert(0, tasks.pop(index))
  404. break
  405. processes['allow_hints'] = not ctx.params['no_hints']
  406. debug_targets = any([task.name in ('openocd', 'gdbgui') for task in tasks])
  407. if debug_targets:
  408. # Register the meta cleanup callback -> called on FatalError
  409. ctx.meta['cleanup'] = debug_cleanup
  410. move_to_front('gdbgui') # possibly 2nd
  411. move_to_front('openocd') # always 1st
  412. # followed by "monitor", "gdb" or "gdbtui" in any order
  413. post_action = ctx.invoke(ctx.command.get_command(ctx, 'post_debug'))
  414. if any([task.name in ('monitor', 'gdb', 'gdbtui') for task in tasks]):
  415. post_action.action_args['block'] = 0
  416. else:
  417. post_action.action_args['block'] = 1
  418. tasks.append(post_action) # always last
  419. if any([task.name == 'openocd' for task in tasks]):
  420. for task in tasks:
  421. if task.name in ('gdb', 'gdbgui', 'gdbtui'):
  422. task.action_args['require_openocd'] = True
  423. def run_gdb(gdb_args: List) -> int:
  424. p = subprocess.Popen(gdb_args)
  425. processes['gdb'] = p
  426. return p.wait()
  427. def gdbtui(action: str, ctx: Context, args: PropertyDict, gdbinit: str, require_openocd: bool) -> None:
  428. """
  429. Synchronous GDB target with text ui mode
  430. """
  431. gdb(action, ctx, args, False, 1, gdbinit, require_openocd)
  432. def gdb(action: str, ctx: Context, args: PropertyDict, batch: bool, gdb_tui: Optional[int], gdbinit: Optional[str], require_openocd: bool) -> None:
  433. """
  434. Synchronous GDB target
  435. """
  436. watch_openocd = Thread(target=_check_openocd_errors, args=(fail_if_openocd_failed, action, ctx, ))
  437. watch_openocd.start()
  438. processes['threads_to_join'].append(watch_openocd)
  439. project_desc = get_project_desc(args, ctx)
  440. gdb = project_desc['monitor_toolprefix'] + 'gdb'
  441. generate_gdbinit_files(gdb, gdbinit, project_desc)
  442. args = [gdb, *get_gdb_args(project_desc)]
  443. if gdb_tui is not None:
  444. args += ['-tui']
  445. if batch:
  446. args += ['--batch']
  447. t = Thread(target=run_gdb, args=(args,))
  448. t.start()
  449. while True:
  450. try:
  451. t.join()
  452. break
  453. except KeyboardInterrupt:
  454. # Catching Keyboard interrupt, as this is used for breaking running program in gdb
  455. continue
  456. finally:
  457. watch_openocd.join()
  458. try:
  459. processes['threads_to_join'].remove(watch_openocd)
  460. except ValueError:
  461. # Valid scenario: watch_openocd task won't be in the list if openocd not started from idf.py
  462. pass
  463. def coredump_info(action: str,
  464. ctx: Context,
  465. args: PropertyDict,
  466. gdb_timeout_sec: int,
  467. core: str = None,
  468. save_core: str = None) -> None:
  469. espcoredump = _get_espcoredump_instance(ctx=ctx, args=args, gdb_timeout_sec=gdb_timeout_sec, core=core,
  470. save_core=save_core)
  471. espcoredump.info_corefile()
  472. def coredump_debug(action: str,
  473. ctx: Context,
  474. args: PropertyDict,
  475. core: str = None,
  476. save_core: str = None) -> None:
  477. espcoredump = _get_espcoredump_instance(ctx=ctx, args=args, core=core, save_core=save_core)
  478. espcoredump.dbg_corefile()
  479. coredump_base = [
  480. {
  481. 'names': ['--core', '-c'],
  482. 'help': 'Path to core dump file (if skipped core dump will be read from flash)',
  483. },
  484. {
  485. 'names': ['--save-core', '-s'],
  486. 'help': 'Save core to file. Otherwise temporary core file will be deleted.',
  487. },
  488. ]
  489. gdb_timeout_sec_opt = {
  490. 'names': ['--gdb-timeout-sec'],
  491. 'type': INT,
  492. 'default': 1,
  493. 'help': 'Overwrite the default internal delay for gdb responses',
  494. }
  495. fail_if_openocd_failed = {
  496. 'names': ['--require-openocd', '--require_openocd'],
  497. 'help': 'Fail this target if openocd (this targets dependency) failed.\n',
  498. 'is_flag': True,
  499. 'default': False,
  500. }
  501. gdbinit = {
  502. 'names': ['--gdbinit'],
  503. 'help': 'Specify the name of gdbinit file to use\n',
  504. 'default': None,
  505. }
  506. debug_actions = {
  507. 'global_action_callbacks': [global_callback],
  508. 'actions': {
  509. 'openocd': {
  510. 'callback': openocd,
  511. 'help': 'Run openocd from current path',
  512. 'options': [
  513. {
  514. 'names': ['--openocd-scripts', '--openocd_scripts'],
  515. 'help':
  516. ('Script directory for openocd cfg files.\n'),
  517. 'default':
  518. None,
  519. },
  520. {
  521. 'names': ['--openocd-commands', '--openocd_commands'],
  522. 'help':
  523. ('Command line arguments for openocd.\n'),
  524. 'default': None,
  525. }
  526. ],
  527. 'order_dependencies': ['all', 'flash'],
  528. },
  529. 'gdb': {
  530. 'callback': gdb,
  531. 'help': 'Run the GDB.',
  532. 'options': [
  533. {
  534. 'names': ['--batch'],
  535. 'help': ('exit after processing gdbinit.\n'),
  536. 'hidden': True,
  537. 'is_flag': True,
  538. 'default': False,
  539. },
  540. {
  541. 'names': ['--gdb-tui', '--gdb_tui'],
  542. 'help': ('run gdb in TUI mode\n'),
  543. 'default': None,
  544. }, gdbinit, fail_if_openocd_failed
  545. ],
  546. 'order_dependencies': ['all', 'flash'],
  547. },
  548. 'gdbgui': {
  549. 'callback': gdbui,
  550. 'help': 'GDB UI in default browser.',
  551. 'options': [
  552. {
  553. 'names': ['--gdbgui-port', '--gdbgui_port'],
  554. 'help':
  555. ('The port on which gdbgui will be hosted. Default: 5000\n'),
  556. 'default':
  557. None,
  558. }, gdbinit, fail_if_openocd_failed
  559. ],
  560. 'order_dependencies': ['all', 'flash'],
  561. },
  562. 'gdbtui': {
  563. 'callback': gdbtui,
  564. 'help': 'GDB TUI mode.',
  565. 'options': [gdbinit, fail_if_openocd_failed],
  566. 'order_dependencies': ['all', 'flash'],
  567. },
  568. 'coredump-info': {
  569. 'callback': coredump_info,
  570. 'help': 'Print crashed task’s registers, callstack, list of available tasks in the system, '
  571. 'memory regions and contents of memory stored in core dump (TCBs and stacks)',
  572. 'options': coredump_base + [PORT, BAUD_RATE, gdb_timeout_sec_opt], # type: ignore
  573. 'order_dependencies': ['all', 'flash'],
  574. },
  575. 'coredump-debug': {
  576. 'callback': coredump_debug,
  577. 'help': 'Create core dump ELF file and run GDB debug session with this file.',
  578. 'options': coredump_base + [PORT, BAUD_RATE], # type: ignore
  579. 'order_dependencies': ['all', 'flash'],
  580. },
  581. 'post-debug': {
  582. 'callback': post_debug,
  583. 'help': 'Utility target to read the output of async debug action and stop them.',
  584. 'options': [
  585. {
  586. 'names': ['--block', '--block'],
  587. 'help':
  588. ('Set to 1 for blocking the console on the outputs of async debug actions\n'),
  589. 'default': 0,
  590. },
  591. ],
  592. 'order_dependencies': [],
  593. },
  594. 'post_debug': {
  595. 'callback': post_debug,
  596. 'deprecated': {
  597. 'since': 'v4.4',
  598. 'removed': 'v5.0',
  599. 'exit_with_error': True,
  600. 'message': 'Have you wanted to run "post-debug" instead?',
  601. },
  602. 'hidden': True,
  603. 'help': 'Utility target to read the output of async debug action and stop them.',
  604. 'options': [
  605. {
  606. 'names': ['--block', '--block'],
  607. 'help':
  608. ('Set to 1 for blocking the console on the outputs of async debug actions\n'),
  609. 'default': 0,
  610. },
  611. ],
  612. 'order_dependencies': [],
  613. },
  614. },
  615. }
  616. return debug_actions