Customizing the analysis
How to customize your CFamily code analysis.
Language-specific properties
Discover and update the C/C++/Objective-C specific properties in Administration > Configuration > General Settings > Languages > C/C++/Objective-C.
Analyzing test files
The scanner property sonar.tests is utilized to pinpoint the directories that contain test source files. Recognizing these test files aids the analyzers in adjusting their rules accordingly. For instance, analyzers can activate rules specific to tests and deactivate those not applicable in a testing context.
There are no specific rules for tests and no specific support for the analysis of tests, so files specified in sonar.tests are ignored by the C/C++/Objective-C analyzer. If you wish to analyze test files, you should include them in sonar.sources, so that normal rules will be applied to them.
To analyze test source files, you should incorporate them into the sonar.sources scanner property. In that case, please note that the test code is considered part of the overall code and counts toward the license usage.
Quality profiles
Like all other languages supported by SonarQube Server, C, C++, and Objective-C come with the Sonar way profile. This is Sonar’s recommended quality profile, designed to fit most projects.
The Sonar MISRA compliance quality profiles check your code against a set of software development guidelines for the C or C++ programming languages used in safety and mission-critical systems. MISRA guidelines are published by the MISRA (Motor Industry Software Reliability Association) consortium. The standards aim to facilitate code safety, security, portability, and reliability. Read The intelligent approach to achieve MISRA C++:2023 compliance blog post on the Sonar website for more information. These quality profiles are available in Enterprise edition and above. MISRA and MISRA C are the registered trade marks of The MISRA Consortium Limited.
For MISRA projects, consider enabling CTU symbolic execution to improve cross-file analysis depth and reduce false positives.
The Mission critical legacy quality profile is maintained for backward compatibility.
Targeted C++ standard
The analyzer targets a specific version of the C++ language to tune the rules in the activated quality profile. This reporting standard is used to:
Suppress rules that cannot be applied. For example, the rules that suggest using C++20 features while compiling the code with C++17.
Adjust rules’ messages to suggest the proper fix according to the used standard. For example, a rule that suggests using
std::ranges::any_ofwith C++20 will be tuned to suggest usingstd::any_ofwith an older standard.
In Compilation Database mode, the reporting standard defaults to the version used to compile the code. This is ideal for most projects. However, there are some edge cases where there is a need to use a reporting standard different from the compilation standard. For this reason, we provide the following scanner property to adjust the reporting standard:
This property is only recommended for use in cases where a project has to comply with a standard older than the one it is compiled with. This can happen if:
The compiler doesn’t allow setting a specific standard. For example, MSVC doesn’t allow specifying a standard older than C++14.
The project wants to be compiled with the latest standard while still complying with an older one.
In AutoConfig mode, the reporting standard defaults to the latest version. In this case, we recommend setting the property if the project needs to comply with an older standard.
C++20 Modules
Support for C++20 modules is currently experimental and not enabled by default.
Since the analyzer is based on Clang 20, not all features of C++20 modules are supported. For more information, see the official documentation for Clang.
Header units are not currently supported.
The CFamily analyzer needs to know where to find the module units and how to build their corresponding Binary Module Interfaces (BMI). Hence, the Compilation Database must contain the necessary compiler calls for a complete clean build. This is also true for import std. Module units do not need to be indexed by Sonar unless you want them to be analyzed.
Support for this feature is only available through the Sonar Community; commercial support is unavailable.
C++20 Modules are not compatible with CTU symbolic execution.
Use the following scanner property to enable C++20 module support:
There are some aspects to keep in mind when analyzing code with C++20 modules:
The property above will enable module support only for source files compiled with C++20 or later.
Using modules requires building intermediate BMIs, which, by default, will be put under the directory configured by
sonar.working.directory(usually,.sonarscannerunder the project root directory). You must account for some extra space to store these files, which SonarScanner will remove at the end of the analysis.Analysis results and module dependencies are cached, but the intermediate BMIs are not. Hence, when re-analyzing a file, the analyzer will have to build its full tree of dependencies.
AutoConfig-specific properties
While AutoConfig mode automatically deduces the low-level configurations, optionally tuning some high-level configurations can be beneficial to force the analysis of specific project variants and improve its analysis quality. Those high-level configurations can be tuned through settings AutoConfig-specific properties that fall into four categories: custom preprocessor, custom analysis target, custom includes directories, and forcing a C++ language standard.
Set a custom preprocessor to tune which parts of the code are analyzed and which features macros are enabled or disabled.
Set custom targets to tune the size of types and inform the analyzer about the environment the project aims to run on. This can be especially useful for embedded projects with custom architecture.
Set custom includes directories to inform the analyzer about the project’s private dependencies that are not part of the project directory. This can improve the quality of the analysis. By default, AutoConfig can simulate dependencies that are part of the analyzed project codebase and popular public dependencies. Note that the analysis logs contain the list of top missing dependencies.
Override the default C++ language standard if the project needs to comply with a standard other than the latest.
If you’re interested in understanding the context in which your project is analyzed, you can activate a feature that generates a JSON file. This JSON file groups the computed analysis configuration for each analyzed C and C++ file in the project.
You can find more on those settings and how to set them in the project administration settings. From the project homepage, go to Project Settings > General Settings > Languages > C/C++/Objective-C > AutoConfig Analysis Settings.
While it is recommended and easier to set these properties from the UI, they can be set from the scanner side. For example, in sonar-project.properties:
Note that you don’t need to worry about these properties by default. An analysis quality score is computed and printed as part of the analysis log. The score represents the percentage of the Analysis scope that the analyzer understood. A UI warning is raised when the quality score is considered too low, suggesting providing the AutoConfig-specific properties or moving from AutoConfig to Compilation Database mode.
Analysis cache
The C/C++/Objective-C analyzer uses the analysis cache mechanism to perform incremental analysis.
Incremental analysis is activated by default and uses server cache storage. It’s possible to change the cache storage to the local file system.
CTU symbolic execution requires filesystem cache storage. Server-side cache is not supported when CTU is enabled.
You should consider changing the cache storage to the local filesystem when:
The server cache size becomes a concern.
You want to optimize the cache lifecycle based on your project workflow. In particular, if you have long-living pull request branches, you may want to persist the cache for each pull request analysis.
With the filesystem cache, you define a path to the cache. The analyzer loads the cache provided in this directory at the beginning of the analysis and overwrites it at the end. Persisting this directory at the end of the analysis, and loading the cache of the most relevant analysis at the beginning becomes the responsibility of the CI configuration. For example, for the first analysis of a pull request branch, a good option is usually to load the target branch cache to the location of the pull request branch analysis cache.
Be aware that the setup of a filesystem cache is complicated since you must implement the cache lifecycle management logic in your CI configuration.
To configure the filesystem cache:
Set the
sonar.cfamily.analysisCache.modeproperty tofs(filesystem) on your CI/CD host (the default value isserverfor server-side cache). See the corresponding SonarScanner section for more information about the setup methods.To set the path to the cache, use the
sonar.cfamily.analysisCache.pathproperty in your CI process configuration.
Incremental symbolic execution
The analyzer provides an incremental symbolic execution mode that incrementally updates the analysis results computed for the rules with a symbolic-execution tag (see Understanding the analysis > Implementation-related rule tags). It may be used to shorten the analysis.
Incremental symbolic execution is enabled by default. It acts as an additional layer on top of the analysis cache (see section above) and uses the same storage to maintain the required information as selected for the analysis cache (server cache or local file system).
In contrast to the analysis cache, incremental symbolic execution detects code changes on an intra-file level rather than treating a file and its dependencies as a whole. This allows it to skip parts of the analysis or to reuse parts of the previous analysis results that are still valid even in cases where a file or its dependencies did undergo edits.
To toggle the incremental symbolic execution mode, set the sonar.cfamily.symbolicExecution.useIncrementalMode property to true or false at the scanner level.
When analyzing several code variants yet (see section below), incremental symbolic execution cannot be used and is automatically disabled.
When CTU symbolic execution is enabled, incremental symbolic execution is automatically disabled and replaced by file-level granularity for cache replay.
Cross-Translation-Unit (CTU) symbolic execution
This feature is currently in beta. Efficiency, resource requirements, and compatibility are likely to change significantly upon general availability (GA).
Some advanced bugs require context from multiple C or C++ files to detect. The default analysis considers each translation unit (a file with all included headers) in isolation and cannot detect such issues. It might also make assumptions about other files that lead to false positives.
CTU symbolic execution enables the analyzer to look across file boundaries and be aware of definitions elsewhere in the project. The analyzer can reason more accurately about functions it encounters and discover faulty scenarios that span multiple implementation files.
This deeper-analysis capability comes with increased resource use: CTU requires more disk space for temporary files (also impacting the cache size), needs more RAM to hold the additional context, and takes longer to complete.
CTU is recommended for projects using the Sonar MISRA compliance quality profiles, as cross-file analysis improves detection accuracy for safety-critical code.
Prerequisites
Disk: Provision an additional ~30 MB of disk space per source file. You can bound disk use at the expense of analysis depth; see Disk space quota.
RAM: Provision 4 GB per thread for a C++ project and 2 GB per thread for a C project. You might need to reduce parallelism if you observe out-of-memory failures. Set Memory-pressure bound to avoid unclear failures in cases of insufficient memory.
Analysis time: Expect an increase. Most of analysis times grow between 10% and a factor of 2.2x.
Incompatible features
Beta version of CTU symbolic execution is not compatible with the following features:
PCH-optimized analysis: Analysis still runs, but it does not use the PCH configured for your build to optimize parsing time.
Server-side analysis cache: CTU analysis requires caching large amounts of internal representation that surpass the expected load for server-side cache. Filesystem cache is supported.
Incremental symbolic execution: With CTU activated, the analyzer automatically switches to file-level granularity for cache replay, reanalyzing entire files and their dependents if they change.
SonarQube for IDE does not support CTU mode. CTU mode in combination with Objective-C code is provided on a best-effort basis.
Configuration
Dedicated CTU analysis branch
CTU requires significantly more time and resources and is not convenient to run for every commit or PR CI build. At the same time, SonarQube does not support issue continuity across analyses of varying depth for the same branch. Use the branchSubstring setting to enable CTU on every analysis for select branches.
If sonar.cfamily.experimental.ctuAnalysis.branchSubstring is set, analysis runs in CTU mode when the current branch name contains the given substring:
Disk space quota
To bound disk usage during analysis, set sonar.cfamily.experimental.ctuAnalysis.diskQuotaMb to the maximum amount of temporary disk space (in MB) allowed for CTU analysis. This comes on top of regular analysis disk usage. Most CTU analysis temporary data is also cached, so you can use this property to control the extra space CTU uses in the cache. We recommend provisioning 30 MB or more per analyzed C or C++ file:
If the disk-space quota prevents the analyzer from maintaining some context, leading to poorer analysis quality, you get a warning both in the SonarQube UI and in the analysis log. Even "partial" CTU analysis (with some context files discarded due to the quota) has higher quality than non-CTU analysis.
To silence this warning:
Memory-pressure bound
In some cases, the analyzer might take an unexpectedly large amount of memory, stifling the system and leading to swapping-to-disk or confusing failures. Configure a reasonably high threshold on system memory pressure (as a percentage of total system memory used by all running processes):
If the threshold is set and reached, the analysis fails with a clear message.
Note that Taint Analysis employs a different and independent mechanism to limit memory pressure.
Parallel code scan
By default, the analyzer tries to parallelize the analysis of compilation units; it spawns as many jobs as the machine’s logical CPUs allow.
If required, the number of scheduled parallel jobs can be customized by configuring the property sonar.cfamily.threads=n at the scanner level, where n is an integer indicating the maximum number of parallel jobs.
You should consider setting the sonar.cfamily.threads property only when the desired number of logical CPUs cannot be detected automatically. A typical example is when the analysis should not consume all the available computing resources to leave room for other tasks running in parallel on the same machine.
When setting the sonar.cfamily.threads property, you should set it to a value less or equal to the number of logical CPUs available. Over-committing doesn’t accelerate the analysis and can even slow it down.
Analyzing several code variants
In Compilation Database mode, you can analyze different variants of the very same version of your code (different target architectures, different build options, etc) and see aggregated results on the server. All variants are analyzed in the same environment and during the same analysis. We do not support analyzing two variants requiring the code to be built on two different machines.
You should define two properties:
sonar.cfamily.variants.names, which contains a comma-separated list of the names of all the variants that need to be analyzed.sonar.cfamily.variants.dir, which contains a path to a folder with one subfolder per variant. Each subfolder should contain acompile_commands.jsonfile.
These properties are mutually exclusive with sonar.cfamily.compile-commands.
The following example defines three variants:
And the folder structure should look like this:
Data from all variants will usually be aggregated when analyzing code for several variants. For instance, a particular issue was present in the previous configuration in Linux ARM and Linux ARM64 but not in Linux x64.
Automatic shallow mode for advanced bug detection
For large files that take a long time to analyze, you can activate Automatic Shallow Mode, which trades a potentially lower bug detection rate for a faster analysis time.
To activate shallow mode on files with more than N entry points set the property sonar.cfamily.symbolicExecution.automaticShallowModeThreshold=N. An entry point is essentially a (member-) function declaration with a body. The analyzer begins its work at every function declared with a body, so a file containing many entry points will require a longer analysis time.
By default sonar.cfamily.symbolicExecution.automaticShallowModeThreshold=0 which means this feature is disabled.
If you are willing to reduce the bug detection rate in order to reduce analysis time, we recommend setting it to 70 entry points. Choosing a lower, non-zero value for N will reduce analysis depth on more files and will make the analysis even faster. Choosing a higher value for N restricts shallow mode only to the largest files, minimizing the impact on small and medium files.
Taint analysis (beta)
The analyzer provides a taint analysis implementation that aims at identifying security-related issues for common, critical CWE-classified vulnerabilities.
About the feature
Taint analysis tracks untrusted data (taint) from sources (user input, external APIs) to sensitive sinks (system calls, database queries, etc.) and reports an issue if it detects such an undesired flow. The analyzer tracks how data generated by a source flows through your code. It detects when data that is potentially manipulated by a malicious user reaches a sensitive piece of code where an attack might occur. This potentially malicious data is also called tainted data because it's tainted by user inputs.
Taint analysis rules
The rules used for taint analysis are tagged with a taint-analysis tag. Rule examples:
S2076: OS commands should not be vulnerable to command injection attacks
S2083: I/O function calls should not be vulnerable to path injection attacks
For more information, see Understanding the analysis.
Default configuration
Taint analysis runs automatically if your quality profile includes rules tagged with a taint-analysis tag.
Our analyzer comes with a comprehensive default configuration for commonly used sources and sinks. However, you can specify additional sources and sinks as well as sanitizers.
See Specifying a custom configuration below for more information.
Taint analysis skips if quality index is low
Running the taint analysis requires the project under analysis to compile successfully. The analyzer computes a quality index based on how much of the code it managed to compile. If this index is too low, the taint analysis won't run. A warning will be logged detailing the issue.
Limitations
The following features are currently incompatible with taint analysis and hence, may not be used when running taint analysis:
Automatic configuration (AutoConfig) mode
Analyzing several code variants
C++20 modules
SonarLint analysis
If taint analysis detects that any of the above features is enabled, it will automatically disable taint analysis.
Beyond these feature incompatibilities, there are additional constraints on what the taint analysis can process. First, taint analysis cannot process non-8-bit character targets such as the AVR target architecture because the compiler backend is unable to generate the required intermediate representation for such targets.
Second, taint analysis can only find taint flows in code that is available for analysis and compiles successfully. In particular, the analysis will not see files that are excluded from the analysis or other unavailable third-party code.
Finally, due to aliasing and pointer arithmetic, it may happen that our analyzer raises issues for rules tagged with taint-analysis, even if you apply correct sanitization to a user-controlled, tainted value. In that case, ensure that sanitization is correct and complete, and then mark the issue as False Positive. We are continuously improving on our taint analysis' pointer analysis to mitigate these situations to the extent possible.
Disabling the taint analysis
To explicitly disable taint analysis, set the sonar.cfamily.taintAnalysis property to false.
Defining resource limits to avoid overtainting
Taint analysis can be resource-intensive because it operates on the whole program and builds a complex model of the code. When it runs into a situation that the literature describes as "over-tainting" or "taint explosion", the analysis will consume excessive resources (time and memory) while exploring only limited new parts of the program. To prevent the analysis from getting stuck, you can set resource limits using the following properties:
sonar.cfamily.taintAnalysis.timeout: Sets a time limit in milliseconds. (Set to 0 or omit for no time limit.)sonar.cfamily.taintAnalysis.dataflowMemoryLimit: Sets a memory limit in bytes. (Set to 0 for the analyzer to automatically determine a suitable memory limit.)
Whenever a limit is reached, the taint analysis will be stopped early, but all of its findings up to that point will be reported. Still, the more resources given to the taint analysis, the deeper it can analyze the target program. Should explicit time and memory constraints not be defined, the analyzer will attempt to automatically determine appropriate limits.
Specifying a custom configuration
Customize the taint configuration by adding your own sources, sinks, and sanitizers.
To customize the taint analysis performed by the CFamily analyzer:
Provide a custom taint analysis configuration file in JSON format. See below.
Set the path (relative to the project base dir or absolute) to this JSON configuration file through the
sonar.cfamily.taintAnalysis.taintConfigproperty.
About the customization
The analyzer already knows a lot of APIs that are potential sources or targets of an attack. While we do our best to identify publicly available APIs, we can't know everything about your homemade frameworks particularly when it comes to sanitizing your data. A sanitizer is a function whose invocation sanitizes ("un-taints") data. After a piece of data has been sanitized it will no longer be tracked by the analysis and can be safely passed to a sensitive sink function.
For example, you may wish to:
Add a source to add support for a framework that our analyzer does not cover out of the box.
Use a custom sanitizer to tell the analysis that all data going through that sanitizer shall be considered safe. This allows you to remove false positives and tailor the taint analysis to your company's needs.
Custom taint analysis configuration file
Through customization, you add an element (source, sink, or sanitizer):
To a specific rule or to all rules.
For one or several methodIds.
Element
You can add the following elements to your custom configuration:
Source (key:
sources): Where you get user data. You should always consider user data tainted and vulnerable to injection attacks. Example: Callingscanfwill generate tainted content.Sink (key:
sinks): A piece of code that can perform a security-sensitive task. Data should not contain any malicious content once it reaches a sink. Example: Callingexeclwith unchecked user data.Sanitizer (key:
sanitizers): Finds and removes malicious content from one or more potentially tainted arguments.
Rule
A rule is identified by its number, for example S2076. Use the special rule key common to apply the given configuration to all rules.
MethodId
All custom configurations rely on the accuracy of the provided methodId. You can either specify a full methodId as a string or use a regular expression, which may be useful for specifying class or function templates as well as overload sets in C++.
File example
An exemplary configuration is shown in the following to help you understand the expected format.
This configuration tells the analyzer that the getPassword and getPassword() functions' return values shall be considered tainted across all taint-based rules. To identify a function in the C programming language, use its symbol name (getPassword). To identify a function in C++, a function's name and its parameter list must be specified to disambiguate static function overloads (getPassword()).
The C function executeCommand and the C++ functions whose name matches the regular expression execute\\(.*\\) as well as the C++ logMessage(char const*) function shall be considered sinks for rule S2076. When specifying methodIds using regular expressions ("isRegex": true), metacharacters need to be escaped with two backslashes (\\). If the analysis discovers that a tainted value is passed as the first parameter to executeCommand, it will report a security issue. If any of its potentially many parameters receives tainted data, any function matching execute\\(.*\\) will be considered a security leak, and an issue will be reported. Note that C++'s parameter lists use "east const" and & and * are not space-separated, e.g. logMessage(char const*).
The configuration also specifies the C function verifyCommand to be a sanitizer that sanitizes (or "un-taints") its first parameter, which tells the analyzer that a tainted piece of data that is passed as the first parameter will no longer be tracked as it is considered safe to use after sanitization.
Last updated
Was this helpful?

