File: run_tool.py

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (418 lines) | stat: -rwxr-xr-x 14,451 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#!/usr/bin/env vpython3
# Copyright 2013 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script to help run clang tools across Chromium code.

How to use run_tool.py:
If you want to run a clang tool across all Chromium code:
run_tool.py <tool> <path/to/compiledb>

If you want to include all files mentioned in the compilation database
(this will also include generated files, unlike the previous command):
run_tool.py <tool> <path/to/compiledb> --all

If you want to run the clang tool across only chrome/browser and
content/browser:
run_tool.py <tool> <path/to/compiledb> chrome/browser content/browser

Please see docs/clang_tool_refactoring.md for more information, which documents
the entire automated refactoring flow in Chromium.

Why use run_tool.py (instead of running a clang tool directly):
The clang tool implementation doesn't take advantage of multiple cores, and if
it fails mysteriously in the middle, all the generated replacements will be
lost. Additionally, if the work is simply sharded across multiple cores by
running multiple RefactoringTools, problems arise when they attempt to rewrite a
file at the same time.

run_tool.py will
1) run multiple instances of clang tool in parallel
2) gather stdout from clang tool invocations
3) "atomically" forward #2 to stdout

Output of run_tool.py can be piped into extract_edits.py and then into
apply_edits.py. These tools will extract individual edits and apply them to the
source files. These tools assume the clang tool emits the edits in the
following format:
    ...
    ==== BEGIN EDITS ====
    r:::<file path>:::<offset>:::<length>:::<replacement text>
    r:::<file path>:::<offset>:::<length>:::<replacement text>
    ...etc...
    ==== END EDITS ====
    ...

extract_edits.py extracts only lines between BEGIN/END EDITS markers
apply_edits.py reads edit lines from stdin and applies the edits
"""

from __future__ import print_function

import argparse
from collections import namedtuple
import functools
import json
import multiprocessing
import os
import os.path
import re
import subprocess
import shlex
import sys

script_dir = os.path.dirname(os.path.realpath(__file__))
tool_dir = os.path.abspath(os.path.join(script_dir, '../pylib'))
sys.path.insert(0, tool_dir)

from clang import compile_db


CompDBEntry = namedtuple('CompDBEntry', ['directory', 'filename', 'command'])

def _PruneGitFiles(git_files, paths):
  """Prunes the list of files from git to include only those that are either in
  |paths| or start with one item in |paths|.

  Args:
    git_files: List of all repository files.
    paths: Prefix filter for the returned paths. May contain multiple entries,
        and the contents should be absolute paths.

  Returns:
    Pruned list of files.
  """
  if not git_files:
    return []
  git_files.sort()
  pruned_list = []
  git_index = 0
  for path in sorted(paths):
    least = git_index
    most = len(git_files) - 1
    while least <= most:
      middle = int((least + most) / 2)
      if git_files[middle] == path:
        least = middle
        break
      elif git_files[middle] > path:
        most = middle - 1
      else:
        least = middle + 1
    while least < len(git_files) and git_files[least].startswith(path):
      pruned_list.append(git_files[least])
      least += 1
    git_index = least

  return pruned_list


def _GetFilesFromGit(paths=None):
  """Gets the list of files in the git repository if |paths| includes prefix
  path filters or is empty. All complete filenames in |paths| are also included
  in the output.

  Args:
    paths: Prefix filter for the returned paths. May contain multiple entries.
  """
  partial_paths = []
  files = []
  for p in paths:
    real_path = os.path.realpath(p)
    if os.path.isfile(real_path):
      files.append(real_path)
    else:
      partial_paths.append(real_path)
  if partial_paths or not files:
    args = []
    if sys.platform == 'win32':
      args.append('git.bat')
    else:
      args.append('git')
    args.append('ls-files')
    command = subprocess.Popen(args, stdout=subprocess.PIPE)
    output, _ = command.communicate()
    output = output.decode('utf-8')
    git_files = [os.path.realpath(p) for p in output.splitlines()]
    if partial_paths:
      git_files = _PruneGitFiles(git_files, partial_paths)
    files.extend(git_files)
  return files


def _GetEntriesFromCompileDB(build_directory, source_filenames):
  """ Gets the list of files and args mentioned in the compilation database.

  Args:
    build_directory: Directory that contains the compile database.
    source_filenames: If not None, only include entries for the given list of
      filenames.
  """

  filenames_set = None if source_filenames is None else set(source_filenames)
  entries = compile_db.Read(build_directory)
  return [
      CompDBEntry(entry['directory'], entry['file'], entry['command'])
      for entry in entries if filenames_set is None or os.path.realpath(
          os.path.join(entry['directory'], entry['file'])) in filenames_set
  ]


def _UpdateCompileCommandsIfNeeded(compile_commands, files_list,
                                   target_os=None):
  """ Filters compile database to only include required files, and makes it
  more clang-tool friendly on Windows.

  Args:
    compile_commands: List of the contents of compile database.
    files_list: List of required files for processing. Can be None to specify
      no filtering.
  Returns:
    List of the contents of the compile database after processing.
  """
  if sys.platform == 'win32' and files_list:
    relative_paths = set([os.path.relpath(f) for f in files_list])
    filtered_compile_commands = []
    for entry in compile_commands:
      file_path = os.path.relpath(
          os.path.join(entry['directory'], entry['file']))
      if file_path in relative_paths:
        filtered_compile_commands.append(entry)
  else:
    filtered_compile_commands = compile_commands

  return compile_db.ProcessCompileDatabase(filtered_compile_commands, [],
                                           target_os)


def _ExecuteTool(toolname, tool_args, build_directory, compdb_entry):
  """Executes the clang tool.

  This is defined outside the class so it can be pickled for the multiprocessing
  module.

  Args:
    toolname: Name of the clang tool to execute.
    tool_args: Arguments to be passed to the clang tool. Can be None.
    build_directory: Directory that contains the compile database.
    compdb_entry: The file and args to run the clang tool over.

  Returns:
    A dictionary that must contain the key "status" and a boolean value
    associated with it.

    If status is True, then the generated output is stored with the key
    "stdout_text" in the dictionary.

    Otherwise, the filename and the output from stderr are associated with the
    keys "filename" and "stderr_text" respectively.
  """

  args = [toolname, compdb_entry.filename]
  if (tool_args):
    args.extend(tool_args)

  args.append('--')
  args.extend([
      a for a in shlex.split(compdb_entry.command,
                             posix=(sys.platform != 'win32'))
      # 'command' contains the full command line, including the input
      # source file itself. We need to filter it out otherwise it's
      # passed to the tool twice - once directly and once via
      # the compile args.
      if a != compdb_entry.filename
        # /showIncludes is used by Ninja to track header file dependencies on
        # Windows. We don't need to do this here, and it results in lots of spam
        # and a massive log file, so we strip it.
        and a != '/showIncludes' and a != '/showIncludes:user'
        # -MMD has the same purpose on non-Windows. It may have a corresponding
        # '-MF <filename>', which we strip below.
        and a != '-MMD'
  ])

  for i, arg in enumerate(args):
    if arg == '-MF':
      del args[i:i+2]
      break

  # shlex.split escapes double quotes in non-Posix mode, so we need to strip
  # them back.
  if sys.platform == 'win32':
    args = [a.replace('\\"', '"') for a in args]
  command = subprocess.Popen(
      args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=build_directory)
  stdout_text, stderr_text = command.communicate()
  stdout_text = stdout_text.decode('utf-8')
  stderr_text = stderr_text.decode('utf-8')
  stderr_text = re.sub(
      r"^warning: .*'linker' input unused \[-Wunused-command-line-argument\]\n",
      "", stderr_text, flags=re.MULTILINE)

  if command.returncode != 0:
    return {
        'status': False,
        'filename': compdb_entry.filename,
        'stderr_text': stderr_text,
    }
  else:
    return {
        'status': True,
        'filename': compdb_entry.filename,
        'stdout_text': stdout_text,
        'stderr_text': stderr_text,
    }


class _CompilerDispatcher(object):
  """Multiprocessing controller for running clang tools in parallel."""

  def __init__(self, toolname, tool_args, build_directory, compdb_entries):
    """Initializer method.

    Args:
      toolname: Path to the tool to execute.
      tool_args: Arguments to be passed to the tool. Can be None.
      build_directory: Directory that contains the compile database.
      compdb_entries: The files and args to run the tool over.
    """
    self.__toolname = toolname
    self.__tool_args = tool_args
    self.__build_directory = build_directory
    self.__compdb_entries = compdb_entries
    self.__success_count = 0
    self.__failed_count = 0

  @property
  def failed_count(self):
    return self.__failed_count

  def Run(self):
    """Does the grunt work."""
    pool = multiprocessing.Pool()
    result_iterator = pool.imap_unordered(
        functools.partial(_ExecuteTool, self.__toolname, self.__tool_args,
                          self.__build_directory),
                          self.__compdb_entries)
    for result in result_iterator:
      self.__ProcessResult(result)
    sys.stderr.write('\n')

  def __ProcessResult(self, result):
    """Handles result processing.

    Args:
      result: The result dictionary returned by _ExecuteTool.
    """
    if result['status']:
      self.__success_count += 1
      sys.stdout.write(result['stdout_text'])
      sys.stderr.write(result['stderr_text'])
    else:
      self.__failed_count += 1
      sys.stderr.write('\nFailed to process %s\n' % result['filename'])
      sys.stderr.write(result['stderr_text'])
      sys.stderr.write('\n')
    done_count = self.__success_count + self.__failed_count
    percentage = (float(done_count) / len(self.__compdb_entries)) * 100
    # Only output progress for every 100th entry, to make log files easier to
    # inspect.
    if done_count % 100 == 0 or done_count == len(self.__compdb_entries):
      sys.stderr.write(
          'Processed %d files with %s tool (%d failures) [%.2f%%]\r' %
          (done_count, self.__toolname, self.__failed_count, percentage))


def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--options-file',
      help='optional file to read options from')
  args, argv = parser.parse_known_args()
  if args.options_file:
    argv = open(args.options_file).read().split()

  parser.add_argument('--tool', required=True, help='clang tool to run')
  parser.add_argument('--all', action='store_true')
  parser.add_argument(
      '--generate-compdb',
      action='store_true',
      help='regenerate the compile database before running the tool')
  parser.add_argument(
      '--shard',
      metavar='<n>-of-<count>')
  parser.add_argument(
      '-p',
      required=True,
      help='path to the directory that contains the compile database')
  parser.add_argument(
      '--target_os',
      choices=['android', 'chromeos', 'ios', 'linux', 'nacl', 'mac', 'win'],
      help='Target OS - see `gn help target_os`. Set to "win" when ' +
      'cross-compiling Windows from Linux or another host')
  parser.add_argument(
      'path_filter',
      nargs='*',
      help='optional paths to filter what files the tool is run on')
  parser.add_argument(
      '--tool-arg', nargs='?', action='append',
      help='optional arguments passed to the tool')
  parser.add_argument(
      '--tool-path', nargs='?',
      help='optional path to the tool directory')
  args = parser.parse_args(argv)

  if args.tool_path:
    tool_path = os.path.abspath(args.tool_path)
  else:
    tool_path = os.path.abspath(os.path.join(
          os.path.dirname(__file__),
          '../../../third_party/llvm-build/Release+Asserts/bin'))
  if not os.path.exists(tool_path):
    sys.stderr.write('tool not found: %s\n' % tool_path)
    return -1

  if args.all:
    # Reading source files is postponed to after possible regeneration of
    # compile_commands.json.
    source_filenames = None
  else:
    git_filenames = set(_GetFilesFromGit(args.path_filter))
    # Filter out files that aren't C/C++/Obj-C/Obj-C++.
    extensions = frozenset(('.c', '.cc', '.cpp', '.m', '.mm'))
    source_filenames = [
        f for f in git_filenames if os.path.splitext(f)[1] in extensions
    ]

  if args.generate_compdb:
    compile_commands = compile_db.GenerateWithNinja(args.p)
    compile_commands = _UpdateCompileCommandsIfNeeded(compile_commands,
                                                      source_filenames,
                                                      args.target_os)
    with open(os.path.join(args.p, 'compile_commands.json'), 'w') as f:
      f.write(json.dumps(compile_commands, indent=2))

  compdb_entries = set(_GetEntriesFromCompileDB(args.p, source_filenames))

  if args.shard:
    total_length = len(compdb_entries)
    match = re.match(r'(\d+)-of-(\d+)$', args.shard)
    # Input is 1-based, but modular arithmetic is 0-based.
    shard_number = int(match.group(1)) - 1
    shard_count = int(match.group(2))
    compdb_entries = [
        f for i, f in enumerate(sorted(compdb_entries))
        if i % shard_count == shard_number
    ]
    print('Shard %d-of-%d will process %d entries out of %d' %
          (shard_number, shard_count, len(compdb_entries), total_length))

  dispatcher = _CompilerDispatcher(os.path.join(tool_path, args.tool),
                                   args.tool_arg,
                                   args.p,
                                   compdb_entries)
  dispatcher.Run()
  return -dispatcher.failed_count


if __name__ == '__main__':
  sys.exit(main())