analyze.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. # -*- 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. To run the static analyzer against a build is done in multiple steps:
  8. -- Intercept: capture the compilation command during the build,
  9. -- Analyze: run the analyzer against the captured commands,
  10. -- Report: create a cover report from the analyzer outputs. """
  11. import re
  12. import os
  13. import os.path
  14. import json
  15. import logging
  16. import multiprocessing
  17. import tempfile
  18. import functools
  19. import subprocess
  20. import contextlib
  21. import datetime
  22. import shutil
  23. import glob
  24. from collections import defaultdict
  25. from libscanbuild import command_entry_point, compiler_wrapper, \
  26. wrapper_environment, run_build, run_command, CtuConfig
  27. from libscanbuild.arguments import parse_args_for_scan_build, \
  28. parse_args_for_analyze_build
  29. from libscanbuild.intercept import capture
  30. from libscanbuild.report import document
  31. from libscanbuild.compilation import split_command, classify_source, \
  32. compiler_language
  33. from libscanbuild.clang import get_version, get_arguments, get_triple_arch
  34. from libscanbuild.shell import decode
  35. __all__ = ['scan_build', 'analyze_build', 'analyze_compiler_wrapper']
  36. COMPILER_WRAPPER_CC = 'analyze-cc'
  37. COMPILER_WRAPPER_CXX = 'analyze-c++'
  38. CTU_FUNCTION_MAP_FILENAME = 'externalFnMap.txt'
  39. CTU_TEMP_FNMAP_FOLDER = 'tmpExternalFnMaps'
  40. @command_entry_point
  41. def scan_build():
  42. """ Entry point for scan-build command. """
  43. args = parse_args_for_scan_build()
  44. # will re-assign the report directory as new output
  45. with report_directory(args.output, args.keep_empty) as args.output:
  46. # Run against a build command. there are cases, when analyzer run
  47. # is not required. But we need to set up everything for the
  48. # wrappers, because 'configure' needs to capture the CC/CXX values
  49. # for the Makefile.
  50. if args.intercept_first:
  51. # Run build command with intercept module.
  52. exit_code = capture(args)
  53. # Run the analyzer against the captured commands.
  54. if need_analyzer(args.build):
  55. govern_analyzer_runs(args)
  56. else:
  57. # Run build command and analyzer with compiler wrappers.
  58. environment = setup_environment(args)
  59. exit_code = run_build(args.build, env=environment)
  60. # Cover report generation and bug counting.
  61. number_of_bugs = document(args)
  62. # Set exit status as it was requested.
  63. return number_of_bugs if args.status_bugs else exit_code
  64. @command_entry_point
  65. def analyze_build():
  66. """ Entry point for analyze-build command. """
  67. args = parse_args_for_analyze_build()
  68. # will re-assign the report directory as new output
  69. with report_directory(args.output, args.keep_empty) as args.output:
  70. # Run the analyzer against a compilation db.
  71. govern_analyzer_runs(args)
  72. # Cover report generation and bug counting.
  73. number_of_bugs = document(args)
  74. # Set exit status as it was requested.
  75. return number_of_bugs if args.status_bugs else 0
  76. def need_analyzer(args):
  77. """ Check the intent of the build command.
  78. When static analyzer run against project configure step, it should be
  79. silent and no need to run the analyzer or generate report.
  80. To run `scan-build` against the configure step might be necessary,
  81. when compiler wrappers are used. That's the moment when build setup
  82. check the compiler and capture the location for the build process. """
  83. return len(args) and not re.search('configure|autogen', args[0])
  84. def prefix_with(constant, pieces):
  85. """ From a sequence create another sequence where every second element
  86. is from the original sequence and the odd elements are the prefix.
  87. eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] """
  88. return [elem for piece in pieces for elem in [constant, piece]]
  89. def get_ctu_config_from_args(args):
  90. """ CTU configuration is created from the chosen phases and dir. """
  91. return (
  92. CtuConfig(collect=args.ctu_phases.collect,
  93. analyze=args.ctu_phases.analyze,
  94. dir=args.ctu_dir,
  95. func_map_cmd=args.func_map_cmd)
  96. if hasattr(args, 'ctu_phases') and hasattr(args.ctu_phases, 'dir')
  97. else CtuConfig(collect=False, analyze=False, dir='', func_map_cmd=''))
  98. def get_ctu_config_from_json(ctu_conf_json):
  99. """ CTU configuration is created from the chosen phases and dir. """
  100. ctu_config = json.loads(ctu_conf_json)
  101. # Recover namedtuple from json when coming from analyze-cc or analyze-c++
  102. return CtuConfig(collect=ctu_config[0],
  103. analyze=ctu_config[1],
  104. dir=ctu_config[2],
  105. func_map_cmd=ctu_config[3])
  106. def create_global_ctu_function_map(func_map_lines):
  107. """ Takes iterator of individual function maps and creates a global map
  108. keeping only unique names. We leave conflicting names out of CTU.
  109. :param func_map_lines: Contains the id of a function (mangled name) and
  110. the originating source (the corresponding AST file) name.
  111. :type func_map_lines: Iterator of str.
  112. :returns: Mangled name - AST file pairs.
  113. :rtype: List of (str, str) tuples.
  114. """
  115. mangled_to_asts = defaultdict(set)
  116. for line in func_map_lines:
  117. mangled_name, ast_file = line.strip().split(' ', 1)
  118. mangled_to_asts[mangled_name].add(ast_file)
  119. mangled_ast_pairs = []
  120. for mangled_name, ast_files in mangled_to_asts.items():
  121. if len(ast_files) == 1:
  122. mangled_ast_pairs.append((mangled_name, next(iter(ast_files))))
  123. return mangled_ast_pairs
  124. def merge_ctu_func_maps(ctudir):
  125. """ Merge individual function maps into a global one.
  126. As the collect phase runs parallel on multiple threads, all compilation
  127. units are separately mapped into a temporary file in CTU_TEMP_FNMAP_FOLDER.
  128. These function maps contain the mangled names of functions and the source
  129. (AST generated from the source) which had them.
  130. These files should be merged at the end into a global map file:
  131. CTU_FUNCTION_MAP_FILENAME."""
  132. def generate_func_map_lines(fnmap_dir):
  133. """ Iterate over all lines of input files in a determined order. """
  134. files = glob.glob(os.path.join(fnmap_dir, '*'))
  135. files.sort()
  136. for filename in files:
  137. with open(filename, 'r') as in_file:
  138. for line in in_file:
  139. yield line
  140. def write_global_map(arch, mangled_ast_pairs):
  141. """ Write (mangled function name, ast file) pairs into final file. """
  142. extern_fns_map_file = os.path.join(ctudir, arch,
  143. CTU_FUNCTION_MAP_FILENAME)
  144. with open(extern_fns_map_file, 'w') as out_file:
  145. for mangled_name, ast_file in mangled_ast_pairs:
  146. out_file.write('%s %s\n' % (mangled_name, ast_file))
  147. triple_arches = glob.glob(os.path.join(ctudir, '*'))
  148. for triple_path in triple_arches:
  149. if os.path.isdir(triple_path):
  150. triple_arch = os.path.basename(triple_path)
  151. fnmap_dir = os.path.join(ctudir, triple_arch,
  152. CTU_TEMP_FNMAP_FOLDER)
  153. func_map_lines = generate_func_map_lines(fnmap_dir)
  154. mangled_ast_pairs = create_global_ctu_function_map(func_map_lines)
  155. write_global_map(triple_arch, mangled_ast_pairs)
  156. # Remove all temporary files
  157. shutil.rmtree(fnmap_dir, ignore_errors=True)
  158. def run_analyzer_parallel(args):
  159. """ Runs the analyzer against the given compilation database. """
  160. def exclude(filename):
  161. """ Return true when any excluded directory prefix the filename. """
  162. return any(re.match(r'^' + directory, filename)
  163. for directory in args.excludes)
  164. consts = {
  165. 'clang': args.clang,
  166. 'output_dir': args.output,
  167. 'output_format': args.output_format,
  168. 'output_failures': args.output_failures,
  169. 'direct_args': analyzer_params(args),
  170. 'force_debug': args.force_debug,
  171. 'ctu': get_ctu_config_from_args(args)
  172. }
  173. logging.debug('run analyzer against compilation database')
  174. with open(args.cdb, 'r') as handle:
  175. generator = (dict(cmd, **consts)
  176. for cmd in json.load(handle) if not exclude(cmd['file']))
  177. # when verbose output requested execute sequentially
  178. pool = multiprocessing.Pool(1 if args.verbose > 2 else None)
  179. for current in pool.imap_unordered(run, generator):
  180. if current is not None:
  181. # display error message from the static analyzer
  182. for line in current['error_output']:
  183. logging.info(line.rstrip())
  184. pool.close()
  185. pool.join()
  186. def govern_analyzer_runs(args):
  187. """ Governs multiple runs in CTU mode or runs once in normal mode. """
  188. ctu_config = get_ctu_config_from_args(args)
  189. # If we do a CTU collect (1st phase) we remove all previous collection
  190. # data first.
  191. if ctu_config.collect:
  192. shutil.rmtree(ctu_config.dir, ignore_errors=True)
  193. # If the user asked for a collect (1st) and analyze (2nd) phase, we do an
  194. # all-in-one run where we deliberately remove collection data before and
  195. # also after the run. If the user asks only for a single phase data is
  196. # left so multiple analyze runs can use the same data gathered by a single
  197. # collection run.
  198. if ctu_config.collect and ctu_config.analyze:
  199. # CTU strings are coming from args.ctu_dir and func_map_cmd,
  200. # so we can leave it empty
  201. args.ctu_phases = CtuConfig(collect=True, analyze=False,
  202. dir='', func_map_cmd='')
  203. run_analyzer_parallel(args)
  204. merge_ctu_func_maps(ctu_config.dir)
  205. args.ctu_phases = CtuConfig(collect=False, analyze=True,
  206. dir='', func_map_cmd='')
  207. run_analyzer_parallel(args)
  208. shutil.rmtree(ctu_config.dir, ignore_errors=True)
  209. else:
  210. # Single runs (collect or analyze) are launched from here.
  211. run_analyzer_parallel(args)
  212. if ctu_config.collect:
  213. merge_ctu_func_maps(ctu_config.dir)
  214. def setup_environment(args):
  215. """ Set up environment for build command to interpose compiler wrapper. """
  216. environment = dict(os.environ)
  217. environment.update(wrapper_environment(args))
  218. environment.update({
  219. 'CC': COMPILER_WRAPPER_CC,
  220. 'CXX': COMPILER_WRAPPER_CXX,
  221. 'ANALYZE_BUILD_CLANG': args.clang if need_analyzer(args.build) else '',
  222. 'ANALYZE_BUILD_REPORT_DIR': args.output,
  223. 'ANALYZE_BUILD_REPORT_FORMAT': args.output_format,
  224. 'ANALYZE_BUILD_REPORT_FAILURES': 'yes' if args.output_failures else '',
  225. 'ANALYZE_BUILD_PARAMETERS': ' '.join(analyzer_params(args)),
  226. 'ANALYZE_BUILD_FORCE_DEBUG': 'yes' if args.force_debug else '',
  227. 'ANALYZE_BUILD_CTU': json.dumps(get_ctu_config_from_args(args))
  228. })
  229. return environment
  230. @command_entry_point
  231. def analyze_compiler_wrapper():
  232. """ Entry point for `analyze-cc` and `analyze-c++` compiler wrappers. """
  233. return compiler_wrapper(analyze_compiler_wrapper_impl)
  234. def analyze_compiler_wrapper_impl(result, execution):
  235. """ Implements analyzer compiler wrapper functionality. """
  236. # don't run analyzer when compilation fails. or when it's not requested.
  237. if result or not os.getenv('ANALYZE_BUILD_CLANG'):
  238. return
  239. # check is it a compilation?
  240. compilation = split_command(execution.cmd)
  241. if compilation is None:
  242. return
  243. # collect the needed parameters from environment, crash when missing
  244. parameters = {
  245. 'clang': os.getenv('ANALYZE_BUILD_CLANG'),
  246. 'output_dir': os.getenv('ANALYZE_BUILD_REPORT_DIR'),
  247. 'output_format': os.getenv('ANALYZE_BUILD_REPORT_FORMAT'),
  248. 'output_failures': os.getenv('ANALYZE_BUILD_REPORT_FAILURES'),
  249. 'direct_args': os.getenv('ANALYZE_BUILD_PARAMETERS',
  250. '').split(' '),
  251. 'force_debug': os.getenv('ANALYZE_BUILD_FORCE_DEBUG'),
  252. 'directory': execution.cwd,
  253. 'command': [execution.cmd[0], '-c'] + compilation.flags,
  254. 'ctu': get_ctu_config_from_json(os.getenv('ANALYZE_BUILD_CTU'))
  255. }
  256. # call static analyzer against the compilation
  257. for source in compilation.files:
  258. parameters.update({'file': source})
  259. logging.debug('analyzer parameters %s', parameters)
  260. current = run(parameters)
  261. # display error message from the static analyzer
  262. if current is not None:
  263. for line in current['error_output']:
  264. logging.info(line.rstrip())
  265. @contextlib.contextmanager
  266. def report_directory(hint, keep):
  267. """ Responsible for the report directory.
  268. hint -- could specify the parent directory of the output directory.
  269. keep -- a boolean value to keep or delete the empty report directory. """
  270. stamp_format = 'scan-build-%Y-%m-%d-%H-%M-%S-%f-'
  271. stamp = datetime.datetime.now().strftime(stamp_format)
  272. parent_dir = os.path.abspath(hint)
  273. if not os.path.exists(parent_dir):
  274. os.makedirs(parent_dir)
  275. name = tempfile.mkdtemp(prefix=stamp, dir=parent_dir)
  276. logging.info('Report directory created: %s', name)
  277. try:
  278. yield name
  279. finally:
  280. if os.listdir(name):
  281. msg = "Run 'scan-view %s' to examine bug reports."
  282. keep = True
  283. else:
  284. if keep:
  285. msg = "Report directory '%s' contains no report, but kept."
  286. else:
  287. msg = "Removing directory '%s' because it contains no report."
  288. logging.warning(msg, name)
  289. if not keep:
  290. os.rmdir(name)
  291. def analyzer_params(args):
  292. """ A group of command line arguments can mapped to command
  293. line arguments of the analyzer. This method generates those. """
  294. result = []
  295. if args.store_model:
  296. result.append('-analyzer-store={0}'.format(args.store_model))
  297. if args.constraints_model:
  298. result.append('-analyzer-constraints={0}'.format(
  299. args.constraints_model))
  300. if args.internal_stats:
  301. result.append('-analyzer-stats')
  302. if args.analyze_headers:
  303. result.append('-analyzer-opt-analyze-headers')
  304. if args.stats:
  305. result.append('-analyzer-checker=debug.Stats')
  306. if args.maxloop:
  307. result.extend(['-analyzer-max-loop', str(args.maxloop)])
  308. if args.output_format:
  309. result.append('-analyzer-output={0}'.format(args.output_format))
  310. if args.analyzer_config:
  311. result.extend(['-analyzer-config', args.analyzer_config])
  312. if args.verbose >= 4:
  313. result.append('-analyzer-display-progress')
  314. if args.plugins:
  315. result.extend(prefix_with('-load', args.plugins))
  316. if args.enable_checker:
  317. checkers = ','.join(args.enable_checker)
  318. result.extend(['-analyzer-checker', checkers])
  319. if args.disable_checker:
  320. checkers = ','.join(args.disable_checker)
  321. result.extend(['-analyzer-disable-checker', checkers])
  322. return prefix_with('-Xclang', result)
  323. def require(required):
  324. """ Decorator for checking the required values in state.
  325. It checks the required attributes in the passed state and stop when
  326. any of those is missing. """
  327. def decorator(function):
  328. @functools.wraps(function)
  329. def wrapper(*args, **kwargs):
  330. for key in required:
  331. if key not in args[0]:
  332. raise KeyError('{0} not passed to {1}'.format(
  333. key, function.__name__))
  334. return function(*args, **kwargs)
  335. return wrapper
  336. return decorator
  337. @require(['command', # entry from compilation database
  338. 'directory', # entry from compilation database
  339. 'file', # entry from compilation database
  340. 'clang', # clang executable name (and path)
  341. 'direct_args', # arguments from command line
  342. 'force_debug', # kill non debug macros
  343. 'output_dir', # where generated report files shall go
  344. 'output_format', # it's 'plist', 'html', both or plist-multi-file
  345. 'output_failures', # generate crash reports or not
  346. 'ctu']) # ctu control options
  347. def run(opts):
  348. """ Entry point to run (or not) static analyzer against a single entry
  349. of the compilation database.
  350. This complex task is decomposed into smaller methods which are calling
  351. each other in chain. If the analyzis is not possible the given method
  352. just return and break the chain.
  353. The passed parameter is a python dictionary. Each method first check
  354. that the needed parameters received. (This is done by the 'require'
  355. decorator. It's like an 'assert' to check the contract between the
  356. caller and the called method.) """
  357. try:
  358. command = opts.pop('command')
  359. command = command if isinstance(command, list) else decode(command)
  360. logging.debug("Run analyzer against '%s'", command)
  361. opts.update(classify_parameters(command))
  362. return arch_check(opts)
  363. except Exception:
  364. logging.error("Problem occurred during analyzis.", exc_info=1)
  365. return None
  366. @require(['clang', 'directory', 'flags', 'file', 'output_dir', 'language',
  367. 'error_output', 'exit_code'])
  368. def report_failure(opts):
  369. """ Create report when analyzer failed.
  370. The major report is the preprocessor output. The output filename generated
  371. randomly. The compiler output also captured into '.stderr.txt' file.
  372. And some more execution context also saved into '.info.txt' file. """
  373. def extension():
  374. """ Generate preprocessor file extension. """
  375. mapping = {'objective-c++': '.mii', 'objective-c': '.mi', 'c++': '.ii'}
  376. return mapping.get(opts['language'], '.i')
  377. def destination():
  378. """ Creates failures directory if not exits yet. """
  379. failures_dir = os.path.join(opts['output_dir'], 'failures')
  380. if not os.path.isdir(failures_dir):
  381. os.makedirs(failures_dir)
  382. return failures_dir
  383. # Classify error type: when Clang terminated by a signal it's a 'Crash'.
  384. # (python subprocess Popen.returncode is negative when child terminated
  385. # by signal.) Everything else is 'Other Error'.
  386. error = 'crash' if opts['exit_code'] < 0 else 'other_error'
  387. # Create preprocessor output file name. (This is blindly following the
  388. # Perl implementation.)
  389. (handle, name) = tempfile.mkstemp(suffix=extension(),
  390. prefix='clang_' + error + '_',
  391. dir=destination())
  392. os.close(handle)
  393. # Execute Clang again, but run the syntax check only.
  394. cwd = opts['directory']
  395. cmd = get_arguments(
  396. [opts['clang'], '-fsyntax-only', '-E'
  397. ] + opts['flags'] + [opts['file'], '-o', name], cwd)
  398. run_command(cmd, cwd=cwd)
  399. # write general information about the crash
  400. with open(name + '.info.txt', 'w') as handle:
  401. handle.write(opts['file'] + os.linesep)
  402. handle.write(error.title().replace('_', ' ') + os.linesep)
  403. handle.write(' '.join(cmd) + os.linesep)
  404. handle.write(' '.join(os.uname()) + os.linesep)
  405. handle.write(get_version(opts['clang']))
  406. handle.close()
  407. # write the captured output too
  408. with open(name + '.stderr.txt', 'w') as handle:
  409. handle.writelines(opts['error_output'])
  410. handle.close()
  411. @require(['clang', 'directory', 'flags', 'direct_args', 'file', 'output_dir',
  412. 'output_format'])
  413. def run_analyzer(opts, continuation=report_failure):
  414. """ It assembles the analysis command line and executes it. Capture the
  415. output of the analysis and returns with it. If failure reports are
  416. requested, it calls the continuation to generate it. """
  417. def target():
  418. """ Creates output file name for reports. """
  419. if opts['output_format'] in {
  420. 'plist',
  421. 'plist-html',
  422. 'plist-multi-file'}:
  423. (handle, name) = tempfile.mkstemp(prefix='report-',
  424. suffix='.plist',
  425. dir=opts['output_dir'])
  426. os.close(handle)
  427. return name
  428. return opts['output_dir']
  429. try:
  430. cwd = opts['directory']
  431. cmd = get_arguments([opts['clang'], '--analyze'] +
  432. opts['direct_args'] + opts['flags'] +
  433. [opts['file'], '-o', target()],
  434. cwd)
  435. output = run_command(cmd, cwd=cwd)
  436. return {'error_output': output, 'exit_code': 0}
  437. except subprocess.CalledProcessError as ex:
  438. result = {'error_output': ex.output, 'exit_code': ex.returncode}
  439. if opts.get('output_failures', False):
  440. opts.update(result)
  441. continuation(opts)
  442. return result
  443. def func_map_list_src_to_ast(func_src_list):
  444. """ Turns textual function map list with source files into a
  445. function map list with ast files. """
  446. func_ast_list = []
  447. for fn_src_txt in func_src_list:
  448. mangled_name, path = fn_src_txt.split(" ", 1)
  449. # Normalize path on windows as well
  450. path = os.path.splitdrive(path)[1]
  451. # Make relative path out of absolute
  452. path = path[1:] if path[0] == os.sep else path
  453. ast_path = os.path.join("ast", path + ".ast")
  454. func_ast_list.append(mangled_name + " " + ast_path)
  455. return func_ast_list
  456. @require(['clang', 'directory', 'flags', 'direct_args', 'file', 'ctu'])
  457. def ctu_collect_phase(opts):
  458. """ Preprocess source by generating all data needed by CTU analysis. """
  459. def generate_ast(triple_arch):
  460. """ Generates ASTs for the current compilation command. """
  461. args = opts['direct_args'] + opts['flags']
  462. ast_joined_path = os.path.join(opts['ctu'].dir, triple_arch, 'ast',
  463. os.path.realpath(opts['file'])[1:] +
  464. '.ast')
  465. ast_path = os.path.abspath(ast_joined_path)
  466. ast_dir = os.path.dirname(ast_path)
  467. if not os.path.isdir(ast_dir):
  468. try:
  469. os.makedirs(ast_dir)
  470. except OSError:
  471. # In case an other process already created it.
  472. pass
  473. ast_command = [opts['clang'], '-emit-ast']
  474. ast_command.extend(args)
  475. ast_command.append('-w')
  476. ast_command.append(opts['file'])
  477. ast_command.append('-o')
  478. ast_command.append(ast_path)
  479. logging.debug("Generating AST using '%s'", ast_command)
  480. run_command(ast_command, cwd=opts['directory'])
  481. def map_functions(triple_arch):
  482. """ Generate function map file for the current source. """
  483. args = opts['direct_args'] + opts['flags']
  484. funcmap_command = [opts['ctu'].func_map_cmd]
  485. funcmap_command.append(opts['file'])
  486. funcmap_command.append('--')
  487. funcmap_command.extend(args)
  488. logging.debug("Generating function map using '%s'", funcmap_command)
  489. func_src_list = run_command(funcmap_command, cwd=opts['directory'])
  490. func_ast_list = func_map_list_src_to_ast(func_src_list)
  491. extern_fns_map_folder = os.path.join(opts['ctu'].dir, triple_arch,
  492. CTU_TEMP_FNMAP_FOLDER)
  493. if not os.path.isdir(extern_fns_map_folder):
  494. try:
  495. os.makedirs(extern_fns_map_folder)
  496. except OSError:
  497. # In case an other process already created it.
  498. pass
  499. if func_ast_list:
  500. with tempfile.NamedTemporaryFile(mode='w',
  501. dir=extern_fns_map_folder,
  502. delete=False) as out_file:
  503. out_file.write("\n".join(func_ast_list) + "\n")
  504. cwd = opts['directory']
  505. cmd = [opts['clang'], '--analyze'] + opts['direct_args'] + opts['flags'] \
  506. + [opts['file']]
  507. triple_arch = get_triple_arch(cmd, cwd)
  508. generate_ast(triple_arch)
  509. map_functions(triple_arch)
  510. @require(['ctu'])
  511. def dispatch_ctu(opts, continuation=run_analyzer):
  512. """ Execute only one phase of 2 phases of CTU if needed. """
  513. ctu_config = opts['ctu']
  514. if ctu_config.collect or ctu_config.analyze:
  515. assert ctu_config.collect != ctu_config.analyze
  516. if ctu_config.collect:
  517. return ctu_collect_phase(opts)
  518. if ctu_config.analyze:
  519. cwd = opts['directory']
  520. cmd = [opts['clang'], '--analyze'] + opts['direct_args'] \
  521. + opts['flags'] + [opts['file']]
  522. triarch = get_triple_arch(cmd, cwd)
  523. ctu_options = ['ctu-dir=' + os.path.join(ctu_config.dir, triarch),
  524. 'experimental-enable-naive-ctu-analysis=true']
  525. analyzer_options = prefix_with('-analyzer-config', ctu_options)
  526. direct_options = prefix_with('-Xanalyzer', analyzer_options)
  527. opts['direct_args'].extend(direct_options)
  528. return continuation(opts)
  529. @require(['flags', 'force_debug'])
  530. def filter_debug_flags(opts, continuation=dispatch_ctu):
  531. """ Filter out nondebug macros when requested. """
  532. if opts.pop('force_debug'):
  533. # lazy implementation just append an undefine macro at the end
  534. opts.update({'flags': opts['flags'] + ['-UNDEBUG']})
  535. return continuation(opts)
  536. @require(['language', 'compiler', 'file', 'flags'])
  537. def language_check(opts, continuation=filter_debug_flags):
  538. """ Find out the language from command line parameters or file name
  539. extension. The decision also influenced by the compiler invocation. """
  540. accepted = frozenset({
  541. 'c', 'c++', 'objective-c', 'objective-c++', 'c-cpp-output',
  542. 'c++-cpp-output', 'objective-c-cpp-output'
  543. })
  544. # language can be given as a parameter...
  545. language = opts.pop('language')
  546. compiler = opts.pop('compiler')
  547. # ... or find out from source file extension
  548. if language is None and compiler is not None:
  549. language = classify_source(opts['file'], compiler == 'c')
  550. if language is None:
  551. logging.debug('skip analysis, language not known')
  552. return None
  553. elif language not in accepted:
  554. logging.debug('skip analysis, language not supported')
  555. return None
  556. else:
  557. logging.debug('analysis, language: %s', language)
  558. opts.update({'language': language,
  559. 'flags': ['-x', language] + opts['flags']})
  560. return continuation(opts)
  561. @require(['arch_list', 'flags'])
  562. def arch_check(opts, continuation=language_check):
  563. """ Do run analyzer through one of the given architectures. """
  564. disabled = frozenset({'ppc', 'ppc64'})
  565. received_list = opts.pop('arch_list')
  566. if received_list:
  567. # filter out disabled architectures and -arch switches
  568. filtered_list = [a for a in received_list if a not in disabled]
  569. if filtered_list:
  570. # There should be only one arch given (or the same multiple
  571. # times). If there are multiple arch are given and are not
  572. # the same, those should not change the pre-processing step.
  573. # But that's the only pass we have before run the analyzer.
  574. current = filtered_list.pop()
  575. logging.debug('analysis, on arch: %s', current)
  576. opts.update({'flags': ['-arch', current] + opts['flags']})
  577. return continuation(opts)
  578. else:
  579. logging.debug('skip analysis, found not supported arch')
  580. return None
  581. else:
  582. logging.debug('analysis, on default arch')
  583. return continuation(opts)
  584. # To have good results from static analyzer certain compiler options shall be
  585. # omitted. The compiler flag filtering only affects the static analyzer run.
  586. #
  587. # Keys are the option name, value number of options to skip
  588. IGNORED_FLAGS = {
  589. '-c': 0, # compile option will be overwritten
  590. '-fsyntax-only': 0, # static analyzer option will be overwritten
  591. '-o': 1, # will set up own output file
  592. # flags below are inherited from the perl implementation.
  593. '-g': 0,
  594. '-save-temps': 0,
  595. '-install_name': 1,
  596. '-exported_symbols_list': 1,
  597. '-current_version': 1,
  598. '-compatibility_version': 1,
  599. '-init': 1,
  600. '-e': 1,
  601. '-seg1addr': 1,
  602. '-bundle_loader': 1,
  603. '-multiply_defined': 1,
  604. '-sectorder': 3,
  605. '--param': 1,
  606. '--serialize-diagnostics': 1
  607. }
  608. def classify_parameters(command):
  609. """ Prepare compiler flags (filters some and add others) and take out
  610. language (-x) and architecture (-arch) flags for future processing. """
  611. result = {
  612. 'flags': [], # the filtered compiler flags
  613. 'arch_list': [], # list of architecture flags
  614. 'language': None, # compilation language, None, if not specified
  615. 'compiler': compiler_language(command) # 'c' or 'c++'
  616. }
  617. # iterate on the compile options
  618. args = iter(command[1:])
  619. for arg in args:
  620. # take arch flags into a separate basket
  621. if arg == '-arch':
  622. result['arch_list'].append(next(args))
  623. # take language
  624. elif arg == '-x':
  625. result['language'] = next(args)
  626. # parameters which looks source file are not flags
  627. elif re.match(r'^[^-].+', arg) and classify_source(arg):
  628. pass
  629. # ignore some flags
  630. elif arg in IGNORED_FLAGS:
  631. count = IGNORED_FLAGS[arg]
  632. for _ in range(count):
  633. next(args)
  634. # we don't care about extra warnings, but we should suppress ones
  635. # that we don't want to see.
  636. elif re.match(r'^-W.+', arg) and not re.match(r'^-Wno-.+', arg):
  637. pass
  638. # and consider everything else as compilation flag.
  639. else:
  640. result['flags'].append(arg)
  641. return result