hresult_to_enum.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/env python3
  2. # Copyright 2021 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Helper for converting Windows HRESULT defines to enums.xml entries.
  6. It only works with HRESULTs defined using `_HRESULT_TYPEDEF_`, e.g.
  7. #define MF_E_SAMPLE_NOT_WRITABLE _HRESULT_TYPEDEF_(0xC00D36E0L)
  8. will be converted to
  9. <int value="-1072875808" label="MF_E_SAMPLE_NOT_WRITABLE"/>
  10. Some Windows files may use different or no macros to define HRESULTs, e.g.
  11. #define DRM_E_FILEOPEN ((DRM_RESULT)0x8003006EL)
  12. #define MF_INDEX_SIZE_ERR 0x80700001
  13. This script will not work in those cases, but is easy to be modified to work.
  14. Usage:
  15. tools/hresult_to_enum.py -i mferror.h -o mferror.xml
  16. """
  17. import argparse
  18. import re
  19. import sys
  20. _HRESULT_RE = re.compile(
  21. r'^#define\s+([0-9A-Z_]+)\s+.*_HRESULT_TYPEDEF_\((0x[0-9A-F]{8}).*')
  22. def _HexToSignedInt(hex_str):
  23. """Converts a hex string to a signed integer string.
  24. Args:
  25. hex_str: A string representing a hex number.
  26. Returns:
  27. A string representing the converted signed integer.
  28. """
  29. int_val = int(hex_str, 16)
  30. if int_val & (1 << 31):
  31. int_val -= 1 << 32
  32. return str(int_val)
  33. def _HresultToEnum(match):
  34. """Converts an HRESULT define to an enums.xml entry.
  35. """
  36. hresult = match.group(1)
  37. hex_str = match.group(2)
  38. int_str = _HexToSignedInt(hex_str)
  39. return f'<int value="{int_str}" label="{hresult}"/>'
  40. def _ConvertAllHresultDefines(source):
  41. """Converts all HRESULT defines to enums.xml entries.
  42. """
  43. in_lines = source.splitlines()
  44. out_lines = []
  45. for in_line in in_lines:
  46. out_line, num_of_subs = _HRESULT_RE.subn(_HresultToEnum, in_line)
  47. assert num_of_subs <= 1
  48. if num_of_subs == 1:
  49. out_lines.append(out_line)
  50. return '\n'.join(out_lines)
  51. def main():
  52. parser = argparse.ArgumentParser(
  53. description='Convert HEX HRESULT to signed integer.')
  54. parser.add_argument('-i',
  55. '--input',
  56. help='The input file containing HRESULT defines',
  57. required=True)
  58. parser.add_argument('-o',
  59. '--output',
  60. help='The output file containing enums.xml entries',
  61. required=True)
  62. args = parser.parse_args()
  63. with open(args.input, 'r') as f:
  64. new_source = _ConvertAllHresultDefines(f.read())
  65. with open(args.output, 'w', newline='\n') as f:
  66. f.write(new_source)
  67. if __name__ == '__main__':
  68. sys.exit(main())