GNU Linux-libre 5.10.219-gnu1
[releases.git] / scripts / clang-tools / gen_compile_commands.py
1 #!/usr/bin/env python3
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
10 import argparse
11 import json
12 import logging
13 import os
14 import re
15 import subprocess
16 import sys
17
18 _DEFAULT_OUTPUT = 'compile_commands.json'
19 _DEFAULT_LOG_LEVEL = 'WARNING'
20
21 _FILENAME_PATTERN = r'^\..*\.cmd$'
22 _LINE_PATTERN = r'^cmd_[^ ]*\.o := (.* )([^ ]*\.c)$'
23 _VALID_LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
24
25
26 def parse_arguments():
27     """Sets up and parses command-line arguments.
28
29     Returns:
30         log_level: A logging level to filter log output.
31         directory: The work directory where the objects were built.
32         ar: Command used for parsing .a archives.
33         output: Where to write the compile-commands JSON file.
34         paths: The list of files/directories to handle to find .cmd files.
35     """
36     usage = 'Creates a compile_commands.json database from kernel .cmd files'
37     parser = argparse.ArgumentParser(description=usage)
38
39     directory_help = ('specify the output directory used for the kernel build '
40                       '(defaults to the working directory)')
41     parser.add_argument('-d', '--directory', type=str, default='.',
42                         help=directory_help)
43
44     output_help = ('path to the output command database (defaults to ' +
45                    _DEFAULT_OUTPUT + ')')
46     parser.add_argument('-o', '--output', type=str, default=_DEFAULT_OUTPUT,
47                         help=output_help)
48
49     log_level_help = ('the level of log messages to produce (defaults to ' +
50                       _DEFAULT_LOG_LEVEL + ')')
51     parser.add_argument('--log_level', choices=_VALID_LOG_LEVELS,
52                         default=_DEFAULT_LOG_LEVEL, help=log_level_help)
53
54     ar_help = 'command used for parsing .a archives'
55     parser.add_argument('-a', '--ar', type=str, default='llvm-ar', help=ar_help)
56
57     paths_help = ('directories to search or files to parse '
58                   '(files should be *.o, *.a, or modules.order). '
59                   'If nothing is specified, the current directory is searched')
60     parser.add_argument('paths', type=str, nargs='*', help=paths_help)
61
62     args = parser.parse_args()
63
64     return (args.log_level,
65             os.path.abspath(args.directory),
66             args.output,
67             args.ar,
68             args.paths if len(args.paths) > 0 else [args.directory])
69
70
71 def cmdfiles_in_dir(directory):
72     """Generate the iterator of .cmd files found under the directory.
73
74     Walk under the given directory, and yield every .cmd file found.
75
76     Args:
77         directory: The directory to search for .cmd files.
78
79     Yields:
80         The path to a .cmd file.
81     """
82
83     filename_matcher = re.compile(_FILENAME_PATTERN)
84
85     for dirpath, _, filenames in os.walk(directory):
86         for filename in filenames:
87             if filename_matcher.match(filename):
88                 yield os.path.join(dirpath, filename)
89
90
91 def to_cmdfile(path):
92     """Return the path of .cmd file used for the given build artifact
93
94     Args:
95         Path: file path
96
97     Returns:
98         The path to .cmd file
99     """
100     dir, base = os.path.split(path)
101     return os.path.join(dir, '.' + base + '.cmd')
102
103
104 def cmdfiles_for_o(obj):
105     """Generate the iterator of .cmd files associated with the object
106
107     Yield the .cmd file used to build the given object
108
109     Args:
110         obj: The object path
111
112     Yields:
113         The path to .cmd file
114     """
115     yield to_cmdfile(obj)
116
117
118 def cmdfiles_for_a(archive, ar):
119     """Generate the iterator of .cmd files associated with the archive.
120
121     Parse the given archive, and yield every .cmd file used to build it.
122
123     Args:
124         archive: The archive to parse
125
126     Yields:
127         The path to every .cmd file found
128     """
129     for obj in subprocess.check_output([ar, '-t', archive]).decode().split():
130         yield to_cmdfile(obj)
131
132
133 def cmdfiles_for_modorder(modorder):
134     """Generate the iterator of .cmd files associated with the modules.order.
135
136     Parse the given modules.order, and yield every .cmd file used to build the
137     contained modules.
138
139     Args:
140         modorder: The modules.order file to parse
141
142     Yields:
143         The path to every .cmd file found
144     """
145     with open(modorder) as f:
146         for line in f:
147             ko = line.rstrip()
148             base, ext = os.path.splitext(ko)
149             if ext != '.ko':
150                 sys.exit('{}: module path must end with .ko'.format(ko))
151             mod = base + '.mod'
152             # The first line of *.mod lists the objects that compose the module.
153             with open(mod) as m:
154                 for obj in m.readline().split():
155                     yield to_cmdfile(obj)
156
157
158 def process_line(root_directory, command_prefix, file_path):
159     """Extracts information from a .cmd line and creates an entry from it.
160
161     Args:
162         root_directory: The directory that was searched for .cmd files. Usually
163             used directly in the "directory" entry in compile_commands.json.
164         command_prefix: The extracted command line, up to the last element.
165         file_path: The .c file from the end of the extracted command.
166             Usually relative to root_directory, but sometimes absolute.
167
168     Returns:
169         An entry to append to compile_commands.
170
171     Raises:
172         ValueError: Could not find the extracted file based on file_path and
173             root_directory or file_directory.
174     """
175     # The .cmd files are intended to be included directly by Make, so they
176     # escape the pound sign '#', either as '\#' or '$(pound)' (depending on the
177     # kernel version). The compile_commands.json file is not interepreted
178     # by Make, so this code replaces the escaped version with '#'.
179     prefix = command_prefix.replace(r'\#', '#').replace('$(pound)', '#')
180
181     # Use os.path.abspath() to normalize the path resolving '.' and '..' .
182     abs_path = os.path.abspath(os.path.join(root_directory, file_path))
183     if not os.path.exists(abs_path):
184         raise ValueError('File %s not found' % abs_path)
185     return {
186         'directory': root_directory,
187         'file': abs_path,
188         'command': prefix + file_path,
189     }
190
191
192 def main():
193     """Walks through the directory and finds and parses .cmd files."""
194     log_level, directory, output, ar, paths = parse_arguments()
195
196     level = getattr(logging, log_level)
197     logging.basicConfig(format='%(levelname)s: %(message)s', level=level)
198
199     line_matcher = re.compile(_LINE_PATTERN)
200
201     compile_commands = []
202
203     for path in paths:
204         # If 'path' is a directory, handle all .cmd files under it.
205         # Otherwise, handle .cmd files associated with the file.
206         # Most of built-in objects are linked via archives (built-in.a or lib.a)
207         # but some objects are linked to vmlinux directly.
208         # Modules are listed in modules.order.
209         if os.path.isdir(path):
210             cmdfiles = cmdfiles_in_dir(path)
211         elif path.endswith('.o'):
212             cmdfiles = cmdfiles_for_o(path)
213         elif path.endswith('.a'):
214             cmdfiles = cmdfiles_for_a(path, ar)
215         elif path.endswith('modules.order'):
216             cmdfiles = cmdfiles_for_modorder(path)
217         else:
218             sys.exit('{}: unknown file type'.format(path))
219
220         for cmdfile in cmdfiles:
221             with open(cmdfile, 'rt') as f:
222                 result = line_matcher.match(f.readline())
223                 if result:
224                     try:
225                         entry = process_line(directory, result.group(1),
226                                              result.group(2))
227                         compile_commands.append(entry)
228                     except ValueError as err:
229                         logging.info('Could not add line from %s: %s',
230                                      cmdfile, err)
231
232     with open(output, 'wt') as f:
233         json.dump(compile_commands, f, indent=2, sort_keys=True)
234
235
236 if __name__ == '__main__':
237     main()