gen_compile_commands.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. #!/usr/bin/env python
  2. # SPDX-License-Identifier: GPL-2.0
  3. #
  4. # Copyright (C) Google LLC, 2018
  5. #
  6. # Author: Tom Roeder <tmroeder@google.com>
  7. #
  8. """A tool for generating compile_commands.json in the Linux kernel."""
  9. import argparse
  10. import json
  11. import logging
  12. import os
  13. import re
  14. _DEFAULT_OUTPUT = 'compile_commands.json'
  15. _DEFAULT_LOG_LEVEL = 'WARNING'
  16. _FILENAME_PATTERN = r'^\..*\.cmd$'
  17. _LINE_PATTERN = r'^cmd_[^ ]*\.o := (.* )([^ ]*\.c)$'
  18. _VALID_LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
  19. # A kernel build generally has over 2000 entries in its compile_commands.json
  20. # database. If this code finds 300 or fewer, then warn the user that they might
  21. # not have all the .cmd files, and they might need to compile the kernel.
  22. _LOW_COUNT_THRESHOLD = 300
  23. def parse_arguments():
  24. """Sets up and parses command-line arguments.
  25. Returns:
  26. log_level: A logging level to filter log output.
  27. directory: The directory to search for .cmd files.
  28. output: Where to write the compile-commands JSON file.
  29. """
  30. usage = 'Creates a compile_commands.json database from kernel .cmd files'
  31. parser = argparse.ArgumentParser(description=usage)
  32. directory_help = ('Path to the kernel source directory to search '
  33. '(defaults to the working directory)')
  34. parser.add_argument('-d', '--directory', type=str, help=directory_help)
  35. output_help = ('The location to write compile_commands.json (defaults to '
  36. 'compile_commands.json in the search directory)')
  37. parser.add_argument('-o', '--output', type=str, help=output_help)
  38. log_level_help = ('The level of log messages to produce (one of ' +
  39. ', '.join(_VALID_LOG_LEVELS) + '; defaults to ' +
  40. _DEFAULT_LOG_LEVEL + ')')
  41. parser.add_argument(
  42. '--log_level', type=str, default=_DEFAULT_LOG_LEVEL,
  43. help=log_level_help)
  44. args = parser.parse_args()
  45. log_level = args.log_level
  46. if log_level not in _VALID_LOG_LEVELS:
  47. raise ValueError('%s is not a valid log level' % log_level)
  48. directory = args.directory or os.getcwd()
  49. output = args.output or os.path.join(directory, _DEFAULT_OUTPUT)
  50. directory = os.path.abspath(directory)
  51. return log_level, directory, output
  52. def process_line(root_directory, file_directory, command_prefix, relative_path):
  53. """Extracts information from a .cmd line and creates an entry from it.
  54. Args:
  55. root_directory: The directory that was searched for .cmd files. Usually
  56. used directly in the "directory" entry in compile_commands.json.
  57. file_directory: The path to the directory the .cmd file was found in.
  58. command_prefix: The extracted command line, up to the last element.
  59. relative_path: The .c file from the end of the extracted command.
  60. Usually relative to root_directory, but sometimes relative to
  61. file_directory and sometimes neither.
  62. Returns:
  63. An entry to append to compile_commands.
  64. Raises:
  65. ValueError: Could not find the extracted file based on relative_path and
  66. root_directory or file_directory.
  67. """
  68. # The .cmd files are intended to be included directly by Make, so they
  69. # escape the pound sign '#', either as '\#' or '$(pound)' (depending on the
  70. # kernel version). The compile_commands.json file is not interepreted
  71. # by Make, so this code replaces the escaped version with '#'.
  72. prefix = command_prefix.replace('\#', '#').replace('$(pound)', '#')
  73. cur_dir = root_directory
  74. expected_path = os.path.join(cur_dir, relative_path)
  75. if not os.path.exists(expected_path):
  76. # Try using file_directory instead. Some of the tools have a different
  77. # style of .cmd file than the kernel.
  78. cur_dir = file_directory
  79. expected_path = os.path.join(cur_dir, relative_path)
  80. if not os.path.exists(expected_path):
  81. raise ValueError('File %s not in %s or %s' %
  82. (relative_path, root_directory, file_directory))
  83. return {
  84. 'directory': cur_dir,
  85. 'file': relative_path,
  86. 'command': prefix + relative_path,
  87. }
  88. def main():
  89. """Walks through the directory and finds and parses .cmd files."""
  90. log_level, directory, output = parse_arguments()
  91. level = getattr(logging, log_level)
  92. logging.basicConfig(format='%(levelname)s: %(message)s', level=level)
  93. filename_matcher = re.compile(_FILENAME_PATTERN)
  94. line_matcher = re.compile(_LINE_PATTERN)
  95. compile_commands = []
  96. for dirpath, _, filenames in os.walk(directory):
  97. for filename in filenames:
  98. if not filename_matcher.match(filename):
  99. continue
  100. filepath = os.path.join(dirpath, filename)
  101. with open(filepath, 'rt') as f:
  102. for line in f:
  103. result = line_matcher.match(line)
  104. if not result:
  105. continue
  106. try:
  107. entry = process_line(directory, dirpath,
  108. result.group(1), result.group(2))
  109. compile_commands.append(entry)
  110. except ValueError as err:
  111. logging.info('Could not add line from %s: %s',
  112. filepath, err)
  113. with open(output, 'wt') as f:
  114. json.dump(compile_commands, f, indent=2, sort_keys=True)
  115. count = len(compile_commands)
  116. if count < _LOW_COUNT_THRESHOLD:
  117. logging.warning(
  118. 'Found %s entries. Have you compiled the kernel?', count)
  119. if __name__ == '__main__':
  120. main()