JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.

If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.

If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.

CodeSonar® 9.2p0 CONFIDENTIAL CodeSecure Inc
C#

Build and Analysis for C# Projects [Windows only]

The CodeSonar build of a C# project is performed after the normal build. It uses both the C# source files and the files produced by the build. This is significantly different from the way in which CodeSonar builds a C/C++ project, which involves observing the actual normal-build process. For a C# project, the CodeSonar build collects the C# bytecode files produced by a normal build, along with the corresponding C# source code for any parts of the project for which warnings are required. The bytecode files are then analyzed, and analysis results are sent to a hub database, from which they can be viewed with an ordinary web browser.

The CodeSonar C# build/analysis can only be applied to code that is both managed and safe.

Incrementality is not supported for C#: C#-only projects (and the C# parts of mixed projects) will always be completely rebuilt and reanalyzed when you perform a CodeSonar analysis.

Important Note: CodeSonar will only report warnings for those parts of the project for which both of the following are true.

In most cases, the corresponding source code must also be available. If the associated PDB files do not provide correct source file paths, specify the paths with -include-sources.

An overview and further links about building and analyzing CodeSonar projects from software in other languages are provided in section Building.

CodeSonar C# analysis is available on 64-bit Windows only, and .NET Framework 4.7.2 or later must be installed on the machine performing the analysis.

The CodeSonar C# analysis is suitable for analyzing the following .NET versions.


How The C# Build Works

The following diagram shows the CodeSonar build and analysis process for C# projects.

Diagram: build hooking

The steps of the build and analysis process are described in Building: Overview. For projects based on C# code, the steps manifest as follows.

1. Observe The user instructs CodeSonar to observe an operation or collection of operations that includes one or more invocations of the form
cs-dotnet-scan -include-artifacts pattern [remaining-options]
or
cs-dotnet-scan -include-sourceless-artifacts pattern [remaining-options]
or
cs-dotnet-scan -msbuild-solution slnpathname -msbuild-location mspath [remaining-options]
  • cs-dotnet-scan itself is a null function: its only purpose is to be recognized by CodeSonar so that the C# bytecode and source files it specifies can be incorporated into the project.
  • In many cases it is most straightforward to pass the cs-dotnet-scan invocation directly to the CodeSonar command line. However, you may find it more convenient to modify your regular build system to call cs-dotnet-scan on the relevant outputs after the build takes place, then have CodeSonar observe the entire build process. Note that this approach provides only convenience, not additional project information: the C# components of the CodeSonar project will still be based only on the invocations of cs-dotnet-scan.
  • If possible, compile the C# source with debugging information. Without this information, CodeSonar will sometimes be unable to correctly derive the source location that corresponds to a problem detected in the bytecode. When this happens, a warning will be issued at an incorrect location within the correct class.
2. Execute The designated operation or operations are executed.

Important: Only invocations of cs-dotnet-scan that take place during this execution will be represented in the project.

3. Recognize CodeSonar will recognize invocations of cs-dotnet-scan.
4. Update Each time it recognizes an invocation of cs-dotnet-scan, CodeSonar updates the project definition to incorporate the files specified by that invocation.

The files included in the project can be divided into sources (.cs files), artifacts (.exe, .dll, .properties, sarl, and .xml files), and PDB files (.pdb).

  • Artifacts can be further categorized, in decreasing order of importance, as (ordinary) artifacts, sourceless artifacts, libraries, and signatures.
    • Ordinary artifacts will be fully analyzed by the analysis engine, and it is assumed that the sources are available for the purpose of presenting warnings to the user.
    • Sourceless artifacts are the same as ordinary artifacts, with the following exception: if one or more sourceless artifacts are present, the analysis will proceed even if one or more ordinary or sourceless artifacts has no source available.
    • Libraries are artifacts that are only partially analyzed by the analysis engine, to support the analysis of other artifacts.
    • Signatures are artifacts which are only examined to collect type information for methods and classes, to support the analysis of other artifacts.
  • For each cs-dotnet-scan invocation, CodeSonar determines the files to add to the project as follows.
    cs-dotnet-scan -msbuild-solution slnfile [...] CodeSonar parses slnfile to identify the sources, artifacts, and PDB files.
    cs-dotnet-scan -include-artifacts pattern [...]
    cs-dotnet-scan -include-sourceless-artifacts pattern [...]
    CodeSonar uses the sequence of include and exclude options to extend and refine the sets of artifacts and sources to include in the project.
    The artifact category for each artifact is determined by the include option used to include it.
  • For each artifact in the project, the C# analysis expects to find a corresponding PDB file in the same directory. If there is no such PDB file, the analysis will issue an alert.

Once it has finished building the project, CodeSonar can run the analysis. If you use the analyze command, the analysis will run (and send its results to the hub) after the build has finished.

The degree of parallelism in the analysis will depend on the setting of ANALYSIS_SLAVES. Additional parallelism can be achieved by executing multiple cs-dotnet-scan commands in parallel for various smaller pieces of a project.

Managed, Safe Code Only

The CodeSonar C# build/analysis can only be applied to code that is both managed and safe. It will not understand native code, including "unsafe" C# code, or account for its effects.

When you invoke cs-dotnet-scan, do not include any artifacts with native or unmanaged code. In some cases you may need to use a combination of include options and exclude options to accomplish this. Example 13, below, illustrates one such case.

If your C# analysis includes one or more components (for example, classes) written in native or unmanaged code, the analysis will issue a Native Component alert.
See the troubleshooting notes below for more information.

Command Line Build

As described in Command Line Build/Analysis: Command, the general form of the usual CodeSonar build/analysis command is

codesonar analyze /path/to/pfiles-name
[-project [/[ancestors/]]proj-name] [-no-services] [-foreground] [-wait] [-clean] [-clean-backend] \
[-force-base-hub-analysis] [-name analysis-name] [-preset preset-name] [-no-default-presets] [-conf-file extra-conf-path] \
[-offline] [-property propkey propval] [-launchd-group ldgroup] [-launchd-key ldkey] \
[-watch-pid pid] [-watch-all-pids] \
[-auth authtype] [-hubuser username] [-hubpwfile pwfile] [-hubbearerfile bearerfile] [-hubcert certfile] [-hubkey privatekeyfile] \
[-remote analysis-launchd] [-remote-archive daemonmode-launchd] [-srcroot basedir] [[protocol://]host:port] [command]

The command element is described below; the other parts of the command line are discussed in Command Line Build/Analysis: Elements.

command

To build a C# project, CodeSonar observes the execution of a command of one of the following forms.

cs-dotnet-scan[.exe] -include-artifacts pattern [remaining-options]
cs-dotnet-scan[.exe] -include-sourceless-artifacts pattern [remaining-options]
cs-dotnet-scan[.exe] -msbuild-solution slnpathname -msbuild-location mspath [remaining-options]

There are therefore three general forms of the CodeSonar build/analysis command for C# projects:

codesonar analyze /path/to/pfiles-name
[-project [/[ancestors/]]proj-name] [-no-services] [-foreground] [-wait] [-clean] [-clean-backend] \
[-force-base-hub-analysis] [-name analysis-name] [-preset preset-name] [-no-default-presets] [-conf-file extra-conf-path] \
[-offline] [-property propkey propval] [-launchd-group ldgroup] [-launchd-key ldkey] \
[-watch-pid pid] [-watch-all-pids] \
[-auth authtype] [-hubuser username] [-hubpwfile pwfile] [-hubbearerfile bearerfile] [-hubcert certfile] [-hubkey privatekeyfile] \
[-remote analysis-launchd] [-remote-archive daemonmode-launchd] [-srcroot basedir] [[protocol://]host:port] cs-dotnet-scan[.exe] -include-artifacts pattern [remaining-options]
codesonar analyze /path/to/pfiles-name
[-project [/[ancestors/]]proj-name] [-no-services] [-foreground] [-wait] [-clean] [-clean-backend] \
[-force-base-hub-analysis] [-name analysis-name] [-preset preset-name] [-no-default-presets] [-conf-file extra-conf-path] \
[-offline] [-property propkey propval] [-launchd-group ldgroup] [-launchd-key ldkey] \
[-watch-pid pid] [-watch-all-pids] \
[-auth authtype] [-hubuser username] [-hubpwfile pwfile] [-hubbearerfile bearerfile] [-hubcert certfile] [-hubkey privatekeyfile] \
[-remote analysis-launchd] [-remote-archive daemonmode-launchd] [-srcroot basedir] [[protocol://]host:port] cs-dotnet-scan[.exe] -include-sourceless-artifacts pattern [remaining-options]
codesonar analyze /path/to/pfiles-name
[-project [/[ancestors/]]proj-name] [-no-services] [-foreground] [-wait] [-clean] [-clean-backend] \
[-force-base-hub-analysis] [-name analysis-name] [-preset preset-name] [-no-default-presets] [-conf-file extra-conf-path] \
[-offline] [-property propkey propval] [-launchd-group ldgroup] [-launchd-key ldkey] \
[-watch-pid pid] [-watch-all-pids] \
[-auth authtype] [-hubuser username] [-hubpwfile pwfile] [-hubbearerfile bearerfile] [-hubcert certfile] [-hubkey privatekeyfile] \
[-remote analysis-launchd] [-remote-archive daemonmode-launchd] [-srcroot basedir] [[protocol://]host:port] cs-dotnet-scan[.exe] -msbuild-solution slnpathname -msbuild-location mspath [remaining-options]

where remaining-options is any combination of include options, exclude options, and other options.

Patterns

Wildcard patterns follow the rules of the Glob library. In particular:

A pattern that matches a directory is considered to match all files with appropriate suffixes that are located in that directory or any of its (recursive) subdirectories. Suffixes are as follows.

C# Build Options

This section describes the available options for cs-dotnet-scan, all of which can be added using configuration file settings.

As described above, there are three general forms of the CodeSonar build/analysis command for C# projects.

codesonar analyze /path/to/pfiles-name
[-project [/[ancestors/]]proj-name] [-no-services] [-foreground] [-wait] [-clean] [-clean-backend] \
[-force-base-hub-analysis] [-name analysis-name] [-preset preset-name] [-no-default-presets] [-conf-file extra-conf-path] \
[-offline] [-property propkey propval] [-launchd-group ldgroup] [-launchd-key ldkey] \
[-watch-pid pid] [-watch-all-pids] \
[-auth authtype] [-hubuser username] [-hubpwfile pwfile] [-hubbearerfile bearerfile] [-hubcert certfile] [-hubkey privatekeyfile] \
[-remote analysis-launchd] [-remote-archive daemonmode-launchd] [-srcroot basedir] [[protocol://]host:port] cs-dotnet-scan[.exe] -include-artifacts pattern [remaining-options]
codesonar analyze /path/to/pfiles-name
[-project [/[ancestors/]]proj-name] [-no-services] [-foreground] [-wait] [-clean] [-clean-backend] \
[-force-base-hub-analysis] [-name analysis-name] [-preset preset-name] [-no-default-presets] [-conf-file extra-conf-path] \
[-offline] [-property propkey propval] [-launchd-group ldgroup] [-launchd-key ldkey] \
[-watch-pid pid] [-watch-all-pids] \
[-auth authtype] [-hubuser username] [-hubpwfile pwfile] [-hubbearerfile bearerfile] [-hubcert certfile] [-hubkey privatekeyfile] \
[-remote analysis-launchd] [-remote-archive daemonmode-launchd] [-srcroot basedir] [[protocol://]host:port] cs-dotnet-scan[.exe] -include-sourceless-artifacts pattern [remaining-options]
codesonar analyze /path/to/pfiles-name
[-project [/[ancestors/]]proj-name] [-no-services] [-foreground] [-wait] [-clean] [-clean-backend] \
[-force-base-hub-analysis] [-name analysis-name] [-preset preset-name] [-no-default-presets] [-conf-file extra-conf-path] \
[-offline] [-property propkey propval] [-launchd-group ldgroup] [-launchd-key ldkey] \
[-watch-pid pid] [-watch-all-pids] \
[-auth authtype] [-hubuser username] [-hubpwfile pwfile] [-hubbearerfile bearerfile] [-hubcert certfile] [-hubkey privatekeyfile] \
[-remote analysis-launchd] [-remote-archive daemonmode-launchd] [-srcroot basedir] [[protocol://]host:port] cs-dotnet-scan[.exe] -msbuild-solution slnpathname -msbuild-location mspath [remaining-options]

Where remaining-options is any combination of include options, exclude options, and other options.

The relative ordering of include and exclude options is important:

Specifying C# Build Options

You can specify C# build options using the following configuration file parameters as an alternative to specifying them directly in the command line.

CSHARP_FLAGS_APPEND Specifies options to append to the list passed to the C# build/analysis command.
CSHARP_FLAGS_PREPEND Specifies options to prepend to the list passed to the C# build/analysis command.

Specifying Files for Analysis

There are two mechanisms for specifying inputs to the analysis in a cs-dotnet-scan command:

In most cases, each cs-dotnet-scan command will only use one or the other of these mechanisms. However, it is possible to use both. The following diagram illustrates the handling for the various specified inputs in each case. For more information on individual command line options, see Options, below.

Diagram: specifying analysis inputs with -msbuild-solution, with input/output options, or both. Text describing this behavior is provided in the documentation for -msbuild-solution

Options

The following table lists all options understood by cs-dotnet-scan.

Option Default Value Description Can Specify More Than Once?

 

Specifying an MSBuild Solution File

-msbuild-solution <slnpathname> none CodeSonar will parse the solution file (.sln) located at <slnpathname> and add identified elements to the project as follows.
  • There must be an available MSBuild or Visual Studio (2017 v15.9 or later) installation. CodeSonar will use this installation to parse the solution file.
    This option cannot be used with earlier versions of Visual Studio 2017, or with Visual Studio 2015 or earlier.
  • If -msbuild-project is specified one or more times, the analysis is limited to the identified Visual Studio projects. Otherwise, all projects in the solution are analyzed.
  • Details of the parsing process are controlled by options -msbuild-location, -msbuild-os-target, and -msbuild-property.
  • All .exe and .dll files in the identified project output directory or directories are added to the CodeSonar project as ordinary artifacts.
  • Their corresponding PDB files are also added to the CodeSonar project.
  • The source files associated with the identified ordinary artifacts must also be in the solution.

IMPORTANT: If you have modified the project or source files, rebuild the project before invoking cs-dotnet-scan.

Use the following options to supply further information.

  • -msbuild-location : the MSBuild or VisualStudio installation to use for parsing the .sln file.
  • -msbuild-property : the property settings that were used to build the project.
  • -framework : the target framework to analyze. Specify this whenever your solution contains one or more projects with multiple target frameworks.
  • -msbuild-os-target : the os-specific project target framework to analyze. Specify this whenever your solution contains one or more projects with multiple target frameworks and these include os-specific target frameworks.

We strongly recommend using -msbuild-project in preference to include and exclude options when you wish to analyze only some projects in the solution.
If you do specify include and exclude options in the same cs-dotnet-scan invocation, they are handled as follows.

yes
-msbuild-location <mspath> -msbuild-location must be specified when -msbuild-solution is specified If -msbuild-solution is specified, CodeSonar will use the MSBuild or Visual Studio installation at <mspath> to parse the specified solution file and identify artifacts and PDB files to add to the project.

<mspath> must be one of the following.

  • [Recommended] A Visual Studio root path. For example,
    C:\Program Files\Microsoft Visual Studio\2022\Professional
  • The path to the top-level Bin directory of an MSBuild installation. For example,
    C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin Note that MSBuild must be installed as part of a Visual Studio installation.

-msbuild-solution can only be used with Visual Studio 2017 v15.9 and later. If the installation at <mspath> is an older version, the build/analysis will fail

If -msbuild-solution is not specified, this option has no effect.

no
-msbuild-project <projpath> All projects in the solution are analyzed. If -msbuild-solution is specified, CodeSonar will analyze only the (Visual Studio) project whose project file (.csproj) is located at <projpath>, rather than all projects in the solution.

If <projpath> does not exist, the build/analysis will fail.

If this option is specified multiple times, all the identified projects are analyzed and all other projects in the solution are not.

If -msbuild-solution is not specified, this option has no effect.

YES

Include Options

These specify files to include in the CodeSonar project.
-include-sources <pattern> none The project should include all source files (.cs) whose filename matches <pattern>.

This supersedes any previous exclusion of any of these files with -exclude-sources, but may in turn be superseded by a subsequent occurrence of -exclude-sources.

Source files are not analyzed directly. Instead, they are used to present the warnings identified in the bytecode files specified with -include-artifacts.

If the PDB files corresponding to your specified artifacts provide accurate source file paths, you do not need to specify any -include-sources options.

yes
-include-artifacts <pattern> none The project should include all ordinary artifacts whose filename matches <pattern>, along with their corresponding PDB files.

This supersedes any previous exclusion of any of these files with -exclude-artifacts, but may in turn be superseded by a subsequent occurrence of -exclude-artifacts.

The source code corresponding to an ordinary artifact must also be available and specified with -include-sources or in PDB files, unless one or more sourceless artifacts are also specified.

yes
-include-sourceless-artifacts <pattern> none The project should include all sourceless artifacts whose filename matches <pattern>, along with their corresponding PDB files.

This supersedes any previous exclusion of any of these files with -exclude-sourceless-artifacts, but may in turn be superseded by a subsequent occurrence of -exclude-sourceless-artifacts.

yes
-include-libraries <pattern> none The project should include all libraries whose filename matches <pattern>, along with their corresponding PDB files.

This supersedes any previous exclusion of any of these files with -exclude-libraries, but may in turn be superseded by a subsequent occurrence of -exclude-libraries.

yes
-include-signatures <pattern> none The project should include all signatures from all artifacts whose filename matches <pattern>, along with their corresponding PDB files.

This supersedes any previous exclusion of any of these files with -exclude-signatures, but may in turn be superseded by a subsequent occurrence of -exclude-signatures.

yes

Exclude Options

These specify previously-included files that should be excluded from the CodeSonar project.
-exclude-sources <pattern> none Removes all files whose filename matches <pattern> from the set of source files (.cs) accumulated by earlier occurrences of -include-sources in the cs-dotnet-scan command.

Some or all of these source files may be added back by subsequent occurrences of -include-sources.

yes
-exclude-artifacts <pattern> none Removes all files whose filename matches <pattern> from the set of ordinary artifacts accumulated by earlier occurrences of -include-artifacts in the cs-dotnet-scan command.

Some or all of these ordinary artifacts may be added back by subsequent occurrences of -include-artifacts.

yes
-exclude-sourceless-artifacts <pattern> none Removes all files whose filename matches <pattern> from the set of sourceless artifacts accumulated by earlier occurrences of -include-sourceless-artifacts in the cs-dotnet-scan command.

Some or all of these sourceless artifacts may be added back by subsequent occurrences of -include-sourceless-artifacts.

yes
-exclude-libraries <pattern> none Removes all files whose filename matches <pattern> from the set of libraries accumulated by earlier occurrences of -include-libraries in the cs-dotnet-scan command.

Some or all of these libraries may be added back by subsequent occurrences of -include-libraries.

yes
-exclude-signatures <pattern> none Removes all files whose filename matches <pattern> from the set of signatures accumulated by earlier occurrences of -include-signatures in the cs-dotnet-scan command.

Some or all of these ordinary artifacts may be added back by subsequent occurrences of -include-signatures.

yes

Other Options

These control other aspects of the C# analysis.
Note that values specified on the command line take precedence over values set with a configuration file option.
-assembly-kind <akind> ConsoleApplication Specifies the kind of assembly for all assemblies specified with -include-artifacts. The possible values of <akind> are those of the Microsoft.CodeAnalysis.OutputKind enumeration: {ConsoleApplication, DynamicallyLinkedLibrary, NetModule, WindowsApplication, WindowsRuntimeApplication, WindowsRuntimeMetadata}.

This is analogous to the OutputType property used in Visual Studio .csproj files, and to the TargetType option of CSC.

no
-cs-verbosity <level> 2 Specifies the verbosity level for diagnostics, as an integer between 0 and 10, with 0 for no diagnostics, 10 for all diagnostics. no
-csharp-analysis-memory <num> The value of configuration parameter CSHARP_ANALYSIS_MAX_MEMORY. Specifies that the memory allocated for running the analysis engine is <num>MB. no
-csharp-launcher-memory <num> The value of configuration parameter CSHARP_LAUNCHER_MEMORY. Specifies that the memory allocated for running the process collecting the files in preparation for the analysis engine is <num>MB. no
-csharp-source-level <num> 13.0 Specifies that the language compliance level to be used in parsing C# source files (.cs) is <num>: one of {1, 2, 3, 4, 5, 6, 7, 7.1, 7.2, 7.3, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0 }. no
-enable-assertions The value of configuration parameter CSHARP_ANALYSIS_ENABLE_ASSERTIONS. Specifies whether or not the C# build/analysis will treat assertion statements as if they are executed. yes
-encoding <encname> utf-8 Specifies the encoding for C# source files. This will affect parsing for all C# source files, whether specified directly or automatically detected by the analysis. The available <encname> values will depend on your local system and runtime setup: see Encoding Class (microsoft.com) for more information.

We recommend using this option only to troubleshoot source file parsing for non-Unicode files.

no
-entrypoints <mode> The value of configuration parameter CSHARP_ANALYSIS_ENTRY_POINTS_MODE. Specifies that the runtime environment of the analyzed application is <mode>: one of {ALL_ENTRIES, ONLY_EXPLICIT_ENTRIES, ONLY_STANDARD_ENTRIES, LIBRARY, ALL_METHODS}.
If specified multiple times, the last value specified is used.
yes
-framework <framework> The value of configuration parameter CSHARP_ANALYSIS_FRAMEWORK. Specifies that the runtime environment of the analyzed application is <framework>. One of: net10, net11, net20, net30, net35, net40, net45, net451, net452, net46, net461, net462, net47, net471, net472, net48, netcoreapp1.0, netcoreapp1.1, netcoreapp2.0, netcoreapp2.1, netcoreapp2.2, netcoreapp3.0, netcoreapp3.1, net5.0, net6.0, net7.0, net8.0, net9.0.

We strongly recommend that you specify this option if you are analyzing one or more projects with multiple target frameworks. See also -msbuild-os-target.

If specified multiple times, the last value specified is used.

yes
-import-require-source Warnings will be submitted to the hub even if there is no corresponding source code. Specifies that warnings should only be submitted to the hub if the corresponding source code is available and specified with -include-sources or in PDB files.
Has no effect for libraries and signatures.
no
-msbuild-os-target <os-targ> CodeSonar will attempt to select a suitable target framework for each project in the solution. When -msbuild-solution <slnpath> is specified, CodeSonar analyzes either some or all of the projects in the solution at <slnpath>, depending on whether -msbuild-project is specified and with what value or values.
Within the set of analyzed projects, CodeSonar always analyzes one target framework per project.
  • If -msbuild-os-target <os-targ> is specified and the project has a <framework>-<os-targ> target framework, CodeSonar will analyze that.
    (<framework> is specified with -framework or CSHARP_ANALYSIS_FRAMEWORK).
  • If -msbuild-os-target <os-targ> is not specified, or it is specified but the project has no <framework>-<os-targ> target framework, CodeSonar will attempt to select a suitable target framework. If available, it will prefer to select one that is consistent with the specified <framework>.

    If this involves selecting from among multiple options, the selected target is recorded in the build log.

The possible values of <os-targ> are {android, maccatalyst, macos, tvos, windows}.

We strongly recommend that you specifiy both -msbuild-os-target and -framework when analyzing solutions that contain one or more multiple target framework projects with OS-specific Target Framework Monikers.

This option does not affect handling of single-target projects, since their one target will always be analyzed.

If -msbuild-solution is not specified, this option has no effect.

no
-msbuild-property <key>:<value> none If -msbuild-solution is specified, CodeSonar will set the MSBuild project property named <key> to <value> in the set of MSBuild project property information extracted from each specified solution file, replacing any previous value.

Use this option to inform cs-dotnet-scan of the property settings that were used to build your project. For example, if you performed a debug build then include -msbuild-property Configuration:Debug in your cs-dotnet-scan command.

If -msbuild-solution is not specified, this option has no effect.
yes
-no-warn-empty-project CodeSonar terminates with an error message if there are no sources or artifacts. Normally, analyzing a project without specifying sources or artifacts will result in the analysis terminating and printing an error message. Use this flag to suppress the error message in this case. no

Artifact Categories

Artifacts are files with the following extensions: .exe, .dll.

Each artifact included in a particular CodeSonar analysis belongs to one of four categories: ordinary artifacts, sourceless artifacts, libraries, and signatures. The artifact's category determines how the analysis will handle the artifact, as described in the table below.

Every artifact (of every category) must have a corresponding PDB file located in the same directory. If there is no such PDB file, the analysis will issue an alert.
For example, if /myfiles/project/X.dll is specified, /myfiles/project/X.pdb must also be present.

The following table describes the artifact categories in order of importance.

Artifact Category Description Include with Exclude with
ordinary artifacts Artifacts for which you
  • wish CodeSonar to issue warnings, and
  • have the corresponding source code.

The C# build/analysis will determine the corresponding source code as follows.

-include-artifacts
  • If the source paths specified in the corresponding PDB file are correct, the analysis will use those source files.
  • Otherwise, if the source paths are incorrect (for example, because you have moved the files), specify the source file locations directly with -include-sources.
  • Otherwise, CodeSonar determines that the corresponding source code is not available.
If source code is not available for one or more ordinary artifacts, behavior depends on the other elements of the containing cs-dotnet-scan command.
  • If the cs-dotnet-scan command specifies at least one sourceless artifact, the analysis proceeds and includes the ordinary artifacts for which source is not available.
    • If -import-require-source is specified, warnings are not uploaded to the hub for artifacts that have no source available.
    • If it is not specified, warnings are uploaded to the hub even if source is not available. Such warnings are presented with reduced detail.
  • Otherwise, the analysis fails and no artifacts are analyzed.
If the source code corresponding to an ordinary artifact is available, warnings for that artifact are uploaded to the hub and presented with respect to the source file or files.
-msbuild-solution The analysis will use the source files identified in the project file or files.
If source code is not available for one or more ordinary artifacts, the analysis fails and no artifacts are analyzed.
Otherwise, warnings for all ordinary artifacts are uploaded to the hub and presented with respect to the source file or files.
-include-artifacts
or
-msbuild-solution
-exclude-artifacts

(not applicable to artifacts derived from a solution file specified with -msbuild-solution)
sourceless artifacts Artifacts for which you
  • wish CodeSonar to issue warnings, and
  • do not wish the analysis to fail if the corresponding source code is not found.

The analysis will attempt to identify corresponding source code as described for ordinary artifacts.

  • If source code is available, warnings for the artifact are uploaded to the hub and presented with respect to the source file or files.
  • If the source code is not present, the warnings for the sourceless artifact are uploaded to the hub only if -import-require-source is not specified. The warnings in this case are presented with reduced detail, since the relevant source files are not available.
-include-sourceless-artifacts -exclude-sourceless-artifacts
libraries Artifacts that you want to include in the CodeSonar analysis, but for which you do not wish to see any warnings. -include-libraries -exclude-libraries
signatures Artifacts that you want to include in the CodeSonar analysis but only to the extent of collecting signatures, and for which you do not wish to see any warnings. Including signatures can improve analysis results, but to a lesser extent than including libraries. -include-signatures -exclude-signatures

Example Command Lines

Some example CodeSonar command lines for building and analyzing C# projects.

Note: Depending on the hub configuration, you may be prompted for hub user account credentials to authenticate and authorize codesonar build and codesonar analyze commands. See Hub Authentication: Authenticated codesonar Subcommands for more information.

The first four examples below are for projects with simple structure.

Example 1

codesonar analyze cs-myproj cs-dotnet-scan \
-include-artifacts Example.dll

Build a CodeSonar project based on the classes contained in Example.dll, located in the current working directory.

Example 2

codesonar analyze cs-myproj cs-dotnet-scan \
-include-artifacts /path/to/binaries -include-sources /path/to/sources

Build and analyze a CodeSonar project based on the source files in /path/to/sources and the artifacts in /path/to/binaries.

Example 3

codesonar analyze cs-myproj cs-dotnet-scan \
-include-artifacts "/path/to/binaries/**/*.dll"

Build and analyze a CodeSonar project based on the source files in /path/to/sources and the artifacts in /path/to/classes.

Example 4

codesonar analyze cs-myproj cs-dotnet-scan \
-include-artifacts /path/to/Project.exe -include-sources /path/to/sources

Build and analyze a CodeSonar project based on the source files in /path/to/sources and the .exe file /path/to/Project.exe.

The following examples illustrate more fine-grained control of the analysis.

Example 5

codesonar analyze cs-myproj cs-dotnet-scan \
-include-artifacts "/path/to/binaries/**/*.dll" \
-exclude-artifacts "/path/to/binaries/A/**/*.dll"

Build and analyze a CodeSonar project based on the artifacts in /path/to/binaries, except for the artifacts in /path/to/binaries/A.

Example 6

codesonar analyze cs-myproj cs-dotnet-scan \
-include-artifacts "/path/to/binaries/**/*.exe" \
-exclude-artifacts "/path/to/binaries/A/**/*.exe" \
-include-artifacts "/path/to/binaries/A/B/**/*.exe"

Build and analyze a CodeSonar project based on the .exe files in the tree below /path/to/binaries, except for those that are in /path/to/binaries/A but not in /path/to/binaries/A/B.

Example 7

codesonar analyze cs-myproj cs-dotnet-scan \
-include-artifacts /path/to/Project.exe \
-include-signatures /path/to/External.dll

Build and analyze a CodeSonar project based on .exe file /path/to/Project.exe, using the type signatures of the classes found inside /path/to/External.dll.

Example 8

codesonar analyze cs-myproj cs-dotnet-scan \
-include-artifacts . -include-sources .

Build and analyze a CodeSonar project based on the full contents of the current directory and all its (recursive) subdirectories.

Example 9

codesonar analyze cs-myproj cs-dotnet-scan \
-include-artifacts . \
-exclude-artifacts "*Test*.dll" \
-exclude-artifacts "*Test*/**/*.dll" \
-include-sources .

Build and analyze a CodeSonar project based on the full contents of the current directory and all its (recursive) subdirectories, excluding .dll files whose name or directory path contains "Test".

Example 10

cat <<EOF > buildscan.sh
#!/bin/sh
ant
cs-dotnet-scan -include-artifacts foo -include-sources foo &
cs-dotnet-scan -include-artifacts bar -include-sources bar &
wait
EOF
chmod +x buildscan.sh
codesonar analyze foo ./buildscan.sh

Executing this shell script will build the project with ant, then run two instances of cs-dotnet-scan in parallel on different parts of the project.

Example 11

codesonar analyze cs-myproj cs-dotnet-scan ^
-msbuild-solution path\to\SolutionX.sln ^
-msbuild-location "C:\Program Files\Microsoft Visual Studio\2022\Professional"

Build and analyze a CodeSonar project based on path\to\SolutionX.sln (an MSBuild solution file).

Example 12

codesonar analyze cs-myproj cs-dotnet-scan ^
-msbuild-solution solpath\to\SolutionX.sln ^
-msbuild-project projpath\to\ProjX5.csproj ^
-msbuild-location "C:\Program Files\Microsoft Visual Studio\2022\Professional"

Build and analyze a CodeSonar project based on MSBuild project projpath\to\ProjX5.csproj, which is part of MSBuild solution solpath\to\SolutionX.sln.

Example 13

Suppose your project has a number of DLL files in directory bin\Debug\. The main artifact is called CashGrabber.dll and has associated source code; the remaining DLLs are libraries and do not have source code. Furthermore, library crypto.dll contains unmanaged code and so must be excluded from the CodeSonar C# analysis.

codesonar analyze cs-myproj cs-dotnet-scan ^
-include-artifacts "bin\Debug\CashGrabber.dll" ^
-include-libraries "bin\Debug" ^
-exclude-libraries "bin\Debug\crypto.dll"

IDE Integrations and Windows Build Wizard

In general, we recommend using the command line CodeSonar build/analysis for C# projects.

Microsoft Visual Studio integration The Microsoft Visual Studio integration supports C# analysis, but requires some additional steps. See CodeSonar Plug-in for Visual Studio: Build and Analyze a Project for details.
Eclipse integration There is currently no plan to support C# analysis in the Eclipse integration: if you use Eclipse for C# development and need such support, please contact CodeSecure.
Windows Build Wizard If you prefer, you can use the Windows build wizard to observe cs-dotnet-scan invocations.
  • Make sure the wizard is set up to watch the process (for example, the command prompt) in which you will invoke cs-dotnet-scan.
  • Once the wizard is recording, run your cs-dotnet-scan commands (details and examples are given above).

Troubleshooting

Resolving Alerts

The most typical alerts related to the C# build/analysis are listed below. For descriptions of all CodeSonar alerts, see Alerts.

Red Alerts
Two important alerts related to the C# build/analysis are num Missing Source Files and Miscellaneous Error. These are red (severe) alerts, because they indicate that the analysis may not be as complete as intended.
num Missing Source Files This indicates that CodeSonar was unable to find corresponding source files for num of the classes specified by the build command, so will not report warnings for those classes. For each of these classes C: If you want warnings to be reported for the class but do not have its source code, you may prefer to retain the alert as a reminder.

Missing source files may be caused by "too many potential candidates" errors.

Miscellaneous Error The analysis engine can produce a wide variety of diagnostics, that do not necessarily affect the analysis. These appear in the hub as Miscellaneous Errors.
Yellow Alerts
Duplicated Component, Invalid Component, and Native Component are all yellow alerts.
Duplicated Component The analyzed artifacts for a single cs-dotnet-scan invocation include two or more components (for example, classes) with the same fully-qualified name.
The analysis will include the first component encountered with each name, and ignore any others.
  • If only one of the duplicated components is of interest, adjust your cs-dotnet-scan invocation so that the other duplicates are not included in the set of analyzed artifacts.
  • If you have multiple components with the same fully-qualified name and want to include them all in your CodeSonar project, you will need to do one of the following.
    • Adjust the component names so that they are no longer identical.
    • Split your build/analysis across two or more cs-dotnet-scan invocations, each of which includes only one of the duplicate components along with any other artifacts that depend on that component.
Invalid Component The analyzed artifacts include one or more components (for example, classes) for which CodeSonar was unable to extract CLR code.

Check the following.

  • Is the component compatible with the -csharp-source-level specified in your cs-dotnet-scan command?
  • Does the component contain code, or only data assets? If the latter, you can exclude it from the analysis.
Native Component The analyzed artifacts include one or more components (for example, classes) written in native code, including "unsafe" C# code.
  • The C# build/analysis will not understand the native code and will not account for its effects.
  • If the native component is written in C or C++, you can include it in the CodeSonar project by observing its compilation.
    The C/C++ build/analysis will account for the component contents and effects on other C and C++ components, but not for its effects on C# components.
  • Native code in signatures will not cause Native Component alerts.

"Too many potential candidates" parse errors

In some cases, you may see a parse error that looks something like the following.

Too many potential candidates for file "Home.cs". Try using a more restrictive -include-sources argument.

For each analyzed ordinary artifact and sourceless artifact, CodeSonar attempts to identify the corresponding source file. To do this, CodeSonar iterates over those files specified with -include-sources and -exclude-sources whose basenames correspond to that of the artifact, checking each in turn to see if it is the correct match. Iteration finishes either when a match is found, or when the number of source files checked for a particular artifact exceeds the limit specified in environment variable CS_DOTNETFE_INCLUDESOURCE_LIMIT. The default value for this limit is 100.

If CodeSonar does not find the correct matching source file before reaching the iteration limit, then:

There are two options for resolving this problem.

In some cases, the most convenient solution might be to split your build/analysis across two or more cs-dotnet-scan invocations, each of which covers a smaller set of artifacts and specifies a more precise set of source files. This approach may still require you to increase the CS_DOTNETFE_INCLUDESOURCE_LIMIT, but typically not to the same extent.

Related Sections

 

To report problems with this documentation, please visit https://support.codesecure.com/.