debug_ext.py 17 KB

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