def capture(args): """ Implementation of compilation database generation. :param args: the parsed and validated command line arguments :return: the exit status of build process. """ with temporary_directory(prefix='intercept-', dir=tempdir()) as tmp_dir: # run the build command environment = setup_environment(args, tmp_dir) exit_code = run_build(args.build, env=environment) # read the intercepted exec calls calls = (parse_exec_trace(file) for file in exec_trace_files(tmp_dir)) current = compilations(calls, args.cc, args.cxx) return exit_code, iter(set(current))
def capture(args): """ Implementation of compilation database generation. :param args: the parsed and validated command line arguments :return: the exit status of build process. """ with temporary_directory(prefix='intercept-', dir=tempdir()) as tmp_dir: # run the build command environment = setup_environment(args, tmp_dir) write_compiler_config(args, tmp_dir) exit_code = run_build(args.build, env=environment) # read the intercepted exec calls calls = (parse_exec_trace(file) for file in exec_trace_files(tmp_dir)) current = compilations(calls, args.cc, args.cxx) return exit_code, iter(set(current))
def capture(args, bin_dir): """ The entry point of build command interception. """ def post_processing(commands): """ To make a compilation database, it needs to filter out commands which are not compiler calls. Needs to find the source file name from the arguments. And do shell escaping on the command. To support incremental builds, it is desired to read elements from an existing compilation database from a previous run. These elemets shall be merged with the new elements. """ # create entries from the current run current = itertools.chain.from_iterable( # creates a sequence of entry generators from an exec, # but filter out non compiler calls before. (format_entry(x) for x in commands if is_compiler_call(x))) # read entries from previous run if 'append' in args and args.append and os.path.exists(args.cdb): with open(args.cdb) as handle: previous = iter(json.load(handle)) else: previous = iter([]) # filter out duplicate entries from both duplicate = duplicate_check(entry_hash) return (entry for entry in itertools.chain(previous, current) if os.path.exists(entry['file']) and not duplicate(entry)) with TemporaryDirectory(prefix='intercept-', dir=tempdir()) as tmp_dir: # run the build command environment = setup_environment(args, tmp_dir, bin_dir) logging.debug('run build in environment: %s', environment) exit_code = subprocess.call(args.build, env=environment) logging.info('build finished with exit code: %d', exit_code) # read the intercepted exec calls commands = itertools.chain.from_iterable( parse_exec_trace(os.path.join(tmp_dir, filename)) for filename in sorted(glob.iglob(os.path.join(tmp_dir, '*.cmd')))) # do post processing only if that was requested if 'raw_entries' not in args or not args.raw_entries: entries = post_processing(commands) else: entries = commands # dump the compilation database with open(args.cdb, 'w+') as handle: json.dump(list(entries), handle, sort_keys=True, indent=4) return exit_code
def capture(args, wrappers_dir): """ The entry point of build command interception. """ def post_processing(commands): # run post processing only if that was requested if 'raw_entries' not in args or not args.raw_entries: # create entries from the current run current = itertools.chain.from_iterable( # creates a sequence of entry generators from an exec, # but filter out non compiler calls before. (format_entry(x) for x in commands if is_compiler_call(x))) # read entries from previous run if 'append' in args and args.append and os.path.exists(args.cdb): with open(args.cdb) as handle: previous = iter(json.load(handle)) else: previous = iter([]) # filter out duplicate entries from both duplicate = duplicate_check(entry_hash) return (entry for entry in itertools.chain(previous, current) if os.path.exists(entry['file']) and not duplicate(entry)) return commands with TemporaryDirectory(prefix='build-intercept', dir=tempdir()) as tmpdir: # run the build command environment = setup_environment(args, tmpdir, wrappers_dir) logging.debug('run build in environment: %s', environment) exit_code = subprocess.call(args.build, env=environment) logging.debug('build finished with exit code: %d', exit_code) # read the intercepted exec calls commands = (parse_exec_trace(os.path.join(tmpdir, filename)) for filename in sorted(os.listdir(tmpdir))) # do post processing entries = post_processing(itertools.chain.from_iterable(commands)) # dump the compilation database with open(args.cdb, 'w+') as handle: json.dump(list(entries), handle, sort_keys=True, indent=4) return exit_code
def create_parser(from_build_command): """ Command line argument parser factory method. """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '--verbose', '-v', action='count', default=0, help="""Enable verbose output from '%(prog)s'. A second and third flag increases verbosity.""") parser.add_argument( '--override-compiler', action='store_true', help="""Always resort to the compiler wrapper even when better interposition methods are available.""") parser.add_argument( '--intercept-first', action='store_true', help="""Run the build commands only, build a compilation database, then run the static analyzer afterwards. Generally speaking it has better coverage on build commands. With '--override-compiler' it use compiler wrapper, but does not run the analyzer till the build is finished. """) parser.add_argument( '--cdb', metavar='<file>', default="compile_commands.json", help="""The JSON compilation database.""") parser.add_argument( '--output', '-o', metavar='<path>', default=tempdir(), help="""Specifies the output directory for analyzer reports. Subdirectory will be created if default directory is targeted. """) parser.add_argument( '--status-bugs', action='store_true', help="""By default, the exit status of '%(prog)s' is the same as the executed build command. Specifying this option causes the exit status of '%(prog)s' to be non zero if it found potential bugs and zero otherwise.""") parser.add_argument( '--html-title', metavar='<title>', help="""Specify the title used on generated HTML pages. If not specified, a default title will be used.""") parser.add_argument( '--analyze-headers', action='store_true', help="""Also analyze functions in #included files. By default, such functions are skipped unless they are called by functions within the main source file.""") format_group = parser.add_mutually_exclusive_group() format_group.add_argument( '--plist', '-plist', dest='output_format', const='plist', default='html', action='store_const', help="""This option outputs the results as a set of .plist files.""") format_group.add_argument( '--plist-html', '-plist-html', dest='output_format', const='plist-html', default='html', action='store_const', help="""This option outputs the results as a set of .html and .plist files.""") # TODO: implement '-view ' advanced = parser.add_argument_group('advanced options') advanced.add_argument( '--keep-empty', action='store_true', help="""Don't remove the build results directory even if no issues were reported.""") advanced.add_argument( '--no-failure-reports', '-no-failure-reports', dest='output_failures', action='store_false', help="""Do not create a 'failures' subdirectory that includes analyzer crash reports and preprocessed source files.""") advanced.add_argument( '--stats', '-stats', action='store_true', help="""Generates visitation statistics for the project being analyzed. """) advanced.add_argument( '--internal-stats', action='store_true', help="""Generate internal analyzer statistics.""") advanced.add_argument( '--maxloop', '-maxloop', metavar='<loop count>', type=int, help="""Specifiy the number of times a block can be visited before giving up. Increase for more comprehensive coverage at a cost of speed.""") advanced.add_argument( '--store', '-store', metavar='<model>', dest='store_model', choices=['region', 'basic'], help="""Specify the store model used by the analyzer. 'region' specifies a field- sensitive store model. 'basic' which is far less precise but can more quickly analyze code. 'basic' was the default store model for checker-0.221 and earlier.""") advanced.add_argument( '--constraints', '-constraints', metavar='<model>', dest='constraints_model', choices=['range', 'basic'], help="""Specify the contraint engine used by the analyzer. Specifying 'basic' uses a simpler, less powerful constraint model used by checker-0.160 and earlier.""") advanced.add_argument( '--use-analyzer', metavar='<path>', dest='clang', default='clang', help="""'%(prog)s' uses the 'clang' executable relative to itself for static analysis. One can override this behavior with this option by using the 'clang' packaged with Xcode (on OS X) or from the PATH.""") advanced.add_argument( '--use-cc', metavar='<path>', dest='cc', default='cc', help="""When '%(prog)s' analyzes a project by interposing a "fake compiler", which executes a real compiler for compilation and do other tasks (to run the static analyzer or just record the compiler invocation). Because of this interposing, '%(prog)s' does not know what compiler your project normally uses. Instead, it simply overrides the CC environment variable, and guesses your default compiler. If you need '%(prog)s' to use a specific compiler for *compilation* then you can use this option to specify a path to that compiler.""") advanced.add_argument( '--use-c++', metavar='<path>', dest='cxx', default='c++', help="""This is the same as "--use-cc" but for C++ code.""") advanced.add_argument( '--analyzer-config', '-analyzer-config', metavar='<options>', help="""Provide options to pass through to the analyzer's -analyzer-config flag. Several options are separated with comma: 'key1=val1,key2=val2' Available options: stable-report-filename=true or false (default) Switch the page naming to: report-<filename>-<function/method name>-<id>.html instead of report-XXXXXX.html""") advanced.add_argument( '--exclude', metavar='<directory>', dest='excludes', action='append', default=[], help="""Do not run static analyzer against files found in this directory. (You can specify this option multiple times.) Could be usefull when project contains 3rd party libraries. The directory path shall be absolute path as file names in the compilation database.""") advanced.add_argument( '--force-analyze-debug-code', dest='force_analyze_debug_code', action='store_true', help="""Tells analyzer to enable assertions in code even if they were disabled during compilation, enabling more precise results.""") plugins = parser.add_argument_group('checker options') plugins.add_argument( '--load-plugin', '-load-plugin', metavar='<plugin library>', dest='plugins', action='append', help="""Loading external checkers using the clang plugin interface.""") plugins.add_argument( '--enable-checker', '-enable-checker', metavar='<checker name>', action=AppendCommaSeparated, help="""Enable specific checker.""") plugins.add_argument( '--disable-checker', '-disable-checker', metavar='<checker name>', action=AppendCommaSeparated, help="""Disable specific checker.""") plugins.add_argument( '--help-checkers', action='store_true', help="""A default group of checkers is run unless explicitly disabled. Exactly which checkers constitute the default group is a function of the operating system in use. These can be printed with this flag.""") plugins.add_argument( '--help-checkers-verbose', action='store_true', help="""Print all available checkers and mark the enabled ones.""") if from_build_command: parser.add_argument( dest='build', nargs=argparse.REMAINDER, help="""Command to run.""") return parser
def create_parser(from_build_command): """ Command line argument parser factory method. """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '--verbose', '-v', action='count', default=0, help="""Enable verbose output from '%(prog)s'. A second and third flag increases verbosity.""") parser.add_argument( '--override-compiler', action='store_true', help="""Always resort to the compiler wrapper even when better interposition methods are available.""") parser.add_argument( '--intercept-first', action='store_true', help="""Run the build commands only, build a compilation database, then run the static analyzer afterwards. Generally speaking it has better coverage on build commands. With '--override-compiler' it use compiler wrapper, but does not run the analyzer till the build is finished. """) parser.add_argument('--cdb', metavar='<file>', default="compile_commands.json", help="""The JSON compilation database.""") parser.add_argument( '--output', '-o', metavar='<path>', default=tempdir(), help="""Specifies the output directory for analyzer reports. Subdirectory will be created if default directory is targeted. """) parser.add_argument( '--status-bugs', action='store_true', help="""By default, the exit status of '%(prog)s' is the same as the executed build command. Specifying this option causes the exit status of '%(prog)s' to be non zero if it found potential bugs and zero otherwise.""") parser.add_argument('--html-title', metavar='<title>', help="""Specify the title used on generated HTML pages. If not specified, a default title will be used.""") parser.add_argument( '--analyze-headers', action='store_true', help="""Also analyze functions in #included files. By default, such functions are skipped unless they are called by functions within the main source file.""") format_group = parser.add_mutually_exclusive_group() format_group.add_argument( '--plist', '-plist', dest='output_format', const='plist', default='html', action='store_const', help="""This option outputs the results as a set of .plist files.""") format_group.add_argument( '--plist-html', '-plist-html', dest='output_format', const='plist-html', default='html', action='store_const', help="""This option outputs the results as a set of .html and .plist files.""") # TODO: implement '-view ' advanced = parser.add_argument_group('advanced options') advanced.add_argument( '--keep-empty', action='store_true', help="""Don't remove the build results directory even if no issues were reported.""") advanced.add_argument( '--no-failure-reports', '-no-failure-reports', dest='output_failures', action='store_false', help="""Do not create a 'failures' subdirectory that includes analyzer crash reports and preprocessed source files.""") advanced.add_argument( '--stats', '-stats', action='store_true', help="""Generates visitation statistics for the project being analyzed. """) advanced.add_argument('--internal-stats', action='store_true', help="""Generate internal analyzer statistics.""") advanced.add_argument( '--maxloop', '-maxloop', metavar='<loop count>', type=int, help="""Specifiy the number of times a block can be visited before giving up. Increase for more comprehensive coverage at a cost of speed.""") advanced.add_argument('--store', '-store', metavar='<model>', dest='store_model', choices=['region', 'basic'], help="""Specify the store model used by the analyzer. 'region' specifies a field- sensitive store model. 'basic' which is far less precise but can more quickly analyze code. 'basic' was the default store model for checker-0.221 and earlier.""") advanced.add_argument( '--constraints', '-constraints', metavar='<model>', dest='constraints_model', choices=['range', 'basic'], help="""Specify the contraint engine used by the analyzer. Specifying 'basic' uses a simpler, less powerful constraint model used by checker-0.160 and earlier.""") advanced.add_argument( '--use-analyzer', metavar='<path>', dest='clang', default='clang', help="""'%(prog)s' uses the 'clang' executable relative to itself for static analysis. One can override this behavior with this option by using the 'clang' packaged with Xcode (on OS X) or from the PATH.""") advanced.add_argument( '--use-cc', metavar='<path>', dest='cc', default='cc', help="""When '%(prog)s' analyzes a project by interposing a "fake compiler", which executes a real compiler for compilation and do other tasks (to run the static analyzer or just record the compiler invocation). Because of this interposing, '%(prog)s' does not know what compiler your project normally uses. Instead, it simply overrides the CC environment variable, and guesses your default compiler. If you need '%(prog)s' to use a specific compiler for *compilation* then you can use this option to specify a path to that compiler.""") advanced.add_argument( '--use-c++', metavar='<path>', dest='cxx', default='c++', help="""This is the same as "--use-cc" but for C++ code.""") advanced.add_argument( '--analyzer-config', '-analyzer-config', metavar='<options>', help="""Provide options to pass through to the analyzer's -analyzer-config flag. Several options are separated with comma: 'key1=val1,key2=val2' Available options: stable-report-filename=true or false (default) Switch the page naming to: report-<filename>-<function/method name>-<id>.html instead of report-XXXXXX.html""") advanced.add_argument( '--exclude', metavar='<directory>', dest='excludes', action='append', default=[], help="""Do not run static analyzer against files found in this directory. (You can specify this option multiple times.) Could be usefull when project contains 3rd party libraries. The directory path shall be absolute path as file names in the compilation database.""") advanced.add_argument( '--force-analyze-debug-code', dest='force_analyze_debug_code', action='store_true', help="""Tells analyzer to enable assertions in code even if they were disabled during compilation, enabling more precise results.""") plugins = parser.add_argument_group('checker options') plugins.add_argument( '--load-plugin', '-load-plugin', metavar='<plugin library>', dest='plugins', action='append', help="""Loading external checkers using the clang plugin interface.""") plugins.add_argument('--enable-checker', '-enable-checker', metavar='<checker name>', action=AppendCommaSeparated, help="""Enable specific checker.""") plugins.add_argument('--disable-checker', '-disable-checker', metavar='<checker name>', action=AppendCommaSeparated, help="""Disable specific checker.""") plugins.add_argument( '--help-checkers', action='store_true', help="""A default group of checkers is run unless explicitly disabled. Exactly which checkers constitute the default group is a function of the operating system in use. These can be printed with this flag.""") plugins.add_argument( '--help-checkers-verbose', action='store_true', help="""Print all available checkers and mark the enabled ones.""") if from_build_command: parser.add_argument(dest='build', nargs=argparse.REMAINDER, help="""Command to run.""") return parser