debug_ext.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. # SPDX-FileCopyrightText: 2022 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 subprocess
  8. import sys
  9. import threading
  10. import time
  11. from threading import Thread
  12. from typing import Any, Dict, List, Optional
  13. from click.core import Context
  14. from idf_py_actions.errors import FatalError
  15. from idf_py_actions.tools import PropertyDict, ensure_build_directory
  16. PYTHON = sys.executable
  17. def action_extensions(base_actions: Dict, project_path: str) -> Dict:
  18. OPENOCD_OUT_FILE = 'openocd_out.txt'
  19. GDBGUI_OUT_FILE = 'gdbgui_out.txt'
  20. # Internal dictionary of currently active processes, threads and their output files
  21. processes: Dict = {'threads_to_join': [], 'openocd_issues': None}
  22. def _check_for_common_openocd_issues(file_name: str, print_all: bool=True) -> Any:
  23. if processes['openocd_issues'] is not None:
  24. return processes['openocd_issues']
  25. try:
  26. message = 'Please check JTAG connection!'
  27. with open(file_name, 'r') as f:
  28. content = f.read()
  29. if print_all:
  30. print(content)
  31. if re.search(r'Address already in use', content):
  32. message = ('Please check if another process uses the mentioned ports. OpenOCD already running, perhaps in the background?\n'
  33. 'Please list all processes to check if OpenOCD is already running; if so, terminate it before starting OpenOCD from idf.py')
  34. finally:
  35. processes['openocd_issues'] = message
  36. return message
  37. def _check_openocd_errors(fail_if_openocd_failed: Dict, target: str, ctx: Context) -> None:
  38. if fail_if_openocd_failed:
  39. if 'openocd' in processes and processes['openocd'] is not None:
  40. p = processes['openocd']
  41. name = processes['openocd_outfile_name']
  42. # watch OpenOCD (for 5x500ms) to check if it hasn't terminated or outputs an error
  43. for _ in range(5):
  44. if p.poll() is not None:
  45. print('OpenOCD exited with {}'.format(p.poll()))
  46. break
  47. with open(name, 'r') as f:
  48. content = f.read()
  49. if re.search(r'no device found', content):
  50. break
  51. if re.search(r'Listening on port \d+ for gdb connections', content):
  52. # expect OpenOCD has started successfully - stop watching
  53. return
  54. time.sleep(0.5)
  55. else:
  56. return
  57. # OpenOCD exited or error message detected -> print possible output and terminate
  58. raise FatalError('Action "{}" failed due to errors in OpenOCD:\n{}'.format(target, _check_for_common_openocd_issues(name)), ctx)
  59. def _terminate_async_target(target: str) -> None:
  60. if target in processes and processes[target] is not None:
  61. try:
  62. if target + '_outfile' in processes:
  63. processes[target + '_outfile'].close()
  64. p = processes[target]
  65. if p.poll() is None:
  66. p.terminate()
  67. # waiting 10x100ms for the process to terminate gracefully
  68. for _ in range(10):
  69. if p.poll() is not None:
  70. break
  71. time.sleep(0.1)
  72. else:
  73. p.kill()
  74. if target + '_outfile_name' in processes:
  75. if target == 'openocd':
  76. print(_check_for_common_openocd_issues(processes[target + '_outfile_name'], print_all=False))
  77. os.unlink(processes[target + '_outfile_name'])
  78. except Exception as e:
  79. print(e)
  80. print('Failed to close/kill {}'.format(target))
  81. processes[target] = None # to indicate this has ended
  82. def is_gdb_with_python(gdb: str) -> bool:
  83. # execute simple python command to check is it supported
  84. return subprocess.run([gdb, '--batch-silent', '--ex', 'python import os'], stderr=subprocess.DEVNULL).returncode == 0
  85. def create_local_gdbinit(gdb: str, gdbinit: str, elf_file: str) -> None:
  86. with open(gdbinit, 'w') as f:
  87. if is_gdb_with_python(gdb):
  88. f.write('python\n')
  89. f.write('import sys\n')
  90. f.write(f'sys.path = {sys.path}\n')
  91. f.write('import freertos_gdb\n')
  92. f.write('end\n')
  93. if os.name == 'nt':
  94. elf_file = elf_file.replace('\\','\\\\')
  95. f.write('file {}\n'.format(elf_file))
  96. f.write('target remote :3333\n')
  97. f.write('mon reset halt\n')
  98. f.write('flushregs\n')
  99. f.write('thb app_main\n')
  100. f.write('c\n')
  101. def debug_cleanup() -> None:
  102. print('cleaning up debug targets')
  103. for t in processes['threads_to_join']:
  104. if threading.currentThread() != t:
  105. t.join()
  106. _terminate_async_target('openocd')
  107. _terminate_async_target('gdbgui')
  108. _terminate_async_target('gdb')
  109. def post_debug(action: str, ctx: Context, args: PropertyDict, **kwargs: str) -> None:
  110. """ Deal with asynchronous targets, such as openocd running in background """
  111. if kwargs['block'] == 1:
  112. for target in ['openocd', 'gdbgui']:
  113. if target in processes and processes[target] is not None:
  114. break
  115. else:
  116. return
  117. try:
  118. p = processes[target]
  119. name = processes[target + '_outfile_name']
  120. pos = 0
  121. while True:
  122. with open(name, 'r') as f:
  123. f.seek(pos)
  124. for line in f:
  125. print(line.rstrip())
  126. pos = f.tell()
  127. if p.poll() is not None:
  128. print('"{}" exited with {}'.format(target, p.poll()))
  129. break
  130. time.sleep(0.5)
  131. except KeyboardInterrupt:
  132. print('Terminated -> exiting debug utility targets')
  133. _terminate_async_target('openocd')
  134. _terminate_async_target('gdbgui')
  135. def get_project_desc(args: PropertyDict, ctx: Context) -> Any:
  136. desc_path = os.path.join(args.build_dir, 'project_description.json')
  137. if not os.path.exists(desc_path):
  138. ensure_build_directory(args, ctx.info_name)
  139. with open(desc_path, 'r') as f:
  140. project_desc = json.load(f)
  141. return project_desc
  142. def openocd(action: str, ctx: Context, args: PropertyDict, openocd_scripts: Optional[str], openocd_commands: str) -> None:
  143. """
  144. Execute openocd as external tool
  145. """
  146. OPENOCD_TAGET_CONFIG = {
  147. 'esp32': '-f board/esp32-wrover-kit-3.3v.cfg',
  148. 'esp32s2': '-f board/esp32s2-kaluga-1.cfg',
  149. 'esp32c3': '-f board/esp32c3-builtin.cfg',
  150. 'esp32s3': '-f board/esp32s3-builtin.cfg',
  151. }
  152. if os.getenv('OPENOCD_SCRIPTS') is None:
  153. raise FatalError('OPENOCD_SCRIPTS not found in the environment: Please run export.sh/export.bat', ctx)
  154. openocd_arguments = os.getenv('OPENOCD_COMMANDS') if openocd_commands is None else openocd_commands
  155. project_desc = get_project_desc(args, ctx)
  156. if openocd_arguments is None:
  157. # use default value if commands not defined in the environment nor command line
  158. target = project_desc['target']
  159. default_args = '-f interface/ftdi/esp32_devkitj_v1.cfg -f target/{}.cfg'.format(target)
  160. openocd_arguments = OPENOCD_TAGET_CONFIG.get(target, default_args)
  161. print('Note: OpenOCD cfg not found (via env variable OPENOCD_COMMANDS nor as a --openocd-commands argument)\n'
  162. 'OpenOCD arguments default to: "{}"'.format(openocd_arguments))
  163. # script directory is taken from the environment by OpenOCD, update only if command line arguments to override
  164. if openocd_scripts is not None:
  165. openocd_arguments += ' -s {}'.format(openocd_scripts)
  166. local_dir = project_desc['build_dir']
  167. args = ['openocd'] + shlex.split(openocd_arguments)
  168. openocd_out_name = os.path.join(local_dir, OPENOCD_OUT_FILE)
  169. openocd_out = open(openocd_out_name, 'a+')
  170. try:
  171. process = subprocess.Popen(args, stdout=openocd_out, stderr=subprocess.STDOUT, bufsize=1)
  172. except Exception as e:
  173. print(e)
  174. raise FatalError('Error starting openocd. Please make sure it is installed and is present in executable paths', ctx)
  175. processes['openocd'] = process
  176. processes['openocd_outfile'] = openocd_out
  177. processes['openocd_outfile_name'] = openocd_out_name
  178. print('OpenOCD started as a background task {}'.format(process.pid))
  179. def get_gdb_args(gdbinit: str, project_desc: Dict[str, Any]) -> List:
  180. args = ['-x={}'.format(gdbinit)]
  181. debug_prefix_gdbinit = project_desc.get('debug_prefix_map_gdbinit')
  182. if debug_prefix_gdbinit:
  183. args.append('-ix={}'.format(debug_prefix_gdbinit))
  184. return args
  185. def gdbui(action: str, ctx: Context, args: PropertyDict, gdbgui_port: Optional[str], gdbinit: Optional[str], require_openocd: bool) -> None:
  186. """
  187. Asynchronous GDB-UI target
  188. """
  189. project_desc = get_project_desc(args, ctx)
  190. local_dir = project_desc['build_dir']
  191. gdb = project_desc['monitor_toolprefix'] + 'gdb'
  192. if gdbinit is None:
  193. gdbinit = os.path.join(local_dir, 'gdbinit')
  194. create_local_gdbinit(gdb, gdbinit, os.path.join(args.build_dir, project_desc['app_elf']))
  195. # this is a workaround for gdbgui
  196. # gdbgui is using shlex.split for the --gdb-args option. When the input is:
  197. # - '"-x=foo -x=bar"', would return ['foo bar']
  198. # - '-x=foo', would return ['-x', 'foo'] and mess up the former option '--gdb-args'
  199. # so for one item, use extra double quotes. for more items, use no extra double quotes.
  200. gdb_args_list = get_gdb_args(gdbinit, project_desc)
  201. gdb_args = '"{}"'.format(' '.join(gdb_args_list)) if len(gdb_args_list) == 1 else ' '.join(gdb_args_list)
  202. args = ['gdbgui', '-g', gdb, '--gdb-args', gdb_args]
  203. print(args)
  204. if gdbgui_port is not None:
  205. args += ['--port', gdbgui_port]
  206. gdbgui_out_name = os.path.join(local_dir, GDBGUI_OUT_FILE)
  207. gdbgui_out = open(gdbgui_out_name, 'a+')
  208. env = os.environ.copy()
  209. # The only known solution for https://github.com/cs01/gdbgui/issues/359 is to set the following environment
  210. # variable. The greenlet package cannot be downgraded for compatibility with other requirements (gdbgui,
  211. # pygdbmi).
  212. env['PURE_PYTHON'] = '1'
  213. try:
  214. process = subprocess.Popen(args, stdout=gdbgui_out, stderr=subprocess.STDOUT, bufsize=1, env=env)
  215. except Exception as e:
  216. print(e)
  217. raise FatalError('Error starting gdbgui. Please make sure gdbgui has been installed with '
  218. '"install.{sh,bat,ps1,fish} --enable-gdbgui" and can be started.', ctx)
  219. processes['gdbgui'] = process
  220. processes['gdbgui_outfile'] = gdbgui_out
  221. processes['gdbgui_outfile_name'] = gdbgui_out_name
  222. print('gdbgui started as a background task {}'.format(process.pid))
  223. _check_openocd_errors(fail_if_openocd_failed, action, ctx)
  224. def global_callback(ctx: Context, global_args: PropertyDict, tasks: List) -> None:
  225. def move_to_front(task_name: str) -> None:
  226. for index, task in enumerate(tasks):
  227. if task.name == task_name:
  228. tasks.insert(0, tasks.pop(index))
  229. break
  230. debug_targets = any([task.name in ('openocd', 'gdbgui') for task in tasks])
  231. if debug_targets:
  232. # Register the meta cleanup callback -> called on FatalError
  233. ctx.meta['cleanup'] = debug_cleanup
  234. move_to_front('gdbgui') # possibly 2nd
  235. move_to_front('openocd') # always 1st
  236. # followed by "monitor", "gdb" or "gdbtui" in any order
  237. post_action = ctx.invoke(ctx.command.get_command(ctx, 'post_debug'))
  238. if any([task.name in ('monitor', 'gdb', 'gdbtui') for task in tasks]):
  239. post_action.action_args['block'] = 0
  240. else:
  241. post_action.action_args['block'] = 1
  242. tasks.append(post_action) # always last
  243. if any([task.name == 'openocd' for task in tasks]):
  244. for task in tasks:
  245. if task.name in ('gdb', 'gdbgui', 'gdbtui'):
  246. task.action_args['require_openocd'] = True
  247. def run_gdb(gdb_args: List) -> int:
  248. p = subprocess.Popen(gdb_args)
  249. processes['gdb'] = p
  250. return p.wait()
  251. def gdbtui(action: str, ctx: Context, args: PropertyDict, gdbinit: str, require_openocd: bool) -> None:
  252. """
  253. Synchronous GDB target with text ui mode
  254. """
  255. gdb(action, ctx, args, 1, gdbinit, require_openocd)
  256. def gdb(action: str, ctx: Context, args: PropertyDict, gdb_tui: Optional[int], gdbinit: Optional[str], require_openocd: bool) -> None:
  257. """
  258. Synchronous GDB target
  259. """
  260. watch_openocd = Thread(target=_check_openocd_errors, args=(fail_if_openocd_failed, action, ctx, ))
  261. watch_openocd.start()
  262. processes['threads_to_join'].append(watch_openocd)
  263. project_desc = get_project_desc(args, ctx)
  264. elf_file = os.path.join(args.build_dir, project_desc['app_elf'])
  265. if not os.path.exists(elf_file):
  266. raise FatalError('ELF file not found. You need to build & flash the project before running debug targets', ctx)
  267. gdb = project_desc['monitor_toolprefix'] + 'gdb'
  268. local_dir = project_desc['build_dir']
  269. if gdbinit is None:
  270. gdbinit = os.path.join(local_dir, 'gdbinit')
  271. create_local_gdbinit(gdb, gdbinit, elf_file)
  272. args = [gdb, *get_gdb_args(gdbinit, project_desc)]
  273. if gdb_tui is not None:
  274. args += ['-tui']
  275. t = Thread(target=run_gdb, args=(args,))
  276. t.start()
  277. while True:
  278. try:
  279. t.join()
  280. break
  281. except KeyboardInterrupt:
  282. # Catching Keyboard interrupt, as this is used for breaking running program in gdb
  283. continue
  284. finally:
  285. watch_openocd.join()
  286. try:
  287. processes['threads_to_join'].remove(watch_openocd)
  288. except ValueError:
  289. # Valid scenario: watch_openocd task won't be in the list if openocd not started from idf.py
  290. pass
  291. fail_if_openocd_failed = {
  292. 'names': ['--require-openocd', '--require_openocd'],
  293. 'help':
  294. ('Fail this target if openocd (this targets dependency) failed.\n'),
  295. 'is_flag': True,
  296. 'default': False,
  297. }
  298. gdbinit = {
  299. 'names': ['--gdbinit'],
  300. 'help': ('Specify the name of gdbinit file to use\n'),
  301. 'default': None,
  302. }
  303. debug_actions = {
  304. 'global_action_callbacks': [global_callback],
  305. 'actions': {
  306. 'openocd': {
  307. 'callback': openocd,
  308. 'help': 'Run openocd from current path',
  309. 'options': [
  310. {
  311. 'names': ['--openocd-scripts', '--openocd_scripts'],
  312. 'help':
  313. ('Script directory for openocd cfg files.\n'),
  314. 'default':
  315. None,
  316. },
  317. {
  318. 'names': ['--openocd-commands', '--openocd_commands'],
  319. 'help':
  320. ('Command line arguments for openocd.\n'),
  321. 'default': None,
  322. }
  323. ],
  324. 'order_dependencies': ['all', 'flash'],
  325. },
  326. 'gdb': {
  327. 'callback': gdb,
  328. 'help': 'Run the GDB.',
  329. 'options': [
  330. {
  331. 'names': ['--gdb-tui', '--gdb_tui'],
  332. 'help':
  333. ('run gdb in TUI mode\n'),
  334. 'default':
  335. None,
  336. }, gdbinit, fail_if_openocd_failed
  337. ],
  338. 'order_dependencies': ['all', 'flash'],
  339. },
  340. 'gdbgui': {
  341. 'callback': gdbui,
  342. 'help': 'GDB UI in default browser.',
  343. 'options': [
  344. {
  345. 'names': ['--gdbgui-port', '--gdbgui_port'],
  346. 'help':
  347. ('The port on which gdbgui will be hosted. Default: 5000\n'),
  348. 'default':
  349. None,
  350. }, gdbinit, fail_if_openocd_failed
  351. ],
  352. 'order_dependencies': ['all', 'flash'],
  353. },
  354. 'gdbtui': {
  355. 'callback': gdbtui,
  356. 'help': 'GDB TUI mode.',
  357. 'options': [gdbinit, fail_if_openocd_failed],
  358. 'order_dependencies': ['all', 'flash'],
  359. },
  360. 'post-debug': {
  361. 'callback': post_debug,
  362. 'help': 'Utility target to read the output of async debug action and stop them.',
  363. 'options': [
  364. {
  365. 'names': ['--block', '--block'],
  366. 'help':
  367. ('Set to 1 for blocking the console on the outputs of async debug actions\n'),
  368. 'default': 0,
  369. },
  370. ],
  371. 'order_dependencies': [],
  372. },
  373. 'post_debug': {
  374. 'callback': post_debug,
  375. 'deprecated': {
  376. 'since': 'v4.4',
  377. 'removed': 'v5.0',
  378. 'exit_with_error': True,
  379. 'message': 'Have you wanted to run "post-debug" instead?',
  380. },
  381. 'hidden': True,
  382. 'help': 'Utility target to read the output of async debug action and stop them.',
  383. 'options': [
  384. {
  385. 'names': ['--block', '--block'],
  386. 'help':
  387. ('Set to 1 for blocking the console on the outputs of async debug actions\n'),
  388. 'default': 0,
  389. },
  390. ],
  391. 'order_dependencies': [],
  392. },
  393. },
  394. }
  395. return debug_actions