blob: 0d3547befeef4c3fd907ea173dad31b9c1c982f8 [file] [log] [blame]
Laszlo Nagybc687582016-01-12 22:38:41 +00001# -*- coding: utf-8 -*-
2# The LLVM Compiler Infrastructure
3#
4# This file is distributed under the University of Illinois Open Source
5# License. See LICENSE.TXT for details.
6""" This module implements the 'scan-build' command API.
7
8To run the static analyzer against a build is done in multiple steps:
9
10 -- Intercept: capture the compilation command during the build,
11 -- Analyze: run the analyzer against the captured commands,
12 -- Report: create a cover report from the analyzer outputs. """
13
14import sys
15import re
16import os
17import os.path
18import json
19import argparse
20import logging
21import subprocess
22import multiprocessing
23from libscanbuild import initialize_logging, tempdir, command_entry_point
24from libscanbuild.runner import run
25from libscanbuild.intercept import capture
26from libscanbuild.report import report_directory, document
27from libscanbuild.clang import get_checkers
28from libscanbuild.runner import action_check
29from libscanbuild.command import classify_parameters, classify_source
30
31__all__ = ['analyze_build_main', 'analyze_build_wrapper']
32
33COMPILER_WRAPPER_CC = 'analyze-cc'
34COMPILER_WRAPPER_CXX = 'analyze-c++'
35
36
37@command_entry_point
38def analyze_build_main(bin_dir, from_build_command):
39 """ Entry point for 'analyze-build' and 'scan-build'. """
40
41 parser = create_parser(from_build_command)
42 args = parser.parse_args()
43 validate(parser, args, from_build_command)
44
45 # setup logging
46 initialize_logging(args.verbose)
47 logging.debug('Parsed arguments: %s', args)
48
49 with report_directory(args.output, args.keep_empty) as target_dir:
50 if not from_build_command:
51 # run analyzer only and generate cover report
52 run_analyzer(args, target_dir)
53 number_of_bugs = document(args, target_dir, True)
54 return number_of_bugs if args.status_bugs else 0
55 elif args.intercept_first:
56 # run build command and capture compiler executions
57 exit_code = capture(args, bin_dir)
58 # next step to run the analyzer against the captured commands
59 if need_analyzer(args.build):
60 run_analyzer(args, target_dir)
61 # cover report generation and bug counting
62 number_of_bugs = document(args, target_dir, True)
63 # remove the compilation database when it was not requested
64 if os.path.exists(args.cdb):
65 os.unlink(args.cdb)
66 # set exit status as it was requested
67 return number_of_bugs if args.status_bugs else exit_code
68 else:
69 return exit_code
70 else:
71 # run the build command with compiler wrappers which
72 # execute the analyzer too. (interposition)
73 environment = setup_environment(args, target_dir, bin_dir)
74 logging.debug('run build in environment: %s', environment)
75 exit_code = subprocess.call(args.build, env=environment)
76 logging.debug('build finished with exit code: %d', exit_code)
77 # cover report generation and bug counting
78 number_of_bugs = document(args, target_dir, False)
79 # set exit status as it was requested
80 return number_of_bugs if args.status_bugs else exit_code
81
82
83def need_analyzer(args):
84 """ Check the intent of the build command.
85
86 When static analyzer run against project configure step, it should be
87 silent and no need to run the analyzer or generate report.
88
89 To run `scan-build` against the configure step might be neccessary,
90 when compiler wrappers are used. That's the moment when build setup
91 check the compiler and capture the location for the build process. """
92
93 return len(args) and not re.search('configure|autogen', args[0])
94
95
96def run_analyzer(args, output_dir):
97 """ Runs the analyzer against the given compilation database. """
98
99 def exclude(filename):
100 """ Return true when any excluded directory prefix the filename. """
101 return any(re.match(r'^' + directory, filename)
102 for directory in args.excludes)
103
104 consts = {
105 'clang': args.clang,
106 'output_dir': output_dir,
107 'output_format': args.output_format,
108 'output_failures': args.output_failures,
109 'direct_args': analyzer_params(args)
110 }
111
112 logging.debug('run analyzer against compilation database')
113 with open(args.cdb, 'r') as handle:
114 generator = (dict(cmd, **consts)
115 for cmd in json.load(handle) if not exclude(cmd['file']))
116 # when verbose output requested execute sequentially
117 pool = multiprocessing.Pool(1 if args.verbose > 2 else None)
118 for current in pool.imap_unordered(run, generator):
119 if current is not None:
120 # display error message from the static analyzer
121 for line in current['error_output']:
122 logging.info(line.rstrip())
123 pool.close()
124 pool.join()
125
126
127def setup_environment(args, destination, bin_dir):
128 """ Set up environment for build command to interpose compiler wrapper. """
129
130 environment = dict(os.environ)
131 environment.update({
132 'CC': os.path.join(bin_dir, COMPILER_WRAPPER_CC),
133 'CXX': os.path.join(bin_dir, COMPILER_WRAPPER_CXX),
134 'ANALYZE_BUILD_CC': args.cc,
135 'ANALYZE_BUILD_CXX': args.cxx,
136 'ANALYZE_BUILD_CLANG': args.clang if need_analyzer(args.build) else '',
137 'ANALYZE_BUILD_VERBOSE': 'DEBUG' if args.verbose > 2 else 'WARNING',
138 'ANALYZE_BUILD_REPORT_DIR': destination,
139 'ANALYZE_BUILD_REPORT_FORMAT': args.output_format,
140 'ANALYZE_BUILD_REPORT_FAILURES': 'yes' if args.output_failures else '',
141 'ANALYZE_BUILD_PARAMETERS': ' '.join(analyzer_params(args))
142 })
143 return environment
144
145
146def analyze_build_wrapper(cplusplus):
147 """ Entry point for `analyze-cc` and `analyze-c++` compiler wrappers. """
148
149 # initialize wrapper logging
150 logging.basicConfig(format='analyze: %(levelname)s: %(message)s',
151 level=os.getenv('ANALYZE_BUILD_VERBOSE', 'INFO'))
152 # execute with real compiler
153 compiler = os.getenv('ANALYZE_BUILD_CXX', 'c++') if cplusplus \
154 else os.getenv('ANALYZE_BUILD_CC', 'cc')
155 compilation = [compiler] + sys.argv[1:]
156 logging.info('execute compiler: %s', compilation)
157 result = subprocess.call(compilation)
158 # exit when it fails, ...
159 if result or not os.getenv('ANALYZE_BUILD_CLANG'):
160 return result
161 # ... and run the analyzer if all went well.
162 try:
163 # collect the needed parameters from environment, crash when missing
164 consts = {
165 'clang': os.getenv('ANALYZE_BUILD_CLANG'),
166 'output_dir': os.getenv('ANALYZE_BUILD_REPORT_DIR'),
167 'output_format': os.getenv('ANALYZE_BUILD_REPORT_FORMAT'),
168 'output_failures': os.getenv('ANALYZE_BUILD_REPORT_FAILURES'),
169 'direct_args': os.getenv('ANALYZE_BUILD_PARAMETERS',
170 '').split(' '),
171 'directory': os.getcwd(),
172 }
173 # get relevant parameters from command line arguments
174 args = classify_parameters(sys.argv)
175 filenames = args.pop('files', [])
176 for filename in (name for name in filenames if classify_source(name)):
177 parameters = dict(args, file=filename, **consts)
178 logging.debug('analyzer parameters %s', parameters)
179 current = action_check(parameters)
180 # display error message from the static analyzer
181 if current is not None:
182 for line in current['error_output']:
183 logging.info(line.rstrip())
184 except Exception:
185 logging.exception("run analyzer inside compiler wrapper failed.")
186 return 0
187
188
189def analyzer_params(args):
190 """ A group of command line arguments can mapped to command
191 line arguments of the analyzer. This method generates those. """
192
193 def prefix_with(constant, pieces):
194 """ From a sequence create another sequence where every second element
195 is from the original sequence and the odd elements are the prefix.
196
197 eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] """
198
199 return [elem for piece in pieces for elem in [constant, piece]]
200
201 result = []
202
203 if args.store_model:
204 result.append('-analyzer-store={0}'.format(args.store_model))
205 if args.constraints_model:
206 result.append(
207 '-analyzer-constraints={0}'.format(args.constraints_model))
208 if args.internal_stats:
209 result.append('-analyzer-stats')
210 if args.analyze_headers:
211 result.append('-analyzer-opt-analyze-headers')
212 if args.stats:
213 result.append('-analyzer-checker=debug.Stats')
214 if args.maxloop:
215 result.extend(['-analyzer-max-loop', str(args.maxloop)])
216 if args.output_format:
217 result.append('-analyzer-output={0}'.format(args.output_format))
218 if args.analyzer_config:
219 result.append(args.analyzer_config)
220 if args.verbose >= 4:
221 result.append('-analyzer-display-progress')
222 if args.plugins:
223 result.extend(prefix_with('-load', args.plugins))
224 if args.enable_checker:
225 checkers = ','.join(args.enable_checker)
226 result.extend(['-analyzer-checker', checkers])
227 if args.disable_checker:
228 checkers = ','.join(args.disable_checker)
229 result.extend(['-analyzer-disable-checker', checkers])
230 if os.getenv('UBIVIZ'):
231 result.append('-analyzer-viz-egraph-ubigraph')
232
233 return prefix_with('-Xclang', result)
234
235
236def print_active_checkers(checkers):
237 """ Print active checkers to stdout. """
238
239 for name in sorted(name for name, (_, active) in checkers.items()
240 if active):
241 print(name)
242
243
244def print_checkers(checkers):
245 """ Print verbose checker help to stdout. """
246
247 print('')
248 print('available checkers:')
249 print('')
250 for name in sorted(checkers.keys()):
251 description, active = checkers[name]
252 prefix = '+' if active else ' '
253 if len(name) > 30:
254 print(' {0} {1}'.format(prefix, name))
255 print(' ' * 35 + description)
256 else:
257 print(' {0} {1: <30} {2}'.format(prefix, name, description))
258 print('')
259 print('NOTE: "+" indicates that an analysis is enabled by default.')
260 print('')
261
262
263def validate(parser, args, from_build_command):
264 """ Validation done by the parser itself, but semantic check still
265 needs to be done. This method is doing that. """
266
267 if args.help_checkers_verbose:
268 print_checkers(get_checkers(args.clang, args.plugins))
269 parser.exit()
270 elif args.help_checkers:
271 print_active_checkers(get_checkers(args.clang, args.plugins))
272 parser.exit()
273
274 if from_build_command and not args.build:
275 parser.error('missing build command')
276
277
278def create_parser(from_build_command):
279 """ Command line argument parser factory method. """
280
281 parser = argparse.ArgumentParser(
282 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
283
284 parser.add_argument(
285 '--verbose', '-v',
286 action='count',
287 default=0,
288 help="""Enable verbose output from '%(prog)s'. A second and third
289 flag increases verbosity.""")
290 parser.add_argument(
291 '--override-compiler',
292 action='store_true',
293 help="""Always resort to the compiler wrapper even when better
294 interposition methods are available.""")
295 parser.add_argument(
296 '--intercept-first',
297 action='store_true',
298 help="""Run the build commands only, build a compilation database,
299 then run the static analyzer afterwards.
300 Generally speaking it has better coverage on build commands.
301 With '--override-compiler' it use compiler wrapper, but does
302 not run the analyzer till the build is finished. """)
303 parser.add_argument(
304 '--cdb',
305 metavar='<file>',
306 default="compile_commands.json",
307 help="""The JSON compilation database.""")
308
309 parser.add_argument(
310 '--output', '-o',
311 metavar='<path>',
312 default=tempdir(),
313 help="""Specifies the output directory for analyzer reports.
314 Subdirectory will be created if default directory is targeted.
315 """)
316 parser.add_argument(
317 '--status-bugs',
318 action='store_true',
319 help="""By default, the exit status of '%(prog)s' is the same as the
320 executed build command. Specifying this option causes the exit
321 status of '%(prog)s' to be non zero if it found potential bugs
322 and zero otherwise.""")
323 parser.add_argument(
324 '--html-title',
325 metavar='<title>',
326 help="""Specify the title used on generated HTML pages.
327 If not specified, a default title will be used.""")
328 parser.add_argument(
329 '--analyze-headers',
330 action='store_true',
331 help="""Also analyze functions in #included files. By default, such
332 functions are skipped unless they are called by functions
333 within the main source file.""")
334 format_group = parser.add_mutually_exclusive_group()
335 format_group.add_argument(
336 '--plist', '-plist',
337 dest='output_format',
338 const='plist',
339 default='html',
340 action='store_const',
341 help="""This option outputs the results as a set of .plist files.""")
342 format_group.add_argument(
343 '--plist-html', '-plist-html',
344 dest='output_format',
345 const='plist-html',
346 default='html',
347 action='store_const',
348 help="""This option outputs the results as a set of .html and .plist
349 files.""")
350 # TODO: implement '-view '
351
352 advanced = parser.add_argument_group('advanced options')
353 advanced.add_argument(
354 '--keep-empty',
355 action='store_true',
356 help="""Don't remove the build results directory even if no issues
357 were reported.""")
358 advanced.add_argument(
359 '--no-failure-reports', '-no-failure-reports',
360 dest='output_failures',
361 action='store_false',
362 help="""Do not create a 'failures' subdirectory that includes analyzer
363 crash reports and preprocessed source files.""")
364 advanced.add_argument(
365 '--stats', '-stats',
366 action='store_true',
367 help="""Generates visitation statistics for the project being analyzed.
368 """)
369 advanced.add_argument(
370 '--internal-stats',
371 action='store_true',
372 help="""Generate internal analyzer statistics.""")
373 advanced.add_argument(
374 '--maxloop', '-maxloop',
375 metavar='<loop count>',
376 type=int,
377 help="""Specifiy the number of times a block can be visited before
378 giving up. Increase for more comprehensive coverage at a cost
379 of speed.""")
380 advanced.add_argument(
381 '--store', '-store',
382 metavar='<model>',
383 dest='store_model',
384 choices=['region', 'basic'],
385 help="""Specify the store model used by the analyzer.
386 'region' specifies a field- sensitive store model.
387 'basic' which is far less precise but can more quickly
388 analyze code. 'basic' was the default store model for
389 checker-0.221 and earlier.""")
390 advanced.add_argument(
391 '--constraints', '-constraints',
392 metavar='<model>',
393 dest='constraints_model',
394 choices=['range', 'basic'],
395 help="""Specify the contraint engine used by the analyzer. Specifying
396 'basic' uses a simpler, less powerful constraint model used by
397 checker-0.160 and earlier.""")
398 advanced.add_argument(
399 '--use-analyzer',
400 metavar='<path>',
401 dest='clang',
402 default='clang',
403 help="""'%(prog)s' uses the 'clang' executable relative to itself for
404 static analysis. One can override this behavior with this
405 option by using the 'clang' packaged with Xcode (on OS X) or
406 from the PATH.""")
407 advanced.add_argument(
408 '--use-cc',
409 metavar='<path>',
410 dest='cc',
411 default='cc',
412 help="""When '%(prog)s' analyzes a project by interposing a "fake
413 compiler", which executes a real compiler for compilation and
414 do other tasks (to run the static analyzer or just record the
415 compiler invocation). Because of this interposing, '%(prog)s'
416 does not know what compiler your project normally uses.
417 Instead, it simply overrides the CC environment variable, and
418 guesses your default compiler.
419
420 If you need '%(prog)s' to use a specific compiler for
421 *compilation* then you can use this option to specify a path
422 to that compiler.""")
423 advanced.add_argument(
424 '--use-c++',
425 metavar='<path>',
426 dest='cxx',
427 default='c++',
428 help="""This is the same as "--use-cc" but for C++ code.""")
429 advanced.add_argument(
430 '--analyzer-config', '-analyzer-config',
431 metavar='<options>',
432 help="""Provide options to pass through to the analyzer's
433 -analyzer-config flag. Several options are separated with
434 comma: 'key1=val1,key2=val2'
435
436 Available options:
437 stable-report-filename=true or false (default)
438
439 Switch the page naming to:
440 report-<filename>-<function/method name>-<id>.html
441 instead of report-XXXXXX.html""")
442 advanced.add_argument(
443 '--exclude',
444 metavar='<directory>',
445 dest='excludes',
446 action='append',
447 default=[],
448 help="""Do not run static analyzer against files found in this
449 directory. (You can specify this option multiple times.)
450 Could be usefull when project contains 3rd party libraries.
451 The directory path shall be absolute path as file names in
452 the compilation database.""")
453
454 plugins = parser.add_argument_group('checker options')
455 plugins.add_argument(
456 '--load-plugin', '-load-plugin',
457 metavar='<plugin library>',
458 dest='plugins',
459 action='append',
460 help="""Loading external checkers using the clang plugin interface.""")
461 plugins.add_argument(
462 '--enable-checker', '-enable-checker',
463 metavar='<checker name>',
464 action=AppendCommaSeparated,
465 help="""Enable specific checker.""")
466 plugins.add_argument(
467 '--disable-checker', '-disable-checker',
468 metavar='<checker name>',
469 action=AppendCommaSeparated,
470 help="""Disable specific checker.""")
471 plugins.add_argument(
472 '--help-checkers',
473 action='store_true',
474 help="""A default group of checkers is run unless explicitly disabled.
475 Exactly which checkers constitute the default group is a
476 function of the operating system in use. These can be printed
477 with this flag.""")
478 plugins.add_argument(
479 '--help-checkers-verbose',
480 action='store_true',
481 help="""Print all available checkers and mark the enabled ones.""")
482
483 if from_build_command:
484 parser.add_argument(
485 dest='build',
486 nargs=argparse.REMAINDER,
487 help="""Command to run.""")
488
489 return parser
490
491
492class AppendCommaSeparated(argparse.Action):
493 """ argparse Action class to support multiple comma separated lists. """
494
495 def __call__(self, __parser, namespace, values, __option_string):
496 # getattr(obj, attr, default) does not really returns default but none
497 if getattr(namespace, self.dest, None) is None:
498 setattr(namespace, self.dest, [])
499 # once it's fixed we can use as expected
500 actual = getattr(namespace, self.dest)
501 actual.extend(values.split(','))
502 setattr(namespace, self.dest, actual)