panic_utils.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import hashlib
  4. import logging
  5. import re
  6. import time
  7. from subprocess import Popen
  8. class NoGdbProcessError(ValueError):
  9. """Raise when trying to interact with gdb subprocess, but it does not exist.
  10. It may have been killed and removed, or failed to initialize for some reason."""
  11. pass
  12. def sha256(file: str) -> str:
  13. res = hashlib.sha256()
  14. with open(file, 'rb') as fr:
  15. res.update(fr.read())
  16. return res.hexdigest()
  17. def quote_string(string: str) -> str:
  18. """Return a shell-escaped version of the string *string*."""
  19. _find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search
  20. if not string:
  21. return "''"
  22. if _find_unsafe(string) is None:
  23. return string
  24. # use single quotes, and put single quotes into double quotes
  25. # the string $'b is then quoted as '$'"'"'b'
  26. return "'" + string.replace("'", "'\"'\"'") + "'"
  27. def verify_valid_gdb_subprocess(gdb_process: Popen) -> None:
  28. """Verify there is a process object, and that it is still running.
  29. Raise NoGdbProcessError if either of the above are not true."""
  30. if not gdb_process:
  31. raise NoGdbProcessError('gdb process is not attached')
  32. elif gdb_process.poll() is not None:
  33. raise NoGdbProcessError(
  34. 'gdb process has already finished with return code: %s'
  35. % str(gdb_process.poll())
  36. )
  37. def attach_logger() -> logging.Logger:
  38. handler = logging.StreamHandler()
  39. handler.setFormatter(logging.Formatter('%(message)s'))
  40. unique_number = time.time()
  41. logger = logging.getLogger(__name__ + '.' + str(unique_number))
  42. logger.propagate = False
  43. logger.setLevel(logging.ERROR)
  44. logger.addHandler(handler)
  45. return logger