debug_ext.py 31 KB

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