Compare commits

..

5 Commits

Author SHA1 Message Date
Taus
01a9bec7df Python: Exclude sources in functions with unclear returns
A common source of FPs is when the flow inside a function depends on
some argument to the function. In this case, if a non-container class is
being returned in _some_ branch, we behave as if it _always_ is
returned, leading to false positives where the code is actually safe
because the argument to the function prevents the bad return from being
executed.
2026-04-14 09:11:28 +00:00
Taus
71318cb3d5 Python: Use global data-flow for ContainsNonContainer.ql
Replaces the `classTracker`-based approach with one based on global
data-flow. To make it easy to share across queries, this is implemented
as a parameterised module.

The data-flow configuration itself keeps track of two flow states:
whether we're tracking a reference to a class or a reference to an
instance.
2026-04-14 09:11:28 +00:00
Taus
d74f34bb66 Python: Get rid of isinstance FPs
Eliminates cases where we explicitly check whether the object in
question is an instance of (a subclass of) a built-in container type.
2026-04-14 09:11:28 +00:00
Taus
8046bfe12f Python: Remove some FPs for ContainsNonContainer.ql
First fix handles the case where there's interference from a class-based
decorator on a function. In this case, _technically_ we have an instance
of the decorator class, but in practice this decorator will (hopefully)
forward all accesses to the thing it wraps.

The second fix has to do with methods that are added dynamically using
`setattr`. In this case, we cannot be sure that the relevant methods are
actually missing.
2026-04-14 09:11:28 +00:00
Taus
fe9def3ff2 Python: Port ContainsNonContainer.ql
Uses the new `DuckTyping` module to handle recognising whether a class
is a container or not. Only trivial test changes (one version uses
"class", the other "Class").

Note that the ported query has no understanding of built-in classes. At
some point we'll likely want to replace `hasUnresolvedBase` (which will
hold for any class that extends a built-in) with something that's aware
of the built-in classes.
2026-04-14 09:11:28 +00:00
553 changed files with 101527 additions and 142272 deletions

View File

@@ -1,206 +0,0 @@
name: Update Go version
on:
workflow_dispatch:
schedule:
- cron: "0 3 * * 1" # Run weekly on Mondays at 3 AM UTC (1 = Monday)
permissions:
contents: write
pull-requests: write
jobs:
update-go-version:
name: Check and update Go version
if: github.repository == 'github/codeql'
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Set up Git
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
- name: Fetch latest Go version
id: fetch-version
run: |
LATEST_GO_VERSION=$(curl -s https://go.dev/dl/?mode=json | jq -r '.[0].version')
if [ -z "$LATEST_GO_VERSION" ] || [ "$LATEST_GO_VERSION" = "null" ]; then
echo "Error: Failed to fetch latest Go version from go.dev"
exit 1
fi
echo "Latest Go version from go.dev: $LATEST_GO_VERSION"
echo "version=$LATEST_GO_VERSION" >> $GITHUB_OUTPUT
# Extract version numbers (e.g., go1.26.0 -> 1.26.0)
LATEST_VERSION_NUM=$(echo $LATEST_GO_VERSION | sed 's/^go//')
echo "version_num=$LATEST_VERSION_NUM" >> $GITHUB_OUTPUT
# Extract major.minor version (e.g., 1.26.0 -> 1.26)
LATEST_MAJOR_MINOR=$(echo $LATEST_VERSION_NUM | sed -E 's/^([0-9]+\.[0-9]+).*/\1/')
echo "major_minor=$LATEST_MAJOR_MINOR" >> $GITHUB_OUTPUT
- name: Check current Go version
id: current-version
run: |
CURRENT_VERSION=$(sed -n 's/.*go_sdk\.download(version = \"\([^\"]*\)\".*/\1/p' MODULE.bazel)
if [ -z "$CURRENT_VERSION" ]; then
echo "Error: Could not extract Go version from MODULE.bazel"
exit 1
fi
echo "Current Go version in MODULE.bazel: $CURRENT_VERSION"
echo "version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
# Extract major.minor version
CURRENT_MAJOR_MINOR=$(echo $CURRENT_VERSION | sed -E 's/^([0-9]+\.[0-9]+).*/\1/')
echo "major_minor=$CURRENT_MAJOR_MINOR" >> $GITHUB_OUTPUT
- name: Compare versions
id: compare
run: |
LATEST="${{ steps.fetch-version.outputs.version_num }}"
CURRENT="${{ steps.current-version.outputs.version }}"
echo "Latest: $LATEST"
echo "Current: $CURRENT"
if [ "$LATEST" = "$CURRENT" ]; then
echo "Go version is up to date"
echo "needs_update=false" >> $GITHUB_OUTPUT
else
echo "Go version needs update from $CURRENT to $LATEST"
echo "needs_update=true" >> $GITHUB_OUTPUT
fi
- name: Update Go version in files
if: steps.compare.outputs.needs_update == 'true'
run: |
LATEST_VERSION_NUM="${{ steps.fetch-version.outputs.version_num }}"
LATEST_MAJOR_MINOR="${{ steps.fetch-version.outputs.major_minor }}"
CURRENT_VERSION="${{ steps.current-version.outputs.version }}"
CURRENT_MAJOR_MINOR="${{ steps.current-version.outputs.major_minor }}"
echo "Updating from $CURRENT_VERSION to $LATEST_VERSION_NUM"
# Escape dots in current version strings for use in sed patterns
CURRENT_VERSION_ESCAPED=$(echo "$CURRENT_VERSION" | sed 's/\./\\./g')
CURRENT_MAJOR_MINOR_ESCAPED=$(echo "$CURRENT_MAJOR_MINOR" | sed 's/\./\\./g')
# Update MODULE.bazel
if ! sed -i "s/go_sdk\.download(version = \"$CURRENT_VERSION_ESCAPED\")/go_sdk.download(version = \"$LATEST_VERSION_NUM\")/" MODULE.bazel; then
echo "Warning: Failed to update MODULE.bazel"
fi
# Update go/extractor/go.mod
if ! sed -i "s/^go $CURRENT_MAJOR_MINOR_ESCAPED\$/go $LATEST_MAJOR_MINOR/" go/extractor/go.mod; then
echo "Warning: Failed to update go directive in go.mod"
fi
if ! sed -i "s/^toolchain go$CURRENT_VERSION_ESCAPED\$/toolchain go$LATEST_VERSION_NUM/" go/extractor/go.mod; then
echo "Warning: Failed to update toolchain in go.mod"
fi
# Update go/extractor/autobuilder/build-environment.go
if ! sed -i "s/var maxGoVersion = util\.NewSemVer(\"$CURRENT_MAJOR_MINOR_ESCAPED\")/var maxGoVersion = util.NewSemVer(\"$LATEST_MAJOR_MINOR\")/" go/extractor/autobuilder/build-environment.go; then
echo "Warning: Failed to update build-environment.go"
fi
# Update go/actions/test/action.yml
if ! sed -i "s/default: \"~$CURRENT_VERSION_ESCAPED\"/default: \"~$LATEST_VERSION_NUM\"/" go/actions/test/action.yml; then
echo "Warning: Failed to update action.yml"
fi
# Show what changed
git diff
- name: Check for changes
id: check-changes
if: steps.compare.outputs.needs_update == 'true'
run: |
if git diff --quiet; then
echo "No changes detected"
echo "has_changes=false" >> $GITHUB_OUTPUT
else
echo "Changes detected"
echo "has_changes=true" >> $GITHUB_OUTPUT
fi
- name: Check for existing PR
if: steps.check-changes.outputs.has_changes == 'true'
id: check-pr
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
BRANCH_NAME="workflow/go-version-update"
PR_NUMBER=$(gh pr list --head "$BRANCH_NAME" --state open --json number --jq '.[0].number')
if [ -n "$PR_NUMBER" ]; then
echo "Existing PR found: #$PR_NUMBER"
echo "pr_exists=true" >> $GITHUB_OUTPUT
echo "pr_number=$PR_NUMBER" >> $GITHUB_OUTPUT
else
echo "No existing PR found"
echo "pr_exists=false" >> $GITHUB_OUTPUT
fi
- name: Commit and push changes
if: steps.check-changes.outputs.has_changes == 'true'
run: |
BRANCH_NAME="workflow/go-version-update"
LATEST_VERSION_NUM="${{ steps.fetch-version.outputs.version_num }}"
LATEST_MAJOR_MINOR="${{ steps.fetch-version.outputs.major_minor }}"
# Create or switch to branch
git checkout -B "$BRANCH_NAME"
# Stage and commit changes
git add MODULE.bazel go/extractor/go.mod go/extractor/autobuilder/build-environment.go go/actions/test/action.yml
git commit -m "Go: Update to $LATEST_MAJOR_MINOR"
# Push changes
git push -f origin "$BRANCH_NAME"
- name: Create or update PR
if: steps.check-changes.outputs.has_changes == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
BRANCH_NAME="workflow/go-version-update"
LATEST_MAJOR_MINOR="${{ steps.fetch-version.outputs.major_minor }}"
CURRENT_MAJOR_MINOR="${{ steps.current-version.outputs.major_minor }}"
PR_TITLE="Go: Update to $LATEST_MAJOR_MINOR"
PR_BODY=$(cat <<EOF
This PR updates Go from $CURRENT_MAJOR_MINOR to $LATEST_MAJOR_MINOR.
Updated files:
- \`MODULE.bazel\` - go_sdk.download version
- \`go/extractor/go.mod\` - go directive and toolchain
- \`go/extractor/autobuilder/build-environment.go\` - maxGoVersion
- \`go/actions/test/action.yml\` - default go-test-version
This PR was automatically created by the [Go version update workflow](https://github.com/${{ github.repository }}/blob/main/.github/workflows/go-version-update.yml).
EOF
)
if [ "${{ steps.check-pr.outputs.pr_exists }}" = "true" ]; then
echo "Updating existing PR #${{ steps.check-pr.outputs.pr_number }}"
gh pr edit "${{ steps.check-pr.outputs.pr_number }}" --title "$PR_TITLE" --body "$PR_BODY"
else
echo "Creating new PR"
gh pr create \
--title "$PR_TITLE" \
--body "$PR_BODY" \
--base main \
--head "$BRANCH_NAME" \
--label "Go"
fi

View File

@@ -1,13 +1,3 @@
## 0.4.34
### Minor Analysis Improvements
* Removed false positive injection sink models for the `context` input of `docker/build-push-action` and the `allowed-endpoints` input of `step-security/harden-runner`.
## 0.4.33
No user-facing changes.
## 0.4.32
No user-facing changes.

View File

@@ -1,3 +0,0 @@
## 0.4.33
No user-facing changes.

View File

@@ -1,5 +0,0 @@
## 0.4.34
### Minor Analysis Improvements
* Removed false positive injection sink models for the `context` input of `docker/build-push-action` and the `allowed-endpoints` input of `step-security/harden-runner`.

View File

@@ -1,2 +1,2 @@
---
lastReleaseVersion: 0.4.34
lastReleaseVersion: 0.4.32

View File

@@ -0,0 +1,6 @@
extensions:
- addsTo:
pack: codeql/actions-all
extensible: actionsSinkModel
data:
- ["docker/build-push-action", "*", "input.context", "code-injection", "manual"]

View File

@@ -0,0 +1,6 @@
extensions:
- addsTo:
pack: codeql/actions-all
extensible: actionsSinkModel
data:
- ["step-security/harden-runner", "*", "input.allowed-endpoints", "command-injection", "manual"]

View File

@@ -1,5 +1,5 @@
name: codeql/actions-all
version: 0.4.35-dev
version: 0.4.33-dev
library: true
warnOnImplicitThis: true
dependencies:

View File

@@ -1,17 +1,3 @@
## 0.6.26
### Major Analysis Improvements
* Fixed alert messages in `actions/artifact-poisoning/critical` and `actions/artifact-poisoning/medium` as they previously included a redundant placeholder in the alert message that would on occasion contain a long block of yml that makes the alert difficult to understand. Also improved the wording to make it clearer that it is not the artifact that is being poisoned, but instead a potentially untrusted artifact that is consumed. Finally, changed the alert location to be the source, to align more with other queries reporting an artifact (e.g. zipslip) which is more useful.
### Minor Analysis Improvements
* The query `actions/missing-workflow-permissions` no longer produces false positive results on reusable workflows where all callers set permissions.
## 0.6.25
No user-facing changes.
## 0.6.24
No user-facing changes.
@@ -173,7 +159,7 @@ No user-facing changes.
* `actions/if-expression-always-true/critical`
* `actions/if-expression-always-true/high`
* `actions/unnecessary-use-of-advanced-config`
* The following query has been moved from the `code-scanning` suite to the `security-extended`
suite. Any existing alerts for this query will be closed automatically unless the analysis is
configured to use the `security-extended` suite.

View File

@@ -0,0 +1,4 @@
---
category: majorAnalysis
---
* Fixed alert messages in `actions/artifact-poisoning/critical` and `actions/artifact-poisoning/medium` as they previously included a redundant placeholder in the alert message that would on occasion contain a long block of yml that makes the alert difficult to understand. Also clarify the wording to make it clear that it is not the artifact that is being poisoned, but instead a potentially untrusted artifact that is consumed. Also change the alert location to be the source, to align more with other queries reporting an artifact (e.g. zipslip) which is more useful.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The query `actions/missing-workflow-permissions` no longer produces false positive results on reusable workflows where all callers set permissions.

View File

@@ -1,3 +0,0 @@
## 0.6.25
No user-facing changes.

View File

@@ -1,9 +0,0 @@
## 0.6.26
### Major Analysis Improvements
* Fixed alert messages in `actions/artifact-poisoning/critical` and `actions/artifact-poisoning/medium` as they previously included a redundant placeholder in the alert message that would on occasion contain a long block of yml that makes the alert difficult to understand. Also improved the wording to make it clearer that it is not the artifact that is being poisoned, but instead a potentially untrusted artifact that is consumed. Finally, changed the alert location to be the source, to align more with other queries reporting an artifact (e.g. zipslip) which is more useful.
### Minor Analysis Improvements
* The query `actions/missing-workflow-permissions` no longer produces false positive results on reusable workflows where all callers set permissions.

View File

@@ -1,2 +1,2 @@
---
lastReleaseVersion: 0.6.26
lastReleaseVersion: 0.6.24

View File

@@ -1,5 +1,5 @@
name: codeql/actions-queries
version: 0.6.27-dev
version: 0.6.25-dev
library: false
warnOnImplicitThis: true
groups: [actions, queries]

View File

@@ -43,7 +43,6 @@ ql/cpp/ql/src/Security/CWE/CWE-367/TOCTOUFilesystemRace.ql
ql/cpp/ql/src/Security/CWE/CWE-416/IteratorToExpiredContainer.ql
ql/cpp/ql/src/Security/CWE/CWE-416/UseOfStringAfterLifetimeEnds.ql
ql/cpp/ql/src/Security/CWE/CWE-416/UseOfUniquePointerAfterLifetimeEnds.ql
ql/cpp/ql/src/Security/CWE/CWE-468/SuspiciousAddWithSizeof.ql
ql/cpp/ql/src/Security/CWE/CWE-497/ExposedSystemData.ql
ql/cpp/ql/src/Security/CWE/CWE-611/XXE.ql
ql/cpp/ql/src/Security/CWE/CWE-676/DangerousFunctionOverflow.ql

View File

@@ -1,34 +1,3 @@
## 10.0.0
### Breaking Changes
* The deprecated `NonThrowingFunction` class has been removed, use `NonCppThrowingFunction` instead.
* The deprecated `ThrowingFunction` class has been removed, use `AlwaysSehThrowingFunction` instead.
### New Features
* Added a subclass `AutoconfConfigureTestFile` of `ConfigurationTestFile` that represents files created by GNU autoconf configure scripts to test the build configuration.
## 9.0.0
### Breaking Changes
* The `SourceModelCsv`, `SinkModelCsv`, and `SummaryModelCsv` classes and the associated CSV parsing infrastructure have been removed from `ExternalFlow.qll`. New models should be added as `.model.yml` files in the `ext/` directory.
### New Features
* Added a subclass `MesonPrivateTestFile` of `ConfigurationTestFile` that represents files created by Meson to test the build configuration.
* Added a class `ConstructorDirectFieldInit` to represent field initializations that occur in member initializer lists.
* Added a class `ConstructorDefaultFieldInit` to represent default field initializations.
* Added a class `DataFlow::IndirectParameterNode` to represent the indirection of a parameter as a dataflow node.
* Added a predicate `Node::asIndirectInstruction` which returns the `Instruction` that defines the indirect dataflow node, if any.
* Added a class `IndirectUninitializedNode` to represent the indirection of an uninitialized local variable as a dataflow node.
### Minor Analysis Improvements
* Added `HttpReceiveHttpRequest`, `HttpReceiveRequestEntityBody`, and `HttpReceiveClientCertificate` from Win32's `http.h` as remote flow sources.
* Added dataflow through members initialized via non-static data member initialization (NSDMI).
## 8.0.3
No user-facing changes.

View File

@@ -0,0 +1,4 @@
---
category: feature
---
* Added a class `IndirectUninitializedNode` to represent the indirection of an uninitialized local variable as a dataflow node.

View File

@@ -1,4 +0,0 @@
---
category: feature
---
* Data flow barriers and barrier guards can now be added using data extensions. For more information see [Customizing library models for C and C++](https://codeql.github.com/docs/codeql-language-guides/customizing-library-models-for-cpp/).

View File

@@ -0,0 +1,5 @@
---
category: feature
---
* Added a class `DataFlow::IndirectParameterNode` to represent the indirection of a parameter as a dataflow node.
* Added a predicate `Node::asIndirectInstruction` which returns the `Instruction` that defines the indirect dataflow node, if any.

View File

@@ -0,0 +1,5 @@
---
category: feature
---
* Added a class `ConstructorDirectFieldInit` to represent field initializations that occur in member initializer lists.
* Added a class `ConstructorDefaultFieldInit` to represent default field initializations.

View File

@@ -0,0 +1,4 @@
---
category: breaking
---
* The `SourceModelCsv`, `SinkModelCsv`, and `SummaryModelCsv` classes and the associated CSV parsing infrastructure have been removed from `ExternalFlow.qll`. New models should be added as `.model.yml` files in the `ext/` directory.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Added dataflow through members initialized via non-static data member initialization (NSDMI).

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Added `HttpReceiveHttpRequest`, `HttpReceiveRequestEntityBody`, and `HttpReceiveClientCertificate` from Win32's `http.h` as remote flow sources.

View File

@@ -0,0 +1,4 @@
---
category: feature
---
* Added a subclass `MesonPrivateTestFile` of `ConfigurationTestFile` that represents files created by Meson to test the build configuration.

View File

@@ -0,0 +1,4 @@
---
category: feature
---
* Added a subclass `AutoconfConfigureTestFile` of `ConfigurationTestFile` that represents files created by GNU autoconf configure scripts to test the build configuration.

View File

@@ -1,10 +0,0 @@
## 10.0.0
### Breaking Changes
* The deprecated `NonThrowingFunction` class has been removed, use `NonCppThrowingFunction` instead.
* The deprecated `ThrowingFunction` class has been removed, use `AlwaysSehThrowingFunction` instead.
### New Features
* Added a subclass `AutoconfConfigureTestFile` of `ConfigurationTestFile` that represents files created by GNU autoconf configure scripts to test the build configuration.

View File

@@ -1,19 +0,0 @@
## 9.0.0
### Breaking Changes
* The `SourceModelCsv`, `SinkModelCsv`, and `SummaryModelCsv` classes and the associated CSV parsing infrastructure have been removed from `ExternalFlow.qll`. New models should be added as `.model.yml` files in the `ext/` directory.
### New Features
* Added a subclass `MesonPrivateTestFile` of `ConfigurationTestFile` that represents files created by Meson to test the build configuration.
* Added a class `ConstructorDirectFieldInit` to represent field initializations that occur in member initializer lists.
* Added a class `ConstructorDefaultFieldInit` to represent default field initializations.
* Added a class `DataFlow::IndirectParameterNode` to represent the indirection of a parameter as a dataflow node.
* Added a predicate `Node::asIndirectInstruction` which returns the `Instruction` that defines the indirect dataflow node, if any.
* Added a class `IndirectUninitializedNode` to represent the indirection of an uninitialized local variable as a dataflow node.
### Minor Analysis Improvements
* Added `HttpReceiveHttpRequest`, `HttpReceiveRequestEntityBody`, and `HttpReceiveClientCertificate` from Win32's `http.h` as remote flow sources.
* Added dataflow through members initialized via non-static data member initialization (NSDMI).

View File

@@ -1,2 +1,2 @@
---
lastReleaseVersion: 10.0.0
lastReleaseVersion: 8.0.3

View File

@@ -12,7 +12,4 @@ extensions:
- ["", "", False, "_malloca", "0", "", "", False]
- ["", "", False, "calloc", "1", "0", "", True]
- ["std", "", False, "calloc", "1", "0", "", True]
- ["bsl", "", False, "calloc", "1", "0", "", True]
- ["", "", False, "aligned_alloc", "1", "", "", True]
- ["std", "", False, "aligned_alloc", "1", "", "", True]
- ["bsl", "", False, "aligned_alloc", "1", "", "", True]
- ["bsl", "", False, "calloc", "1", "0", "", True]

View File

@@ -1,5 +1,5 @@
name: codeql/cpp-all
version: 10.0.1-dev
version: 8.0.4-dev
groups: cpp
dbscheme: semmlecode.cpp.dbscheme
extractor: cpp

View File

@@ -11,3 +11,10 @@ import semmle.code.cpp.models.Models
* The function may still raise a structured exception handling (SEH) exception.
*/
abstract class NonCppThrowingFunction extends Function { }
/**
* A function that is guaranteed to never throw.
*
* DEPRECATED: use `NonCppThrowingFunction` instead.
*/
deprecated class NonThrowingFunction = NonCppThrowingFunction;

View File

@@ -10,6 +10,19 @@ import semmle.code.cpp.Function
import semmle.code.cpp.models.Models
import semmle.code.cpp.models.interfaces.FunctionInputsAndOutputs
/**
* A function that is known to raise an exception.
*
* DEPRECATED: use `AlwaysSehThrowingFunction` instead.
*/
abstract deprecated class ThrowingFunction extends Function {
/**
* Holds if this function may throw an exception during evaluation.
* If `unconditional` is `true` the function always throws an exception.
*/
abstract predicate mayThrowException(boolean unconditional);
}
/**
* A function that unconditionally raises a structured exception handling (SEH) exception.
*/

View File

@@ -1,28 +1,3 @@
## 1.6.1
### Minor Analysis Improvements
* Added `AllocationFunction` models for `aligned_alloc`, `std::aligned_alloc`, and `bsl::aligned_alloc`.
* The "Comparison of narrow type with wide type in loop condition" (`cpp/comparison-with-wider-type`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.
* The "Multiplication result converted to larger type" (`cpp/integer-multiplication-cast-to-long`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.
* The "Suspicious add with sizeof" (`cpp/suspicious-add-sizeof`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.
* The "Wrong type of arguments to formatting function" (`cpp/wrong-type-format-argument`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.
* The "Implicit function declaration" (`cpp/implicit-function-declaration`) query has been upgraded to `high` precision. However, for `build mode: none` databases, it no longer produces any results. The results in this mode were found to be very noisy and fundamentally imprecise.
## 1.6.0
### Query Metadata Changes
* The `@security-severity` metadata of `cpp/cgi-xss` has been increased from 6.1 (medium) to 7.8 (high).
### Minor Analysis Improvements
* The "Extraction warnings" (`cpp/diagnostics/extraction-warnings`) diagnostics query no longer yields `ExtractionRecoverableWarning`s for `build-mode: none` databases. The results were found to significantly increase the sizes of the produced SARIF files, making them unprocessable in some cases.
* Fixed an issue with the "Suspicious add with sizeof" (`cpp/suspicious-add-sizeof`) query causing false positive results in `build-mode: none` databases.
* Fixed an issue with the "Uncontrolled format string" (`cpp/tainted-format-string`) query involving certain kinds of formatting function implementations.
* Fixed an issue with the "Wrong type of arguments to formatting function" (`cpp/wrong-type-format-argument`) query causing false positive results in `build-mode: none` databases.
* Fixed an issue with the "Multiplication result converted to larger type" (`cpp/integer-multiplication-cast-to-long`) query causing false positive results in `build-mode: none` databases.
## 1.5.15
No user-facing changes.
@@ -366,7 +341,7 @@ No user-facing changes.
### Minor Analysis Improvements
* The "non-constant format string" query (`cpp/non-constant-format`) has been updated to produce fewer false positives.
* Added dataflow models for the `gettext` function variants.
* Added dataflow models for the `gettext` function variants.
## 0.9.4

View File

@@ -6,7 +6,7 @@
* @kind problem
* @problem.severity warning
* @security-severity 8.8
* @precision high
* @precision medium
* @id cpp/suspicious-add-sizeof
* @tags security
* external/cwe/cwe-468

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Fixed an issue with the "Multiplication result converted to larger type" (`cpp/integer-multiplication-cast-to-long`) query causing false positive results in `build-mode: none` databases.

View File

@@ -0,0 +1,4 @@
---
category: queryMetadata
---
* The `@security-severity` metadata of `cpp/cgi-xss` has been increased from 6.1 (medium) to 7.8 (high).

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Fixed an issue with the "Wrong type of arguments to formatting function" (`cpp/wrong-type-format-argument`) query causing false positive results in `build-mode: none` databases.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Fixed an issue with the "Suspicious add with sizeof" (`cpp/suspicious-add-sizeof`) query causing false positive results in `build-mode: none` databases.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Fixed an issue with the "Uncontrolled format string" (`cpp/tainted-format-string`) query involving certain kinds of formatting function implementations.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The "Implicit function declaration" (`cpp/implicit-function-declaration`) query no longer produces results on `build mode: none` databases. These results were found to be very noisy and fundamentally imprecise in this mode.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The "Extraction warnings" (`cpp/diagnostics/extraction-warnings`) diagnostics query no longer yields `ExtractionRecoverableWarning`s for `build-mode: none` databases. The results were found to significantly increase the sizes of the produced SARIF files, making them unprocessable in some cases.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The "Comparison of narrow type with wide type in loop condition" (`cpp/comparison-with-wider-type`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The "Implicit function declaration" (`cpp/implicit-function-declaration`) query has been upgraded to `high` precision.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The "Multiplication result converted to larger type" (`cpp/integer-multiplication-cast-to-long`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The "Wrong type of arguments to formatting function" (`cpp/wrong-type-format-argument`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.

View File

@@ -1,13 +0,0 @@
## 1.6.0
### Query Metadata Changes
* The `@security-severity` metadata of `cpp/cgi-xss` has been increased from 6.1 (medium) to 7.8 (high).
### Minor Analysis Improvements
* The "Extraction warnings" (`cpp/diagnostics/extraction-warnings`) diagnostics query no longer yields `ExtractionRecoverableWarning`s for `build-mode: none` databases. The results were found to significantly increase the sizes of the produced SARIF files, making them unprocessable in some cases.
* Fixed an issue with the "Suspicious add with sizeof" (`cpp/suspicious-add-sizeof`) query causing false positive results in `build-mode: none` databases.
* Fixed an issue with the "Uncontrolled format string" (`cpp/tainted-format-string`) query involving certain kinds of formatting function implementations.
* Fixed an issue with the "Wrong type of arguments to formatting function" (`cpp/wrong-type-format-argument`) query causing false positive results in `build-mode: none` databases.
* Fixed an issue with the "Multiplication result converted to larger type" (`cpp/integer-multiplication-cast-to-long`) query causing false positive results in `build-mode: none` databases.

View File

@@ -1,10 +0,0 @@
## 1.6.1
### Minor Analysis Improvements
* Added `AllocationFunction` models for `aligned_alloc`, `std::aligned_alloc`, and `bsl::aligned_alloc`.
* The "Comparison of narrow type with wide type in loop condition" (`cpp/comparison-with-wider-type`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.
* The "Multiplication result converted to larger type" (`cpp/integer-multiplication-cast-to-long`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.
* The "Suspicious add with sizeof" (`cpp/suspicious-add-sizeof`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.
* The "Wrong type of arguments to formatting function" (`cpp/wrong-type-format-argument`) query has been upgraded to `high` precision. This query will now run in the default code scanning suite.
* The "Implicit function declaration" (`cpp/implicit-function-declaration`) query has been upgraded to `high` precision. However, for `build mode: none` databases, it no longer produces any results. The results in this mode were found to be very noisy and fundamentally imprecise.

View File

@@ -1,2 +1,2 @@
---
lastReleaseVersion: 1.6.1
lastReleaseVersion: 1.5.15

View File

@@ -1,5 +1,5 @@
name: codeql/cpp-queries
version: 1.6.2-dev
version: 1.5.16-dev
groups:
- cpp
- queries

View File

@@ -1,11 +1,3 @@
## 1.7.65
No user-facing changes.
## 1.7.64
No user-facing changes.
## 1.7.63
No user-facing changes.

View File

@@ -1,3 +0,0 @@
## 1.7.64
No user-facing changes.

View File

@@ -1,3 +0,0 @@
## 1.7.65
No user-facing changes.

View File

@@ -1,2 +1,2 @@
---
lastReleaseVersion: 1.7.65
lastReleaseVersion: 1.7.63

View File

@@ -1,5 +1,5 @@
name: codeql/csharp-solorigate-all
version: 1.7.66-dev
version: 1.7.64-dev
groups:
- csharp
- solorigate

View File

@@ -1,11 +1,3 @@
## 1.7.65
No user-facing changes.
## 1.7.64
No user-facing changes.
## 1.7.63
No user-facing changes.

View File

@@ -13,13 +13,11 @@ import csharp
import Solorigate
import experimental.code.csharp.Cryptography.NonCryptographicHashes
ControlFlowNode loopExitNode(LoopStmt loop) { result.isAfter(loop) }
from Variable v, Literal l, LoopStmt loop, Expr additional_xor
where
maybeUsedInFnvFunction(v, _, _, loop) and
exists(BitwiseXorOperation xor2 | xor2.getAnOperand() = l and additional_xor = xor2 |
loopExitNode(loop).getASuccessor*() = xor2.getControlFlowNode() and
loop.getAControlFlowExitNode().getASuccessor*() = xor2.getAControlFlowNode() and
xor2.getAnOperand() = v.getAnAccess()
)
select l, "This literal is used in an $@ after an FNV-like hash calculation with variable $@.",

View File

@@ -1,3 +0,0 @@
## 1.7.64
No user-facing changes.

View File

@@ -1,3 +0,0 @@
## 1.7.65
No user-facing changes.

View File

@@ -1,2 +1,2 @@
---
lastReleaseVersion: 1.7.65
lastReleaseVersion: 1.7.63

View File

@@ -1,5 +1,5 @@
name: codeql/csharp-solorigate-queries
version: 1.7.66-dev
version: 1.7.64-dev
groups:
- csharp
- solorigate

View File

@@ -1,2 +1,5 @@
import csharp
import ControlFlow::Consistency
import semmle.code.csharp.controlflow.internal.Completion
import ControlFlow
import semmle.code.csharp.controlflow.internal.ControlFlowGraphImpl::Consistency
import semmle.code.csharp.controlflow.internal.Splitting

View File

@@ -1,4 +1,5 @@
import csharp
private import semmle.code.csharp.controlflow.internal.ControlFlowGraphImpl as ControlFlowGraphImpl
private import semmle.code.csharp.dataflow.internal.DataFlowImplSpecific
private import semmle.code.csharp.dataflow.internal.TaintTrackingImplSpecific
private import codeql.dataflow.internal.DataFlowImplConsistency
@@ -6,6 +7,20 @@ private import codeql.dataflow.internal.DataFlowImplConsistency
private module Input implements InputSig<Location, CsharpDataFlow> {
private import CsharpDataFlow
private predicate isStaticAssignable(Assignable a) { a.(Modifiable).isStatic() }
predicate uniqueEnclosingCallableExclude(Node node) {
// TODO: Remove once static initializers are folded into the
// static constructors
isStaticAssignable(ControlFlowGraphImpl::getNodeCfgScope(node.getControlFlowNode()))
}
predicate uniqueCallEnclosingCallableExclude(DataFlowCall call) {
// TODO: Remove once static initializers are folded into the
// static constructors
isStaticAssignable(ControlFlowGraphImpl::getNodeCfgScope(call.getControlFlowNode()))
}
predicate uniqueNodeLocationExclude(Node n) {
// Methods with multiple implementations
n instanceof ParameterNode
@@ -55,14 +70,17 @@ private module Input implements InputSig<Location, CsharpDataFlow> {
init.getInitializer().getNumberOfChildren() > 1
)
or
call.(NonDelegateDataFlowCall).getDispatchCall().isReflection()
or
// Exclude calls that are both getter and setter calls, as they share the same argument nodes.
exists(AccessorCall ac |
call.(NonDelegateDataFlowCall).getDispatchCall().getCall() = ac and
ac instanceof AssignableRead and
ac instanceof AssignableWrite
exists(ControlFlow::Nodes::ElementNode cfn, ControlFlow::Nodes::Split split |
exists(arg.asExprAtNode(cfn))
|
split = cfn.getASplit() and
not split = call.getControlFlowNode().getASplit()
or
split = call.getControlFlowNode().getASplit() and
not split = cfn.getASplit()
)
or
call.(NonDelegateDataFlowCall).getDispatchCall().isReflection()
)
}
}

View File

@@ -1,6 +1,13 @@
import csharp
import semmle.code.csharp.dataflow.internal.DataFlowPrivate::VariableCapture::Flow::ConsistencyChecks
private import semmle.code.csharp.dataflow.internal.DataFlowPrivate::VariableCapture::Flow::ConsistencyChecks as ConsistencyChecks
private import semmle.code.csharp.controlflow.BasicBlocks
private import semmle.code.csharp.controlflow.internal.ControlFlowGraphImpl
query predicate uniqueEnclosingCallable(BasicBlock bb, string msg) {
ConsistencyChecks::uniqueEnclosingCallable(bb, msg) and
getNodeCfgScope(bb.getFirstNode()) instanceof Callable
}
query predicate consistencyOverview(string msg, int n) { none() }

View File

@@ -9,5 +9,5 @@
import csharp
from IntegerLiteral literal
where literal.getIntValue() = 0
where literal.getValue().toInt() = 0
select literal

View File

@@ -1,19 +1,3 @@
## 5.5.0
### Deprecated APIs
* The predicates `get[L|R]Value` in the class `Assignment` have been deprecated. Use `get[Left|Right]Operand` instead.
## 5.4.12
### Minor Analysis Improvements
* The extractor no longer synthesizes expanded forms of compound assignments. This may have a small impact on the results of queries that explicitly or implicitly rely on the expanded form of compound assignments.
* The `cs/log-forging` query no longer treats arguments to extension methods with
source code on `ILogger` types as sinks. Instead, taint is tracked interprocedurally
through extension method bodies, reducing false positives when extension methods
sanitize input internally.
## 5.4.11
No user-facing changes.

View File

@@ -121,17 +121,15 @@ predicate missedOfTypeOpportunity(ForeachStmtEnumerable fes, LocalVariableDeclSt
/**
* Holds if `foreach` statement `fes` can be converted to a `.Select()` call.
* That is, the loop variable is accessed only in the first statement of the
* block, the access is not a cast, the first statement is a
* local variable declaration statement `s`, and the initializer does not
* contain an `await` expression (since `Select` does not support async lambdas).
* block, the access is not a cast, and the first statement is a
* local variable declaration statement `s`.
*/
predicate missedSelectOpportunity(ForeachStmtGenericEnumerable fes, LocalVariableDeclStmt s) {
s = firstStmt(fes) and
forex(VariableAccess va | va = fes.getVariable().getAnAccess() |
va = s.getAVariableDeclExpr().getAChildExpr*()
) and
not s.getAVariableDeclExpr().getInitializer() instanceof Cast and
not s.getAVariableDeclExpr().getInitializer().getAChildExpr*() instanceof AwaitExpr
not s.getAVariableDeclExpr().getInitializer() instanceof Cast
}
/**

View File

@@ -1,8 +1,6 @@
## 5.4.12
### Minor Analysis Improvements
* The extractor no longer synthesizes expanded forms of compound assignments. This may have a small impact on the results of queries that explicitly or implicitly rely on the expanded form of compound assignments.
---
category: minorAnalysis
---
* The `cs/log-forging` query no longer treats arguments to extension methods with
source code on `ILogger` types as sinks. Instead, taint is tracked interprocedurally
through extension method bodies, reducing false positives when extension methods

View File

@@ -1,4 +0,0 @@
---
category: feature
---
* Data flow barriers and barrier guards can now be added using data extensions. For more information see [Customizing library models for C#](https://codeql.github.com/docs/codeql-language-guides/customizing-library-models-for-csharp/).

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The extractor no longer synthesizes expanded forms of compound assignments. This may have a small impact on the results of queries that explicitly or implicitly rely on the expanded form of compound assignments.

View File

@@ -1,4 +0,0 @@
---
category: minorAnalysis
---
* Expanded ASP and ASP.NET remote source modeling to cover additional sources, including fields of tainted parameters as well as properties and fields that become tainted transitively.

View File

@@ -1,5 +1,4 @@
## 5.5.0
### Deprecated APIs
---
category: deprecated
---
* The predicates `get[L|R]Value` in the class `Assignment` have been deprecated. Use `get[Left|Right]Operand` instead.

View File

@@ -1,20 +0,0 @@
---
category: breaking
---
* The C# control flow graph (CFG) implementation has been completely
rewritten. The CFG now includes additional nodes to more accurately represent
certain constructs. This also means that any existing code that implicitly
relies on very specific details about the CFG may need to be updated.
The CFG no longer uses splitting, which means that AST nodes now have a unique
CFG node representation.
Additionally, the following breaking changes have been made:
- `ControlFlow::Node` has been renamed to `ControlFlowNode`.
- `ControlFlow::Nodes` has been renamed to `ControlFlowNodes`.
- `BasicBlock.getCallable` has been renamed to `BasicBlock.getEnclosingCallable`.
- `BasicBlocks.qll` has been deleted.
- `ControlFlowNode.getAstNode` has changed its meaning. The AST-to-CFG
mapping remains one-to-many, but now for a different reason. It used to be
because of splitting, but now it's because of additional "helper" CFG
nodes. To get the (now canonical) CFG node for a given AST node, use
`ControlFlowNode.asExpr()` or `ControlFlowNode.asStmt()` or
`ControlFlowElement.getControlFlowNode()` instead.

View File

@@ -1,2 +1,2 @@
---
lastReleaseVersion: 5.5.0
lastReleaseVersion: 5.4.11

View File

@@ -30,7 +30,7 @@ predicate maybeUsedInFnvFunction(Variable v, Operation xor, Operation mul, LoopS
e2.getAChild*() = v.getAnAccess() and
e1 = xor.getAnOperand() and
e2 = mul.getAnOperand() and
xor.getControlFlowNode().getASuccessor*() = mul.getControlFlowNode() and
xor.getAControlFlowNode().getASuccessor*() = mul.getAControlFlowNode() and
(xor instanceof AssignXorExpr or xor instanceof BitwiseXorExpr) and
(mul instanceof AssignMulExpr or mul instanceof MulExpr)
) and
@@ -55,11 +55,11 @@ private predicate maybeUsedInElfHashFunction(Variable v, Operation xor, Operatio
v = addAssign.getTargetVariable() and
addAssign.getAChild*() = add and
(xor instanceof BitwiseXorExpr or xor instanceof AssignXorExpr) and
addAssign.getControlFlowNode().getASuccessor*() = xor.getControlFlowNode() and
addAssign.getAControlFlowNode().getASuccessor*() = xor.getAControlFlowNode() and
xorAssign.getAChild*() = xor and
v = xorAssign.getTargetVariable() and
(notOp instanceof UnaryBitwiseOperation or notOp instanceof AssignBitwiseOperation) and
xor.getControlFlowNode().getASuccessor*() = notOp.getControlFlowNode() and
xor.getAControlFlowNode().getASuccessor*() = notOp.getAControlFlowNode() and
notAssign.getAChild*() = notOp and
v = notAssign.getTargetVariable() and
loop.getAChild*() = add.getEnclosingStmt() and

View File

@@ -7,7 +7,7 @@
* @tags ide-contextual-queries/print-cfg
*/
import csharp
private import semmle.code.csharp.controlflow.internal.ControlFlowGraphImpl
external string selectedSourceFile();
@@ -21,7 +21,7 @@ external int selectedSourceColumn();
private predicate selectedSourceColumnAlias = selectedSourceColumn/0;
module ViewCfgQueryInput implements ControlFlow::ViewCfgQueryInputSig<File> {
module ViewCfgQueryInput implements ViewCfgQueryInputSig<File> {
predicate selectedSourceFile = selectedSourceFileAlias/0;
predicate selectedSourceLine = selectedSourceLineAlias/0;
@@ -29,7 +29,7 @@ module ViewCfgQueryInput implements ControlFlow::ViewCfgQueryInputSig<File> {
predicate selectedSourceColumn = selectedSourceColumnAlias/0;
predicate cfgScopeSpan(
Callable scope, File file, int startLine, int startColumn, int endLine, int endColumn
CfgScope scope, File file, int startLine, int startColumn, int endLine, int endColumn
) {
file = scope.getFile() and
scope.getLocation().getStartLine() = startLine and
@@ -40,20 +40,11 @@ module ViewCfgQueryInput implements ControlFlow::ViewCfgQueryInputSig<File> {
|
loc = scope.(Callable).getBody().getLocation()
or
loc = any(AssignExpr init | scope.(ObjectInitMethod).initializes(init)).getLocation()
loc = scope.(Field).getInitializer().getLocation()
or
exists(AssignableMember a, Constructor ctor |
scope = ctor and
ctor.isStatic() and
a.isStatic() and
a.getDeclaringType() = ctor.getDeclaringType()
|
loc = a.(Field).getInitializer().getLocation()
or
loc = a.(Property).getInitializer().getLocation()
)
loc = scope.(Property).getInitializer().getLocation()
)
}
}
import ControlFlow::ViewCfgQuery<File, ViewCfgQueryInput>
import ViewCfgQuery<File, ViewCfgQueryInput>

View File

@@ -1,5 +1,5 @@
name: codeql/csharp-all
version: 5.5.1-dev
version: 5.4.12-dev
groups: csharp
dbscheme: semmlecode.csharp.dbscheme
extractor: csharp

View File

@@ -85,8 +85,8 @@ class AssignableRead extends AssignableAccess {
}
pragma[noinline]
private ControlFlowNode getAnAdjacentReadSameVar() {
SsaImpl::adjacentReadPairSameVar(_, this.getControlFlowNode(), result)
private ControlFlow::Node getAnAdjacentReadSameVar() {
SsaImpl::adjacentReadPairSameVar(_, this.getAControlFlowNode(), result)
}
/**
@@ -114,7 +114,11 @@ class AssignableRead extends AssignableAccess {
* - The read of `this.Field` on line 11 is next to the read on line 10.
*/
pragma[nomagic]
AssignableRead getANextRead() { result.getControlFlowNode() = this.getAnAdjacentReadSameVar() }
AssignableRead getANextRead() {
forex(ControlFlow::Node cfn | cfn = result.getAControlFlowNode() |
cfn = this.getAnAdjacentReadSameVar()
)
}
}
/**
@@ -406,7 +410,7 @@ private import AssignableInternal
*/
class AssignableDefinition extends TAssignableDefinition {
/**
* DEPRECATED: Use `this.getExpr().getControlFlowNode()` instead.
* DEPRECATED: Use `this.getExpr().getAControlFlowNode()` instead.
*
* Gets a control flow node that updates the targeted assignable when
* reached.
@@ -415,7 +419,9 @@ class AssignableDefinition extends TAssignableDefinition {
* the definitions of `x` and `y` in `M(out x, out y)` and `(x, y) = (0, 1)`
* relate to the same call to `M` and assignment node, respectively.
*/
deprecated ControlFlowNode getAControlFlowNode() { result = this.getExpr().getControlFlowNode() }
deprecated ControlFlow::Node getAControlFlowNode() {
result = this.getExpr().getAControlFlowNode()
}
/**
* Gets the underlying expression that updates the targeted assignable when
@@ -488,7 +494,7 @@ class AssignableDefinition extends TAssignableDefinition {
*/
pragma[nomagic]
AssignableRead getAFirstRead() {
exists(ControlFlowNode cfn | cfn = result.getControlFlowNode() |
forex(ControlFlow::Node cfn | cfn = result.getAControlFlowNode() |
exists(Ssa::ExplicitDefinition def | result = def.getAFirstReadAtNode(cfn) |
this = def.getADefinition()
)
@@ -566,9 +572,11 @@ module AssignableDefinitions {
}
/** Holds if a node in basic block `bb` assigns to `ref` parameter `p` via definition `def`. */
private predicate basicBlockRefParamDef(BasicBlock bb, Parameter p, AssignableDefinition def) {
private predicate basicBlockRefParamDef(
ControlFlow::BasicBlock bb, Parameter p, AssignableDefinition def
) {
def = any(RefArg arg).getAnAnalyzableRefDef(p) and
bb.getANode() = def.getExpr().getControlFlowNode()
bb.getANode() = def.getExpr().getAControlFlowNode()
}
/**
@@ -577,7 +585,7 @@ module AssignableDefinitions {
* any assignments to `p`.
*/
pragma[nomagic]
private predicate parameterReachesWithoutDef(Parameter p, BasicBlock bb) {
private predicate parameterReachesWithoutDef(Parameter p, ControlFlow::BasicBlock bb) {
forall(AssignableDefinition def | basicBlockRefParamDef(bb, p, def) |
isUncertainRefCall(def.getTargetAccess())
) and
@@ -585,7 +593,9 @@ module AssignableDefinitions {
any(RefArg arg).isAnalyzable(p) and
p.getCallable().getEntryPoint() = bb.getFirstNode()
or
exists(BasicBlock mid | parameterReachesWithoutDef(p, mid) | bb = mid.getASuccessor())
exists(ControlFlow::BasicBlock mid | parameterReachesWithoutDef(p, mid) |
bb = mid.getASuccessor()
)
)
}
@@ -597,7 +607,7 @@ module AssignableDefinitions {
cached
predicate isUncertainRefCall(RefArg arg) {
arg.isPotentialAssignment() and
exists(BasicBlock bb, Parameter p | arg.isAnalyzable(p) |
exists(ControlFlow::BasicBlock bb, Parameter p | arg.isAnalyzable(p) |
parameterReachesWithoutDef(p, bb) and
bb.getLastNode() = p.getCallable().getExitPoint()
)
@@ -678,7 +688,7 @@ module AssignableDefinitions {
/** Gets the underlying parameter. */
Parameter getParameter() { result = p }
deprecated override ControlFlowNode getAControlFlowNode() {
deprecated override ControlFlow::Node getAControlFlowNode() {
result = p.getCallable().getEntryPoint()
}

View File

@@ -7,6 +7,23 @@ private import csharp
* in the same stage across different files.
*/
module Stages {
cached
module ControlFlowStage {
private import semmle.code.csharp.controlflow.internal.Splitting
cached
predicate forceCachingInSameStage() { any() }
cached
private predicate forceCachingInSameStageRev() {
exists(Split s)
or
exists(ControlFlow::Node n)
or
forceCachingInSameStageRev()
}
}
cached
module GuardsStage {
private import semmle.code.csharp.controlflow.Guards

View File

@@ -22,7 +22,7 @@ private import TypeRef
* an anonymous function (`AnonymousFunctionExpr`), or a local function
* (`LocalFunction`).
*/
class Callable extends Parameterizable, ControlFlowElementOrCallable, @callable {
class Callable extends Parameterizable, ExprOrStmtParent, @callable {
/** Gets the return type of this callable. */
Type getReturnType() { none() }
@@ -157,10 +157,10 @@ class Callable extends Parameterizable, ControlFlowElementOrCallable, @callable
final predicate hasExpressionBody() { exists(this.getExpressionBody()) }
/** Gets the entry point in the control graph for this callable. */
ControlFlow::EntryNode getEntryPoint() { result.getEnclosingCallable() = this }
ControlFlow::Nodes::EntryNode getEntryPoint() { result.getCallable() = this }
/** Gets the exit point in the control graph for this callable. */
ControlFlow::ExitNode getExitPoint() { result.getEnclosingCallable() = this }
ControlFlow::Nodes::ExitNode getExitPoint() { result.getCallable() = this }
/**
* Gets the enclosing callable of this callable, if any.

View File

@@ -713,7 +713,7 @@ private class SignedIntegralConstantExpr extends Expr {
}
private predicate convConstantIntExpr(SignedIntegralConstantExpr e, SimpleType toType) {
exists(int n | n = e.getIntValue() |
exists(int n | n = e.getValue().toInt() |
toType = any(SByteType t | n in [t.minValue() .. t.maxValue()])
or
toType = any(ByteType t | n in [t.minValue() .. t.maxValue()])
@@ -730,7 +730,7 @@ private predicate convConstantIntExpr(SignedIntegralConstantExpr e, SimpleType t
private predicate convConstantLongExpr(SignedIntegralConstantExpr e) {
e.getType() instanceof LongType and
e.getIntValue() >= 0
e.getValue().toInt() >= 0
}
/** 6.1.10: Implicit reference conversions involving type parameters. */

View File

@@ -129,6 +129,13 @@ private module Cached {
result = parent.getAChildStmt()
}
pragma[inline]
private ControlFlowElement enclosingStart(ControlFlowElement cfe) {
result = cfe
or
getAChild(result).(AnonymousFunctionExpr) = cfe
}
private predicate parent(ControlFlowElement child, ExprOrStmtParent parent) {
child = getAChild(parent) and
not child = getBody(_)
@@ -138,7 +145,7 @@ private module Cached {
cached
predicate enclosingBody(ControlFlowElement cfe, ControlFlowElement body) {
body = getBody(_) and
parent*(cfe, body)
parent*(enclosingStart(cfe), body)
}
/** Holds if the enclosing callable of `cfe` is `c`. */
@@ -146,7 +153,7 @@ private module Cached {
predicate enclosingCallable(ControlFlowElement cfe, Callable c) {
enclosingBody(cfe, getBody(c))
or
parent*(cfe, c.(Constructor).getInitializer())
parent*(enclosingStart(cfe), c.(Constructor).getInitializer())
or
parent*(cfe, c.(Constructor).getObjectInitializerCall())
or

View File

@@ -54,44 +54,21 @@ private string genericCollectionTypeName() {
]
}
/** A collection type */
abstract private class CollectionTypeImpl extends RefType {
/**
* Gets the element type of this collection, for example `int` in `List<int>`.
*/
abstract Type getElementType();
}
private class GenericCollectionType extends CollectionTypeImpl {
private ConstructedType base;
GenericCollectionType() {
base = this.getABaseType*() and
base.getUnboundGeneric()
.hasFullyQualifiedName(genericCollectionNamespaceName(), genericCollectionTypeName())
}
override Type getElementType() {
result = base.getTypeArgument(0) and base.getNumberOfTypeArguments() = 1
}
}
private class NonGenericCollectionType extends CollectionTypeImpl {
NonGenericCollectionType() {
/** A collection type. */
class CollectionType extends RefType {
CollectionType() {
exists(RefType base | base = this.getABaseType*() |
base.hasFullyQualifiedName(collectionNamespaceName(), collectionTypeName())
or
base.(ConstructedType)
.getUnboundGeneric()
.hasFullyQualifiedName(genericCollectionNamespaceName(), genericCollectionTypeName())
)
or
this instanceof ArrayType
}
override Type getElementType() { none() }
}
private class ArrayCollectionType extends CollectionTypeImpl instanceof ArrayType {
override Type getElementType() { result = ArrayType.super.getElementType() }
}
final class CollectionType = CollectionTypeImpl;
/**
* A collection type that can be used as a `params` parameter type.
*/

View File

@@ -161,7 +161,7 @@ private newtype TComparisonTest =
compare.getComparisonKind().isCompare() and
outerKind = outer.getComparisonKind() and
outer.getAnArgument() = compare.getExpr() and
i = outer.getAnArgument().getIntValue()
i = outer.getAnArgument().getValue().toInt()
|
outerKind.isEquality() and
(

View File

@@ -32,13 +32,13 @@ private module ConstantComparisonOperation {
private int maxValue(Expr expr) {
if convertedType(expr) instanceof IntegralType and exists(expr.getValue())
then result = expr.getIntValue()
then result = expr.getValue().toInt()
else result = convertedType(expr).maxValue()
}
private int minValue(Expr expr) {
if convertedType(expr) instanceof IntegralType and exists(expr.getValue())
then result = expr.getIntValue()
then result = expr.getValue().toInt()
else result = convertedType(expr).minValue()
}

View File

@@ -29,7 +29,7 @@ class ImplicitToStringExpr extends Expr {
m = p.getCallable()
|
m = any(SystemTextStringBuilderClass c).getAMethod() and
m.getName() = "Append" and
m.getName().regexpMatch("Append(Line)?") and
not p.getType() instanceof ArrayType
or
p instanceof StringFormatItemParameter and

View File

@@ -0,0 +1,356 @@
/**
* Provides classes representing basic blocks.
*/
import csharp
private import ControlFlow
private import semmle.code.csharp.controlflow.internal.ControlFlowGraphImpl as CfgImpl
private import CfgImpl::BasicBlocks as BasicBlocksImpl
private import codeql.controlflow.BasicBlock as BB
/**
* A basic block, that is, a maximal straight-line sequence of control flow nodes
* without branches or joins.
*/
final class BasicBlock extends BasicBlocksImpl::BasicBlock {
/** Gets an immediate successor of this basic block of a given type, if any. */
BasicBlock getASuccessor(ControlFlow::SuccessorType t) { result = super.getASuccessor(t) }
/** DEPRECATED: Use `getASuccessor` instead. */
deprecated BasicBlock getASuccessorByType(ControlFlow::SuccessorType t) {
result = this.getASuccessor(t)
}
/** Gets an immediate predecessor of this basic block of a given type, if any. */
BasicBlock getAPredecessorByType(ControlFlow::SuccessorType t) {
result = this.getAPredecessor(t)
}
/**
* Gets an immediate `true` successor, if any.
*
* An immediate `true` successor is a successor that is reached when
* the condition that ends this basic block evaluates to `true`.
*
* Example:
*
* ```csharp
* if (x < 0)
* x = -x;
* ```
*
* The basic block on line 2 is an immediate `true` successor of the
* basic block on line 1.
*/
BasicBlock getATrueSuccessor() { result.getFirstNode() = this.getLastNode().getATrueSuccessor() }
/**
* Gets an immediate `false` successor, if any.
*
* An immediate `false` successor is a successor that is reached when
* the condition that ends this basic block evaluates to `false`.
*
* Example:
*
* ```csharp
* if (!(x >= 0))
* x = -x;
* ```
*
* The basic block on line 2 is an immediate `false` successor of the
* basic block on line 1.
*/
BasicBlock getAFalseSuccessor() {
result.getFirstNode() = this.getLastNode().getAFalseSuccessor()
}
BasicBlock getASuccessor() { result = super.getASuccessor() }
/** Gets the control flow node at a specific (zero-indexed) position in this basic block. */
ControlFlow::Node getNode(int pos) { result = super.getNode(pos) }
/** Gets a control flow node in this basic block. */
ControlFlow::Node getANode() { result = super.getANode() }
/** Gets the first control flow node in this basic block. */
ControlFlow::Node getFirstNode() { result = super.getFirstNode() }
/** Gets the last control flow node in this basic block. */
ControlFlow::Node getLastNode() { result = super.getLastNode() }
/** Gets the callable that this basic block belongs to. */
final Callable getCallable() { result = this.getFirstNode().getEnclosingCallable() }
/**
* Holds if this basic block immediately dominates basic block `bb`.
*
* That is, this basic block is the unique basic block satisfying:
* 1. This basic block strictly dominates `bb`
* 2. There exists no other basic block that is strictly dominated by this
* basic block and which strictly dominates `bb`.
*
* All basic blocks, except entry basic blocks, have a unique immediate
* dominator.
*
* Example:
*
* ```csharp
* int M(string s) {
* if (s == null)
* throw new ArgumentNullException(nameof(s));
* return s.Length;
* }
* ```
*
* The basic block starting on line 2 strictly dominates the
* basic block on line 4 (all paths from the entry point of `M`
* to `return s.Length;` must go through the null check).
*/
predicate immediatelyDominates(BasicBlock bb) { super.immediatelyDominates(bb) }
/**
* Holds if this basic block strictly dominates basic block `bb`.
*
* That is, all paths reaching basic block `bb` from some entry point
* basic block must go through this basic block (which must be different
* from `bb`).
*
* Example:
*
* ```csharp
* int M(string s) {
* if (s == null)
* throw new ArgumentNullException(nameof(s));
* return s.Length;
* }
* ```
*
* The basic block starting on line 2 strictly dominates the
* basic block on line 4 (all paths from the entry point of `M`
* to `return s.Length;` must go through the null check).
*/
predicate strictlyDominates(BasicBlock bb) { super.strictlyDominates(bb) }
/**
* Holds if this basic block dominates basic block `bb`.
*
* That is, all paths reaching basic block `bb` from some entry point
* basic block must go through this basic block.
*
* Example:
*
* ```csharp
* int M(string s) {
* if (s == null)
* throw new ArgumentNullException(nameof(s));
* return s.Length;
* }
* ```
*
* The basic block starting on line 2 dominates the basic
* block on line 4 (all paths from the entry point of `M` to
* `return s.Length;` must go through the null check).
*
* This predicate is *reflexive*, so for example `if (s == null)` dominates
* itself.
*/
predicate dominates(BasicBlock bb) {
bb = this or
this.strictlyDominates(bb)
}
/**
* Holds if `df` is in the dominance frontier of this basic block.
* That is, this basic block dominates a predecessor of `df`, but
* does not dominate `df` itself.
*
* Example:
*
* ```csharp
* if (x < 0) {
* x = -x;
* if (x > 10)
* x--;
* }
* Console.Write(x);
* ```
*
* The basic block on line 6 is in the dominance frontier
* of the basic block starting on line 2 because that block
* dominates the basic block on line 4, which is a predecessor of
* `Console.Write(x);`. Also, the basic block starting on line 2
* does not dominate the basic block on line 6.
*/
predicate inDominanceFrontier(BasicBlock df) { super.inDominanceFrontier(df) }
/**
* Gets the basic block that immediately dominates this basic block, if any.
*
* That is, the result is the unique basic block satisfying:
* 1. The result strictly dominates this basic block.
* 2. There exists no other basic block that is strictly dominated by the
* result and which strictly dominates this basic block.
*
* All basic blocks, except entry basic blocks, have a unique immediate
* dominator.
*
* Example:
*
* ```csharp
* int M(string s) {
* if (s == null)
* throw new ArgumentNullException(nameof(s));
* return s.Length;
* }
* ```
*
* The basic block starting on line 2 is an immediate dominator of
* the basic block online 4 (all paths from the entry point of `M`
* to `return s.Length;` must go through the null check.
*/
BasicBlock getImmediateDominator() { result = super.getImmediateDominator() }
/**
* Holds if the edge with successor type `s` out of this basic block is a
* dominating edge for `dominated`.
*
* That is, all paths reaching `dominated` from the entry point basic
* block must go through the `s` edge out of this basic block.
*
* Edge dominance is similar to node dominance except it concerns edges
* instead of nodes: A basic block is dominated by a _basic block_ `bb` if it
* can only be reached through `bb` and dominated by an _edge_ `e` if it can
* only be reached through `e`.
*
* Note that where all basic blocks (except the entry basic block) are
* strictly dominated by at least one basic block, a basic block may not be
* dominated by any edge. If an edge dominates a basic block `bb`, then
* both endpoints of the edge dominates `bb`. The converse is not the case,
* as there may be multiple paths between the endpoints with none of them
* dominating.
*/
predicate edgeDominates(BasicBlock dominated, ControlFlow::SuccessorType s) {
super.edgeDominates(dominated, s)
}
/**
* Holds if this basic block strictly post-dominates basic block `bb`.
*
* That is, all paths reaching a normal exit point basic block from basic
* block `bb` must go through this basic block (which must be different
* from `bb`).
*
* Example:
*
* ```csharp
* int M(string s) {
* try {
* return s.Length;
* }
* finally {
* Console.WriteLine("M");
* }
* }
* ```
*
* The basic block on line 6 strictly post-dominates the basic block on
* line 3 (all paths to the exit point of `M` from `return s.Length;`
* must go through the `WriteLine` call).
*/
predicate strictlyPostDominates(BasicBlock bb) { super.strictlyPostDominates(bb) }
/**
* Holds if this basic block post-dominates basic block `bb`.
*
* That is, all paths reaching a normal exit point basic block from basic
* block `bb` must go through this basic block.
*
* Example:
*
* ```csharp
* int M(string s) {
* try {
* return s.Length;
* }
* finally {
* Console.WriteLine("M");
* }
* }
* ```
*
* The basic block on line 6 post-dominates the basic block on line 3
* (all paths to the exit point of `M` from `return s.Length;` must go
* through the `WriteLine` call).
*
* This predicate is *reflexive*, so for example `Console.WriteLine("M");`
* post-dominates itself.
*/
predicate postDominates(BasicBlock bb) { super.postDominates(bb) }
/**
* Holds if this basic block is in a loop in the control flow graph. This
* includes loops created by `goto` statements. This predicate may not hold
* even if this basic block is syntactically inside a `while` loop if the
* necessary back edges are unreachable.
*/
predicate inLoop() { this.getASuccessor+() = this }
}
/**
* An entry basic block, that is, a basic block whose first node is
* an entry node.
*/
final class EntryBasicBlock extends BasicBlock, BasicBlocksImpl::EntryBasicBlock { }
/**
* An annotated exit basic block, that is, a basic block that contains an
* annotated exit node.
*/
final class AnnotatedExitBasicBlock extends BasicBlock, BasicBlocksImpl::AnnotatedExitBasicBlock { }
/**
* An exit basic block, that is, a basic block whose last node is
* an exit node.
*/
final class ExitBasicBlock extends BasicBlock, BasicBlocksImpl::ExitBasicBlock { }
/** A basic block with more than one predecessor. */
final class JoinBlock extends BasicBlock, BasicBlocksImpl::JoinBasicBlock {
JoinBlockPredecessor getJoinBlockPredecessor(int i) { result = super.getJoinBlockPredecessor(i) }
}
/** A basic block that is an immediate predecessor of a join block. */
final class JoinBlockPredecessor extends BasicBlock, BasicBlocksImpl::JoinPredecessorBasicBlock { }
/**
* A basic block that terminates in a condition, splitting the subsequent
* control flow.
*/
final class ConditionBlock extends BasicBlock, BasicBlocksImpl::ConditionBasicBlock {
/** DEPRECATED: Use `edgeDominates` instead. */
deprecated predicate immediatelyControls(BasicBlock succ, ConditionalSuccessor s) {
this.getASuccessor(s) = succ and
BasicBlocksImpl::dominatingEdge(this, succ)
}
/** DEPRECATED: Use `edgeDominates` instead. */
deprecated predicate controls(BasicBlock controlled, ConditionalSuccessor s) {
super.edgeDominates(controlled, s)
}
}
private class BasicBlockAlias = BasicBlock;
private class EntryBasicBlockAlias = EntryBasicBlock;
module Cfg implements BB::CfgSig<Location> {
class ControlFlowNode = ControlFlow::Node;
class BasicBlock = BasicBlockAlias;
class EntryBasicBlock = EntryBasicBlockAlias;
predicate dominatingEdge(BasicBlock bb1, BasicBlock bb2) {
BasicBlocksImpl::dominatingEdge(bb1, bb2)
}
}

View File

@@ -4,21 +4,20 @@ import csharp
private import semmle.code.csharp.ExprOrStmtParent
private import semmle.code.csharp.commons.Compilation
private import ControlFlow
private import ControlFlow::BasicBlocks
private import semmle.code.csharp.Caching
private class TControlFlowElementOrCallable = @callable or @control_flow_element;
/** A `ControlFlowElement` or a `Callable`. */
class ControlFlowElementOrCallable extends ExprOrStmtParent, TControlFlowElementOrCallable { }
private import internal.ControlFlowGraphImpl as Impl
/**
* A program element that can possess control flow. That is, either a statement or
* an expression.
*
* A control flow element can be mapped to a control flow node (`ControlFlowNode`)
* via `getControlFlowNode()`.
* A control flow element can be mapped to a control flow node (`ControlFlow::Node`)
* via `getAControlFlowNode()`. There is a one-to-many relationship between
* control flow elements and control flow nodes. This allows control flow
* splitting, for example modeling the control flow through `finally` blocks.
*/
class ControlFlowElement extends ControlFlowElementOrCallable, @control_flow_element {
class ControlFlowElement extends ExprOrStmtParent, @control_flow_element {
/** Gets the enclosing callable of this element, if any. */
Callable getEnclosingCallable() { none() }
@@ -31,26 +30,41 @@ class ControlFlowElement extends ControlFlowElementOrCallable, @control_flow_ele
}
/**
* DEPRECATED: Use `getControlFlowNode()` instead.
*
* Gets a control flow node for this element. That is, a node in the
* control flow graph that corresponds to this element.
*
* Typically, there is exactly one `ControlFlow::Node` associated with a
* `ControlFlowElement`, but a `ControlFlowElement` may be split into
* several `ControlFlow::Node`s, for example to represent the continuation
* flow in a `try/catch/finally` construction.
*/
deprecated ControlFlowNodes::ElementNode getAControlFlowNode() {
result = this.getControlFlowNode()
}
Nodes::ElementNode getAControlFlowNode() { result.getAstNode() = this }
/** Gets the control flow node for this element, if any. */
ControlFlowNode getControlFlowNode() { result.injects(this) }
/** Gets the control flow node for this element. */
ControlFlow::Node getControlFlowNode() { result.getAstNode() = this }
/** Gets the basic block in which this element occurs. */
BasicBlock getBasicBlock() { result = this.getControlFlowNode().getBasicBlock() }
BasicBlock getBasicBlock() { result = this.getAControlFlowNode().getBasicBlock() }
/**
* Gets a first control flow node executed within this element.
*/
Nodes::ElementNode getAControlFlowEntryNode() {
result = Impl::getAControlFlowEntryNode(this).(ControlFlowElement).getAControlFlowNode()
}
/**
* Gets a potential last control flow node executed within this element.
*/
Nodes::ElementNode getAControlFlowExitNode() {
result = Impl::getAControlFlowExitNode(this).(ControlFlowElement).getAControlFlowNode()
}
/**
* Holds if this element is live, that is this element can be reached
* from the entry point of its enclosing callable.
*/
predicate isLive() { exists(this.getControlFlowNode()) }
predicate isLive() { exists(this.getAControlFlowNode()) }
/** Holds if the current element is reachable from `src`. */
// potentially very large predicate, so must be inlined
@@ -63,13 +77,31 @@ class ControlFlowElement extends ControlFlowElementOrCallable, @control_flow_ele
ControlFlowElement getAReachableElement() {
// Reachable in same basic block
exists(BasicBlock bb, int i, int j |
bb.getNode(i) = this.getControlFlowNode() and
bb.getNode(j) = result.getControlFlowNode() and
bb.getNode(i) = this.getAControlFlowNode() and
bb.getNode(j) = result.getAControlFlowNode() and
i < j
)
or
// Reachable in different basic blocks
this.getControlFlowNode().getBasicBlock().getASuccessor+().getANode() =
result.getControlFlowNode()
this.getAControlFlowNode().getBasicBlock().getASuccessor+().getANode() =
result.getAControlFlowNode()
}
/**
* DEPRECATED: Use `Guard` class instead.
*
* Holds if basic block `controlled` is controlled by this control flow element
* with conditional value `s`. That is, `controlled` can only be reached from
* the callable entry point by going via the `s` edge out of *some* basic block
* ending with this element.
*
* `cb` records all of the possible condition blocks for this control flow element
* that a path from the callable entry point to `controlled` may go through.
*/
deprecated predicate controlsBlock(
BasicBlock controlled, ConditionalSuccessor s, ConditionBlock cb
) {
cb.getLastNode() = this.getAControlFlowNode() and
cb.edgeDominates(controlled, s)
}
}

View File

@@ -1,577 +1,315 @@
import csharp
/**
* Provides classes representing the control flow graph within callables.
*/
import csharp
private import codeql.controlflow.ControlFlowGraph
private import codeql.controlflow.SuccessorType
private import semmle.code.csharp.commons.Compilation
private import semmle.code.csharp.controlflow.internal.NonReturning as NonReturning
private module Cfg0 = Make0<Location, Ast>;
private module Cfg1 = Make1<Input>;
private module Cfg2 = Make2<Input>;
private import Cfg0
private import Cfg1
private import Cfg2
import Public
/** Provides an implementation of the AST signature for C#. */
private module Ast implements AstSig<Location> {
private import csharp as CS
class AstNode = ControlFlowElementOrCallable;
additional predicate skipControlFlow(AstNode e) {
e instanceof TypeAccess and
not e instanceof TypeAccessPatternExpr
or
not e.getFile().fromSource()
}
private AstNode getExprChild0(Expr e, int i) {
not e instanceof NameOfExpr and
not e instanceof AnonymousFunctionExpr and
not skipControlFlow(result) and
result = e.getChild(i)
}
private AstNode getStmtChild0(Stmt s, int i) {
not s instanceof FixedStmt and
not s instanceof UsingBlockStmt and
result = s.getChild(i)
or
s =
any(FixedStmt fs |
result = fs.getVariableDeclExpr(i)
or
result = fs.getBody() and
i = max(int j | exists(fs.getVariableDeclExpr(j))) + 1
)
or
s =
any(UsingBlockStmt us |
result = us.getExpr() and
i = 0
or
result = us.getVariableDeclExpr(i)
or
result = us.getBody() and
i = max([1, count(us.getVariableDeclExpr(_))])
)
}
AstNode getChild(AstNode n, int index) {
result = getStmtChild0(n, index)
or
result = getExprChild0(n, index)
}
private AstNode getParent(AstNode n) { n = getChild(result, _) }
Callable getEnclosingCallable(AstNode node) {
result = node.(ControlFlowElement).getEnclosingCallable() or
result.(ObjectInitMethod).initializes(getParent*(node)) or
Initializers::staticMemberInitializer(result, getParent*(node))
}
class Callable = CS::Callable;
AstNode callableGetBody(Callable c) {
not skipControlFlow(result) and
result = c.getBody()
}
class Stmt = CS::Stmt;
class Expr = CS::Expr;
class BlockStmt = CS::BlockStmt;
class ExprStmt = CS::ExprStmt;
class IfStmt = CS::IfStmt;
class LoopStmt = CS::LoopStmt;
class WhileStmt = CS::WhileStmt;
class DoStmt = CS::DoStmt;
final private class FinalForStmt = CS::ForStmt;
class ForStmt extends FinalForStmt {
Expr getInit(int index) { result = this.getInitializer(index) }
}
final private class FinalForeachStmt = CS::ForeachStmt;
class ForeachStmt extends FinalForeachStmt {
Expr getVariable() {
result = this.getVariableDeclExpr() or result = this.getVariableDeclTuple()
}
Expr getCollection() { result = this.getIterableExpr() }
}
class BreakStmt = CS::BreakStmt;
class ContinueStmt = CS::ContinueStmt;
class GotoStmt = CS::GotoStmt;
class ReturnStmt = CS::ReturnStmt;
class Throw = CS::ThrowElement;
final private class FinalTryStmt = CS::TryStmt;
class TryStmt extends FinalTryStmt {
Stmt getBody() { result = this.getBlock() }
CatchClause getCatch(int index) { result = this.getCatchClause(index) }
Stmt getFinally() { result = super.getFinally() }
}
final private class FinalCatchClause = CS::CatchClause;
class CatchClause extends FinalCatchClause {
AstNode getVariable() { result = this.(CS::SpecificCatchClause).getVariableDeclExpr() }
Expr getCondition() { result = this.getFilterClause() }
Stmt getBody() { result = this.getBlock() }
}
final private class FinalSwitch = CS::Switch;
class Switch extends FinalSwitch {
Case getCase(int index) { result = super.getCase(index) }
Stmt getStmt(int index) { result = this.(CS::SwitchStmt).getStmt(index) }
}
final private class FinalCase = CS::Case;
class Case extends FinalCase {
AstNode getAPattern() { result = this.getPattern() }
Expr getGuard() { result = this.getCondition() }
AstNode getBody() { result = super.getBody() }
}
class DefaultCase extends Case instanceof CS::DefaultCase { }
class ConditionalExpr = CS::ConditionalExpr;
class BinaryExpr = CS::BinaryOperation;
class LogicalAndExpr = CS::LogicalAndExpr;
class LogicalOrExpr = CS::LogicalOrExpr;
class NullCoalescingExpr = CS::NullCoalescingExpr;
class UnaryExpr = CS::UnaryOperation;
class LogicalNotExpr = CS::LogicalNotExpr;
class Assignment = CS::Assignment;
class AssignExpr = CS::AssignExpr;
class CompoundAssignment = CS::AssignOperation;
class AssignLogicalAndExpr extends CompoundAssignment {
AssignLogicalAndExpr() { none() }
}
class AssignLogicalOrExpr extends CompoundAssignment {
AssignLogicalOrExpr() { none() }
}
class AssignNullCoalescingExpr = CS::AssignCoalesceExpr;
final private class FinalBoolLiteral = CS::BoolLiteral;
class BooleanLiteral extends FinalBoolLiteral {
boolean getValue() { result = this.getBoolValue() }
}
final private class FinalIsExpr = CS::IsExpr;
class PatternMatchExpr extends FinalIsExpr {
AstNode getPattern() { result = super.getPattern() }
}
}
/**
* A compilation.
*
* Unlike the standard `Compilation` class, this class also supports buildless
* extraction.
*/
private newtype TCompilationExt =
TCompilation(Compilation c) { not extractionIsStandalone() } or
TBuildless() { extractionIsStandalone() }
private class CompilationExt extends TCompilationExt {
string toString() {
exists(Compilation c |
this = TCompilation(c) and
result = c.toString()
)
or
this = TBuildless() and result = "buildless compilation"
}
}
/** Gets the compilation that source file `f` belongs to. */
private CompilationExt getCompilation(File f) {
exists(Compilation c |
f = c.getAFileCompiled() and
result = TCompilation(c)
)
or
result = TBuildless()
}
private module Initializers {
private import semmle.code.csharp.ExprOrStmtParent as ExprOrStmtParent
module ControlFlow {
private import semmle.code.csharp.controlflow.BasicBlocks as BBs
import semmle.code.csharp.controlflow.internal.SuccessorType
private import internal.ControlFlowGraphImpl as Impl
private import internal.Splitting as Splitting
/**
* The `expr_parent_top_level_adjusted()` relation restricted to exclude relations
* between properties and their getters' expression bodies in properties such as
* `int P => 0`.
* A control flow node.
*
* This is in order to only associate the expression body with one CFG scope, namely
* the getter (and not the declaration itself).
* Either a callable entry node (`EntryNode`), a callable exit node (`ExitNode`),
* or a control flow node for a control flow element, that is, an expression or a
* statement (`ElementNode`).
*
* A control flow node is a node in the control flow graph (CFG). There is a
* many-to-one relationship between `ElementNode`s and `ControlFlowElement`s.
* This allows control flow splitting, for example modeling the control flow
* through `finally` blocks.
*
* Only nodes that can be reached from the callable entry point are included in
* the CFG.
*/
private predicate expr_parent_top_level_adjusted2(
Expr child, int i, @top_level_exprorstmt_parent parent
) {
ExprOrStmtParent::expr_parent_top_level_adjusted(child, i, parent) and
not exists(Getter g |
g.getDeclaration() = parent and
i = 0
)
}
class Node extends Impl::Node {
/** Gets the control flow element that this node corresponds to, if any. */
final ControlFlowElement getAstNode() { result = super.getAstNode() }
/**
* Holds if `init` is a static member initializer and `staticCtor` is the
* static constructor in the same declaring type. Hence, `staticCtor` can be
* considered to execute `init` prior to the execution of its body.
*/
predicate staticMemberInitializer(Constructor staticCtor, Expr init) {
exists(Assignable a |
a.(Modifiable).isStatic() and
expr_parent_top_level_adjusted2(init, _, a) and
a.getDeclaringType() = staticCtor.getDeclaringType() and
staticCtor.isStatic()
)
}
/** Gets the basic block that this control flow node belongs to. */
BasicBlock getBasicBlock() { result.getANode() = this }
/**
* Gets the `i`th static member initializer expression for static constructor `staticCtor`.
*/
Expr initializedStaticMemberOrder(Constructor staticCtor, int i) {
result =
rank[i + 1](Expr init, Location l, string filepath, int startline, int startcolumn |
staticMemberInitializer(staticCtor, init) and
l = init.getLocation() and
l.hasLocationInfo(filepath, startline, startcolumn, _, _)
|
init order by startline, startcolumn, filepath
)
}
/**
* Gets the `i`th member initializer expression for object initializer method `obinit`.
*/
AssignExpr initializedInstanceMemberOrder(ObjectInitMethod obinit, int i) {
result =
rank[i + 1](AssignExpr ae0, Location l, string filepath, int startline, int startcolumn |
obinit.initializes(ae0) and
l = ae0.getLocation() and
l.hasLocationInfo(filepath, startline, startcolumn, _, _)
|
ae0 order by startline, startcolumn, filepath
)
}
}
private module Exceptions {
private import semmle.code.csharp.commons.Assertions
private class Overflowable extends UnaryOperation {
Overflowable() {
not this instanceof UnaryBitwiseOperation and
this.getType() instanceof IntegralType
}
}
/** Holds if `cfe` is a control flow element that may throw an exception. */
predicate mayThrowException(ControlFlowElement cfe) {
cfe.(TriedControlFlowElement).mayThrowException()
or
cfe instanceof Assertion
}
/** A control flow element that is inside a `try` block. */
private class TriedControlFlowElement extends ControlFlowElement {
TriedControlFlowElement() {
this = any(TryStmt try).getATriedElement() and
not this instanceof NonReturning::NonReturningCall
/**
* Holds if this node dominates `that` node.
*
* That is, all paths reaching `that` node from some callable entry
* node (`EntryNode`) must go through this node.
*
* Example:
*
* ```csharp
* int M(string s)
* {
* if (s == null)
* throw new ArgumentNullException(nameof(s));
* return s.Length;
* }
* ```
*
* The node on line 3 dominates the node on line 5 (all paths from the
* entry point of `M` to `return s.Length;` must go through the null check).
*
* This predicate is *reflexive*, so for example `if (s == null)` dominates
* itself.
*/
// potentially very large predicate, so must be inlined
pragma[inline]
predicate dominates(Node that) {
this.strictlyDominates(that)
or
this = that
}
/**
* Holds if this element may potentially throw an exception.
* Holds if this node strictly dominates `that` node.
*
* That is, all paths reaching `that` node from some callable entry
* node (`EntryNode`) must go through this node (which must
* be different from `that` node).
*
* Example:
*
* ```csharp
* int M(string s)
* {
* if (s == null)
* throw new ArgumentNullException(nameof(s));
* return s.Length;
* }
* ```
*
* The node on line 3 strictly dominates the node on line 5
* (all paths from the entry point of `M` to `return s.Length;` must go
* through the null check).
*/
predicate mayThrowException() {
this instanceof Overflowable
// potentially very large predicate, so must be inlined
pragma[inline]
predicate strictlyDominates(Node that) {
this.getBasicBlock().strictlyDominates(that.getBasicBlock())
or
this.(CastExpr).getType() instanceof IntegralType
or
invalidCastCandidate(this)
or
this instanceof Call
or
this =
any(MemberAccess ma |
not ma.isConditional() and
ma.getQualifier() = any(Expr e | not e instanceof TypeAccess)
)
or
this instanceof DelegateCreation
or
this instanceof ArrayCreation
or
this =
any(AddOperation ae |
ae.getType() instanceof StringType
or
ae.getType() instanceof IntegralType
)
or
this = any(SubOperation se | se.getType() instanceof IntegralType)
or
this = any(MulOperation me | me.getType() instanceof IntegralType)
or
this = any(DivOperation de | not de.getDenominator().getValue().toFloat() != 0)
or
this instanceof RemOperation
or
this instanceof DynamicExpr
exists(BasicBlock bb, int i, int j |
bb.getNode(i) = this and
bb.getNode(j) = that and
i < j
)
}
}
pragma[nomagic]
private ValueOrRefType getACastExprBaseType(CastExpr ce) {
result = ce.getType().(ValueOrRefType).getABaseType()
or
result = getACastExprBaseType(ce).getABaseType()
}
pragma[nomagic]
private predicate invalidCastCandidate(CastExpr ce) {
ce.getExpr().getType() = getACastExprBaseType(ce)
}
}
private module Input implements InputSig1, InputSig2 {
predicate cfgCachedStageRef() { CfgCachedStage::ref() }
predicate catchAll(Ast::CatchClause catch) { catch instanceof GeneralCatchClause }
predicate matchAll(Ast::Case c) { c instanceof DefaultCase or c.(SwitchCaseExpr).matchesAll() }
private newtype TLabel =
TLblGoto(string label) { any(GotoLabelStmt goto).getLabel() = label } or
TLblSwitchCase(string value) { any(GotoCaseStmt goto).getLabel() = value } or
TLblSwitchDefault()
class Label extends TLabel {
string toString() {
this = TLblGoto(result)
/**
* Holds if this node post-dominates `that` node.
*
* That is, all paths reaching a normal callable exit node (an `AnnotatedExitNode`
* with a normal exit type) from `that` node must go through this node.
*
* Example:
*
* ```csharp
* int M(string s)
* {
* try
* {
* return s.Length;
* }
* finally
* {
* Console.WriteLine("M");
* }
* }
* ```
*
* The node on line 9 post-dominates the node on line 5 (all paths to the
* exit point of `M` from `return s.Length;` must go through the `WriteLine`
* call).
*
* This predicate is *reflexive*, so for example `Console.WriteLine("M");`
* post-dominates itself.
*/
// potentially very large predicate, so must be inlined
pragma[inline]
predicate postDominates(Node that) {
this.strictlyPostDominates(that)
or
this = TLblSwitchCase(result)
or
this = TLblSwitchDefault() and result = "default"
this = that
}
}
predicate hasLabel(Ast::AstNode n, Label l) {
l = TLblGoto(n.(GotoLabelStmt).getLabel())
or
l = TLblSwitchCase(n.(GotoCaseStmt).getLabel())
or
l = TLblSwitchDefault() and n instanceof GotoDefaultStmt
or
l = TLblGoto(n.(LabelStmt).getLabel())
}
class CallableBodyPartContext = CompilationExt;
pragma[nomagic]
Ast::AstNode callableGetBodyPart(Callable c, CallableBodyPartContext ctx, int index) {
not Ast::skipControlFlow(result) and
ctx = getCompilation(result.getFile()) and
(
result = Initializers::initializedInstanceMemberOrder(c, index)
/**
* Holds if this node strictly post-dominates `that` node.
*
* That is, all paths reaching a normal callable exit node (an `AnnotatedExitNode`
* with a normal exit type) from `that` node must go through this node
* (which must be different from `that` node).
*
* Example:
*
* ```csharp
* int M(string s)
* {
* try
* {
* return s.Length;
* }
* finally
* {
* Console.WriteLine("M");
* }
* }
* ```
*
* The node on line 9 strictly post-dominates the node on line 5 (all
* paths to the exit point of `M` from `return s.Length;` must go through
* the `WriteLine` call).
*/
// potentially very large predicate, so must be inlined
pragma[inline]
predicate strictlyPostDominates(Node that) {
this.getBasicBlock().strictlyPostDominates(that.getBasicBlock())
or
result = Initializers::initializedStaticMemberOrder(c, index)
or
exists(Constructor ctor, int i, int staticMembers |
c = ctor and
staticMembers = count(Expr init | Initializers::staticMemberInitializer(ctor, init)) and
index = staticMembers + i + 1
|
i = 0 and result = ctor.getObjectInitializerCall()
or
i = 1 and result = ctor.getInitializer()
or
i = 2 and result = ctor.getBody()
exists(BasicBlock bb, int i, int j |
bb.getNode(i) = this and
bb.getNode(j) = that and
i > j
)
)
}
/** Gets a successor node of a given type, if any. */
Node getASuccessorByType(SuccessorType t) { result = this.getASuccessor(t) }
/** Gets an immediate successor, if any. */
Node getASuccessor() { result = this.getASuccessorByType(_) }
/** Gets an immediate predecessor node of a given flow type, if any. */
Node getAPredecessorByType(SuccessorType t) { result.getASuccessorByType(t) = this }
/** Gets an immediate predecessor, if any. */
Node getAPredecessor() { result = this.getAPredecessorByType(_) }
/**
* Gets an immediate `true` successor, if any.
*
* An immediate `true` successor is a successor that is reached when
* this condition evaluates to `true`.
*
* Example:
*
* ```csharp
* if (x < 0)
* x = -x;
* ```
*
* The node on line 2 is an immediate `true` successor of the node
* on line 1.
*/
Node getATrueSuccessor() {
result = this.getASuccessorByType(any(BooleanSuccessor t | t.getValue() = true))
}
/**
* Gets an immediate `false` successor, if any.
*
* An immediate `false` successor is a successor that is reached when
* this condition evaluates to `false`.
*
* Example:
*
* ```csharp
* if (!(x >= 0))
* x = -x;
* ```
*
* The node on line 2 is an immediate `false` successor of the node
* on line 1.
*/
Node getAFalseSuccessor() {
result = this.getASuccessorByType(any(BooleanSuccessor t | t.getValue() = false))
}
/** Gets the enclosing callable of this control flow node. */
final Callable getEnclosingCallable() { result = Impl::getNodeCfgScope(this) }
}
private Expr getQualifier(QualifiableExpr qe) {
result = qe.getQualifier() or
result = qe.(ExtensionMethodCall).getArgument(0)
/** Provides different types of control flow nodes. */
module Nodes {
/** A node for a callable entry point. */
class EntryNode extends Node instanceof Impl::EntryNode {
/** Gets the callable that this entry applies to. */
Callable getCallable() { result = this.getScope() }
override BasicBlocks::EntryBlock getBasicBlock() { result = Node.super.getBasicBlock() }
}
/** A node for a callable exit point, annotated with the type of exit. */
class AnnotatedExitNode extends Node instanceof Impl::AnnotatedExitNode {
/** Holds if this node represent a normal exit. */
final predicate isNormal() { super.isNormal() }
/** Gets the callable that this exit applies to. */
Callable getCallable() { result = this.getScope() }
override BasicBlocks::AnnotatedExitBlock getBasicBlock() {
result = Node.super.getBasicBlock()
}
}
/** A control flow node indicating normal termination of a callable. */
class NormalExitNode extends AnnotatedExitNode instanceof Impl::NormalExitNode { }
/** A node for a callable exit point. */
class ExitNode extends Node instanceof Impl::ExitNode {
/** Gets the callable that this exit applies to. */
Callable getCallable() { result = this.getScope() }
override BasicBlocks::ExitBlock getBasicBlock() { result = Node.super.getBasicBlock() }
}
/**
* A node for a control flow element, that is, an expression or a statement.
*
* Each control flow element maps to zero or more `ElementNode`s: zero when
* the element is in unreachable (dead) code, and multiple when there are
* different splits for the element.
*/
class ElementNode extends Node instanceof Impl::AstCfgNode {
/** Gets a comma-separated list of strings for each split in this node, if any. */
final string getSplitsString() { result = super.getSplitsString() }
/** Gets a split for this control flow node, if any. */
final Split getASplit() { result = super.getASplit() }
}
/** A control-flow node for an expression. */
class ExprNode extends ElementNode {
Expr e;
ExprNode() { e = unique(Expr e_ | e_ = this.getAstNode() | e_) }
/** Gets the expression that this control-flow node belongs to. */
Expr getExpr() { result = e }
/** Gets the value of this expression node, if any. */
string getValue() { result = e.getValue() }
/** Gets the type of this expression node. */
Type getType() { result = e.getType() }
}
class Split = Splitting::Split;
}
predicate inConditionalContext(Ast::AstNode n, ConditionKind kind) {
kind.isNullness() and
exists(QualifiableExpr qe | qe.isConditional() | n = getQualifier(qe))
}
class BasicBlock = BBs::BasicBlock;
predicate postOrInOrder(Ast::AstNode n) { n instanceof YieldStmt or n instanceof Call }
/** Provides different types of basic blocks. */
module BasicBlocks {
class EntryBlock = BBs::EntryBasicBlock;
predicate beginAbruptCompletion(
Ast::AstNode ast, PreControlFlowNode n, AbruptCompletion c, boolean always
) {
// `yield break` behaves like a return statement
ast instanceof YieldBreakStmt and
n.isIn(ast) and
c.asSimpleAbruptCompletion() instanceof ReturnSuccessor and
always = true
or
Exceptions::mayThrowException(ast) and
n.isIn(ast) and
c.asSimpleAbruptCompletion() instanceof ExceptionSuccessor and
always = false
or
ast instanceof NonReturning::NonReturningCall and
n.isIn(ast) and
c.asSimpleAbruptCompletion() instanceof ExceptionSuccessor and
always = true
}
class AnnotatedExitBlock = BBs::AnnotatedExitBasicBlock;
predicate endAbruptCompletion(Ast::AstNode ast, PreControlFlowNode n, AbruptCompletion c) {
exists(SwitchStmt switch, Label l, Ast::Case case |
ast.(Stmt).getParent() = switch and
c.getSuccessorType() instanceof GotoSuccessor and
c.hasLabel(l) and
n.isAfterValue(case, any(MatchingSuccessor t | t.getValue() = true))
|
exists(string value, ConstCase cc |
l = TLblSwitchCase(value) and
switch.getAConstCase() = cc and
cc.getLabel() = value and
cc = case
)
or
l = TLblSwitchDefault() and switch.getDefaultCase() = case
)
}
class ExitBlock = BBs::ExitBasicBlock;
predicate step(PreControlFlowNode n1, PreControlFlowNode n2) {
exists(QualifiableExpr qe | qe.isConditional() |
n1.isBefore(qe) and n2.isBefore(getQualifier(qe))
or
exists(NullnessSuccessor t | n1.isAfterValue(getQualifier(qe), t) |
if t.isNull()
then (
// if `q` is null in `q?.f = x` then the assignment is skipped. This
// holds for both regular, compound, and null-coalescing assignments.
// On the other hand, the CFG definition for the assignment can treat
// the LHS the same regardless of whether it's a conditionally
// qualified access or not, as it just connects to the "before" and
// "after" nodes of the LHS, and the "after" node is skipped in this
// case.
exists(AssignableDefinition def |
def.getTargetAccess() = qe and
n2.isAfterValue(def.getExpr(), t)
)
or
not qe instanceof AssignableWrite and
n2.isAfterValue(qe, t)
) else (
n2.isBefore(Ast::getChild(qe, 0))
or
n2.isIn(qe) and not exists(Ast::getChild(qe, 0))
)
)
or
exists(int i | i >= 0 and n1.isAfter(Ast::getChild(qe, i)) |
n2.isBefore(Ast::getChild(qe, i + 1))
or
not exists(Ast::getChild(qe, i + 1)) and n2.isIn(qe)
)
or
n1.isIn(qe) and n2.isAfter(qe) and not beginAbruptCompletion(qe, n1, _, true)
)
or
exists(ObjectCreation oc |
n1.isBefore(oc) and n2.isBefore(oc.getArgument(0))
or
n1.isBefore(oc) and n2.isIn(oc) and not exists(oc.getAnArgument())
or
exists(int i | n1.isAfter(oc.getArgument(i)) |
n2.isBefore(oc.getArgument(i + 1))
or
not exists(oc.getArgument(i + 1)) and n2.isIn(oc)
)
or
n1.isIn(oc) and n2.isBefore(oc.getInitializer())
or
n1.isIn(oc) and n2.isAfter(oc) and not exists(oc.getInitializer())
or
n1.isAfter(oc.getInitializer()) and n2.isAfter(oc)
)
}
}
/** Provides different types of control flow nodes. */
module ControlFlowNodes {
/**
* A node for a control flow element, that is, an expression or a statement.
*
* Each control flow element maps to zero or one `ElementNode`s: zero when
* the element is in unreachable (dead) code, and otherwise one.
*/
class ElementNode extends ControlFlowNode {
ElementNode() { exists(this.asExpr()) or exists(this.asStmt()) }
}
/** A control-flow node for an expression. */
class ExprNode extends ElementNode {
Expr e;
ExprNode() { e = this.asExpr() }
/** Gets the expression that this control-flow node belongs to. */
Expr getExpr() { result = e }
/** Gets the value of this expression node, if any. */
string getValue() { result = e.getValue() }
/** Gets the type of this expression node. */
Type getType() { result = e.getType() }
class JoinBlock = BBs::JoinBlock;
class JoinBlockPredecessor = BBs::JoinBlockPredecessor;
class ConditionBlock = BBs::ConditionBlock;
}
}

View File

@@ -4,13 +4,16 @@
import csharp
private import codeql.controlflow.ControlFlowReachability
private import semmle.code.csharp.controlflow.BasicBlocks
private import semmle.code.csharp.controlflow.Guards as Guards
private import semmle.code.csharp.ExprOrStmtParent
private module ControlFlowInput implements InputSig<Location, ControlFlowNode, BasicBlock> {
private module ControlFlowInput implements
InputSig<Location, ControlFlow::Node, ControlFlow::BasicBlock>
{
private import csharp as CS
AstNode getEnclosingAstNode(ControlFlowNode node) {
AstNode getEnclosingAstNode(ControlFlow::Node node) {
node.getAstNode() = result
or
not exists(node.getAstNode()) and result = node.getEnclosingCallable()

View File

@@ -7,16 +7,20 @@ private import ControlFlow
private import semmle.code.csharp.commons.Assertions
private import semmle.code.csharp.commons.ComparisonTest
private import semmle.code.csharp.commons.StructuralComparison as SC
private import semmle.code.csharp.controlflow.BasicBlocks
private import semmle.code.csharp.controlflow.internal.Completion
private import semmle.code.csharp.frameworks.System
private import semmle.code.csharp.frameworks.system.Linq
private import semmle.code.csharp.frameworks.system.Collections
private import semmle.code.csharp.frameworks.system.collections.Generic
private import codeql.controlflow.Guards as SharedGuards
private module GuardsInput implements SharedGuards::InputSig<Location, ControlFlowNode, BasicBlock> {
private module GuardsInput implements
SharedGuards::InputSig<Location, ControlFlow::Node, ControlFlow::BasicBlock>
{
private import csharp as CS
class NormalExitNode = ControlFlow::NormalExitNode;
class NormalExitNode = ControlFlow::Nodes::NormalExitNode;
class AstNode = ControlFlowElement;
@@ -56,16 +60,25 @@ private module GuardsInput implements SharedGuards::InputSig<Location, ControlFl
override boolean asBooleanValue() { boolConst(this, result) }
}
private class IntegerConstant extends ConstantExpr {
IntegerConstant() { exists(this.getIntValue()) }
private predicate intConst(Expr e, int i) {
e.getValue().toInt() = i and
(
e.getType() instanceof Enum
or
e.getType() instanceof IntegralType
)
}
override int asIntegerValue() { result = this.getIntValue() }
private class IntegerConstant extends ConstantExpr {
IntegerConstant() { intConst(this, _) }
override int asIntegerValue() { intConst(this, result) }
}
private class EnumConst extends ConstantExpr {
EnumConst() { this.getType() instanceof Enum and this.hasValue() }
override int asIntegerValue() { result = this.getIntValue() }
override int asIntegerValue() { result = this.getValue().toInt() }
}
private class StringConstant extends ConstantExpr instanceof StringLiteral {
@@ -83,14 +96,21 @@ private module GuardsInput implements SharedGuards::InputSig<Location, ControlFl
ConstantExpr asConstantCase() { super.getPattern() = result }
private predicate hasEdge(BasicBlock bb1, BasicBlock bb2, MatchingCompletion c) {
exists(PatternExpr pe |
super.getPattern() = pe and
c.isValidFor(pe) and
bb1.getLastNode() = pe.getAControlFlowNode() and
bb1.getASuccessor(c.getAMatchingSuccessorType()) = bb2
)
}
predicate matchEdge(BasicBlock bb1, BasicBlock bb2) {
bb1.getASuccessor(any(MatchingSuccessor s | s.getValue() = true)) = bb2 and
bb1.getLastNode() = AstNode.super.getControlFlowNode()
exists(MatchingCompletion c | this.hasEdge(bb1, bb2, c) and c.isMatch())
}
predicate nonMatchEdge(BasicBlock bb1, BasicBlock bb2) {
bb1.getASuccessor(any(MatchingSuccessor s | s.getValue() = false)) = bb2 and
bb1.getLastNode() = AstNode.super.getControlFlowNode()
exists(MatchingCompletion c | this.hasEdge(bb1, bb2, c) and c.isNonMatch())
}
}
@@ -302,7 +322,7 @@ class Guard extends Guards::Guard {
* In case `cfn` or `sub` access an SSA variable in their left-most qualifier, then
* so must the other (accessing the same SSA variable).
*/
predicate controlsNode(ControlFlowNodes::ElementNode cfn, AccessOrCallExpr sub, GuardValue v) {
predicate controlsNode(ControlFlow::Nodes::ElementNode cfn, AccessOrCallExpr sub, GuardValue v) {
isGuardedByNode(cfn, this, sub, v)
}
@@ -312,7 +332,7 @@ class Guard extends Guards::Guard {
* Note: This predicate is inlined.
*/
pragma[inline]
predicate controlsNode(ControlFlowNodes::ElementNode cfn, GuardValue v) {
predicate controlsNode(ControlFlow::Nodes::ElementNode cfn, GuardValue v) {
guardControls(this, cfn.getBasicBlock(), v)
}
@@ -430,8 +450,7 @@ class DereferenceableExpr extends Expr {
predicate guardSuggestsMaybeNull(Guards::Guard guard) {
not nonNullValueImplied(this) and
(
exists(guard.getControlFlowNode().getASuccessor(any(NullnessSuccessor n | n.isNull()))) and
guard = this
exists(NullnessCompletion c | c.isValidFor(this) and c.isNull() and guard = this)
or
LogicInput::additionalNullCheck(guard, _, this, true)
or
@@ -498,35 +517,35 @@ class EnumerableCollectionExpr extends Expr {
|
// x.Length == 0
ct.getComparisonKind().isEquality() and
ct.getAnArgument().getIntValue() = 0 and
ct.getAnArgument().getValue().toInt() = 0 and
branch = isEmpty
or
// x.Length == k, k > 0
ct.getComparisonKind().isEquality() and
ct.getAnArgument().getIntValue() > 0 and
ct.getAnArgument().getValue().toInt() > 0 and
branch = true and
isEmpty = false
or
// x.Length != 0
ct.getComparisonKind().isInequality() and
ct.getAnArgument().getIntValue() = 0 and
ct.getAnArgument().getValue().toInt() = 0 and
branch = isEmpty.booleanNot()
or
// x.Length != k, k != 0
ct.getComparisonKind().isInequality() and
ct.getAnArgument().getIntValue() != 0 and
ct.getAnArgument().getValue().toInt() != 0 and
branch = false and
isEmpty = false
or
// x.Length > k, k >= 0
ct.getComparisonKind().isLessThan() and
ct.getFirstArgument().getIntValue() >= 0 and
ct.getFirstArgument().getValue().toInt() >= 0 and
branch = true and
isEmpty = false
or
// x.Length >= k, k > 0
ct.getComparisonKind().isLessThanEquals() and
ct.getFirstArgument().getIntValue() > 0 and
ct.getFirstArgument().getValue().toInt() > 0 and
branch = true and
isEmpty = false
)
@@ -586,7 +605,7 @@ class AccessOrCallExpr extends Expr {
* An expression can have more than one SSA qualifier in the presence
* of control flow splitting.
*/
Ssa::Definition getAnSsaQualifier(ControlFlowNode cfn) { result = getAnSsaQualifier(this, cfn) }
Ssa::Definition getAnSsaQualifier(ControlFlow::Node cfn) { result = getAnSsaQualifier(this, cfn) }
}
private Declaration getDeclarationTarget(Expr e) {
@@ -594,14 +613,14 @@ private Declaration getDeclarationTarget(Expr e) {
result = e.(Call).getTarget()
}
private Ssa::Definition getAnSsaQualifier(Expr e, ControlFlowNode cfn) {
private Ssa::Definition getAnSsaQualifier(Expr e, ControlFlow::Node cfn) {
e = getATrackedAccess(result, cfn)
or
not e = getATrackedAccess(_, _) and
result = getAnSsaQualifier(e.(QualifiableExpr).getQualifier(), cfn)
}
private AssignableAccess getATrackedAccess(Ssa::Definition def, ControlFlowNode cfn) {
private AssignableAccess getATrackedAccess(Ssa::Definition def, ControlFlow::Node cfn) {
result = def.getAReadAtNode(cfn)
or
result = def.(Ssa::ExplicitDefinition).getADefinition().getTargetAccess() and
@@ -710,7 +729,7 @@ class GuardedExpr extends AccessOrCallExpr {
* In the example above, the node for `x.ToString()` is null-guarded in the
* split `b == true`, but not in the split `b == false`.
*/
class GuardedControlFlowNode extends ControlFlowNodes::ElementNode {
class GuardedControlFlowNode extends ControlFlow::Nodes::ElementNode {
private Guard g;
private AccessOrCallExpr sub0;
private GuardValue v0;
@@ -766,7 +785,7 @@ class GuardedDataFlowNode extends DataFlow::ExprNode {
private GuardValue v0;
GuardedDataFlowNode() {
exists(ControlFlowNodes::ElementNode cfn | exists(this.getExprAtNode(cfn)) |
exists(ControlFlow::Nodes::ElementNode cfn | exists(this.getExprAtNode(cfn)) |
g.controlsNode(cfn, sub0, v0)
)
}
@@ -1064,7 +1083,7 @@ module Internal {
candidateAux(x, d, bb) and
y =
any(AccessOrCallExpr e |
e.getControlFlowNode().getBasicBlock() = bb and
e.getAControlFlowNode().getBasicBlock() = bb and
e.getTarget() = d
)
)
@@ -1096,11 +1115,11 @@ module Internal {
pragma[nomagic]
private predicate nodeIsGuardedBySameSubExpr0(
ControlFlowNode guardedCfn, BasicBlock guardedBB, AccessOrCallExpr guarded, Guard g,
ControlFlow::Node guardedCfn, BasicBlock guardedBB, AccessOrCallExpr guarded, Guard g,
AccessOrCallExpr sub, GuardValue v
) {
Stages::GuardsStage::forceCachingInSameStage() and
guardedCfn = guarded.getControlFlowNode() and
guardedCfn = guarded.getAControlFlowNode() and
guardedBB = guardedCfn.getBasicBlock() and
guardControls(g, guardedBB, v) and
guardControlsSubSame(g, guardedBB, sub) and
@@ -1109,7 +1128,7 @@ module Internal {
pragma[nomagic]
private predicate nodeIsGuardedBySameSubExpr(
ControlFlowNode guardedCfn, BasicBlock guardedBB, AccessOrCallExpr guarded, Guard g,
ControlFlow::Node guardedCfn, BasicBlock guardedBB, AccessOrCallExpr guarded, Guard g,
AccessOrCallExpr sub, GuardValue v
) {
nodeIsGuardedBySameSubExpr0(guardedCfn, guardedBB, guarded, g, sub, v) and
@@ -1118,8 +1137,8 @@ module Internal {
pragma[nomagic]
private predicate nodeIsGuardedBySameSubExprSsaDef0(
ControlFlowNode cfn, BasicBlock guardedBB, AccessOrCallExpr guarded, Guard g,
ControlFlowNode subCfn, BasicBlock subCfnBB, AccessOrCallExpr sub, GuardValue v,
ControlFlow::Node cfn, BasicBlock guardedBB, AccessOrCallExpr guarded, Guard g,
ControlFlow::Node subCfn, BasicBlock subCfnBB, AccessOrCallExpr sub, GuardValue v,
Ssa::Definition def
) {
nodeIsGuardedBySameSubExpr(cfn, guardedBB, guarded, g, sub, v) and
@@ -1129,7 +1148,7 @@ module Internal {
pragma[nomagic]
private predicate nodeIsGuardedBySameSubExprSsaDef(
ControlFlowNode guardedCfn, AccessOrCallExpr guarded, Guard g, ControlFlowNode subCfn,
ControlFlow::Node guardedCfn, AccessOrCallExpr guarded, Guard g, ControlFlow::Node subCfn,
AccessOrCallExpr sub, GuardValue v, Ssa::Definition def
) {
exists(BasicBlock guardedBB, BasicBlock subCfnBB |
@@ -1143,13 +1162,15 @@ module Internal {
private predicate isGuardedByExpr0(
AccessOrCallExpr guarded, Guard g, AccessOrCallExpr sub, GuardValue v
) {
nodeIsGuardedBySameSubExpr(guarded.getControlFlowNode(), _, guarded, g, sub, v)
forex(ControlFlow::Node cfn | cfn = guarded.getAControlFlowNode() |
nodeIsGuardedBySameSubExpr(cfn, _, guarded, g, sub, v)
)
}
cached
predicate isGuardedByExpr(AccessOrCallExpr guarded, Guard g, AccessOrCallExpr sub, GuardValue v) {
isGuardedByExpr0(guarded, g, sub, v) and
forall(ControlFlowNode subCfn, Ssa::Definition def |
forall(ControlFlow::Node subCfn, Ssa::Definition def |
nodeIsGuardedBySameSubExprSsaDef(_, guarded, g, subCfn, sub, v, def)
|
def = guarded.getAnSsaQualifier(_)
@@ -1158,14 +1179,17 @@ module Internal {
cached
predicate isGuardedByNode(
ControlFlowNodes::ElementNode guarded, Guard g, AccessOrCallExpr sub, GuardValue v
ControlFlow::Nodes::ElementNode guarded, Guard g, AccessOrCallExpr sub, GuardValue v
) {
nodeIsGuardedBySameSubExpr(guarded, _, _, g, sub, v) and
forall(ControlFlowNode subCfn, Ssa::Definition def |
forall(ControlFlow::Node subCfn, Ssa::Definition def |
nodeIsGuardedBySameSubExprSsaDef(guarded, _, g, subCfn, sub, v, def)
|
def =
guarded.asExpr().(AccessOrCallExpr).getAnSsaQualifier(guarded.getBasicBlock().getANode())
guarded
.getAstNode()
.(AccessOrCallExpr)
.getAnSsaQualifier(guarded.getBasicBlock().getANode())
)
}
}

View File

@@ -0,0 +1,896 @@
/**
* INTERNAL: Do not use.
*
* Provides classes representing control flow completions.
*
* A completion represents how a statement or expression terminates.
*
* There are six kinds of completions: normal completion,
* `return` completion, `break` completion, `continue` completion,
* `goto` completion, and `throw` completion.
*
* Normal completions are further subdivided into Boolean completions and all
* other normal completions. A Boolean completion adds the information that the
* expression terminated with the given boolean value due to a subexpression
* terminating with the other given Boolean value. This is only relevant for
* conditional contexts in which the value controls the control-flow successor.
*
* Goto successors are further subdivided into label gotos, case gotos, and
* default gotos.
*/
import csharp
private import semmle.code.csharp.commons.Assertions
private import semmle.code.csharp.commons.Constants
private import semmle.code.csharp.frameworks.System
private import ControlFlowGraphImpl
private import NonReturning
private import SuccessorType
private newtype TCompletion =
TSimpleCompletion() or
TBooleanCompletion(boolean b) { b = true or b = false } or
TNullnessCompletion(boolean isNull) { isNull = true or isNull = false } or
TMatchingCompletion(boolean isMatch) { isMatch = true or isMatch = false } or
TEmptinessCompletion(boolean isEmpty) { isEmpty = true or isEmpty = false } or
TReturnCompletion() or
TBreakCompletion() or
TContinueCompletion() or
TGotoCompletion(string label) { label = any(GotoStmt gs).getLabel() } or
TThrowCompletion(ExceptionClass ec) or
TExitCompletion() or
TNestedCompletion(Completion inner, Completion outer, int nestLevel) {
inner = TBreakCompletion() and
outer instanceof NonNestedNormalCompletion and
nestLevel = 0
or
inner instanceof NormalCompletion and
nestedFinallyCompletion(outer, nestLevel)
}
pragma[nomagic]
private int getAFinallyNestLevel() { result = any(Statements::TryStmtTree t).nestLevel() }
pragma[nomagic]
private predicate nestedFinallyCompletion(Completion outer, int nestLevel) {
(
outer = TReturnCompletion()
or
outer = TBreakCompletion()
or
outer = TContinueCompletion()
or
outer = TGotoCompletion(_)
or
outer = TThrowCompletion(_)
or
outer = TExitCompletion()
) and
nestLevel = getAFinallyNestLevel()
}
pragma[noinline]
private predicate completionIsValidForStmt(Stmt s, Completion c) {
s instanceof BreakStmt and
c = TBreakCompletion()
or
s instanceof ContinueStmt and
c = TContinueCompletion()
or
s instanceof GotoStmt and
c = TGotoCompletion(s.(GotoStmt).getLabel())
or
s instanceof ReturnStmt and
c = TReturnCompletion()
or
s instanceof YieldBreakStmt and
// `yield break` behaves like a return statement
c = TReturnCompletion()
or
mustHaveEmptinessCompletion(s) and
c = TEmptinessCompletion(_)
}
/**
* A completion of a statement or an expression.
*/
abstract class Completion extends TCompletion {
/**
* Holds if this completion is valid for control flow element `cfe`.
*
* If `cfe` is part of a `try` statement and `cfe` may throw an exception, this
* completion can be a throw completion.
*
* If `cfe` is used in a Boolean context, this completion is a Boolean completion,
* otherwise it is a normal non-Boolean completion.
*/
predicate isValidFor(ControlFlowElement cfe) {
this = cfe.(NonReturningCall).getACompletion()
or
this = TThrowCompletion(cfe.(TriedControlFlowElement).getAThrownException())
or
cfe instanceof ThrowElement and
this = TThrowCompletion(cfe.(ThrowElement).getThrownExceptionType())
or
this = assertionCompletion(cfe, _)
or
completionIsValidForStmt(cfe, this)
or
mustHaveBooleanCompletion(cfe) and
(
exists(boolean value | isBooleanConstant(cfe, value) | this = TBooleanCompletion(value))
or
not isBooleanConstant(cfe, _) and
this = TBooleanCompletion(_)
or
// Corner case: In `if (x ?? y) { ... }`, `x` must have both a `true`
// completion, a `false` completion, and a `null` completion (but not a
// non-`null` completion)
mustHaveNullnessCompletion(cfe) and
this = TNullnessCompletion(true)
)
or
mustHaveNullnessCompletion(cfe) and
not mustHaveBooleanCompletion(cfe) and
(
exists(boolean value | isNullnessConstant(cfe, value) | this = TNullnessCompletion(value))
or
not isNullnessConstant(cfe, _) and
this = TNullnessCompletion(_)
)
or
mustHaveMatchingCompletion(cfe) and
(
exists(boolean value | isMatchingConstant(cfe, value) | this = TMatchingCompletion(value))
or
not isMatchingConstant(cfe, _) and
this = TMatchingCompletion(_)
)
or
not cfe instanceof NonReturningCall and
not cfe instanceof ThrowElement and
not cfe instanceof BreakStmt and
not cfe instanceof ContinueStmt and
not cfe instanceof GotoStmt and
not cfe instanceof ReturnStmt and
not cfe instanceof YieldBreakStmt and
not mustHaveBooleanCompletion(cfe) and
not mustHaveNullnessCompletion(cfe) and
not mustHaveMatchingCompletion(cfe) and
not mustHaveEmptinessCompletion(cfe) and
this = TSimpleCompletion()
}
/**
* Holds if this completion will continue a loop when it is the completion
* of a loop body.
*/
predicate continuesLoop() {
this instanceof NormalCompletion or
this instanceof ContinueCompletion
}
/**
* Gets the inner completion. This is either the inner completion,
* when the completion is nested, or the completion itself.
*/
Completion getInnerCompletion() { result = this }
/**
* Gets the outer completion. This is either the outer completion,
* when the completion is nested, or the completion itself.
*/
Completion getOuterCompletion() { result = this }
/** Gets a successor type that matches this completion. */
abstract SuccessorType getAMatchingSuccessorType();
/** Gets a textual representation of this completion. */
abstract string toString();
}
/** Holds if expression `e` has the Boolean constant value `value`. */
private predicate isBooleanConstant(Expr e, boolean value) {
mustHaveBooleanCompletion(e) and
(
e.getValue() = "true" and
value = true
or
e.getValue() = "false" and
value = false
or
isConstantComparison(e, value)
or
exists(Method m, Call c, Expr expr |
m = any(SystemStringClass s).getIsNullOrEmptyMethod() and
c.getTarget() = m and
e = c and
expr = c.getArgument(0) and
expr.hasValue() and
if expr.getValue().length() > 0 and not expr instanceof NullLiteral
then value = false
else value = true
)
)
}
/**
* Holds if expression `e` is constantly `null` (`value = true`) or constantly
* non-`null` (`value = false`).
*/
private predicate isNullnessConstant(Expr e, boolean value) {
mustHaveNullnessCompletion(e) and
exists(Expr stripped | stripped = e.stripCasts() |
stripped.getType() =
any(ValueType t |
not t instanceof NullableType and
// Extractor bug: the type of `x?.Length` is reported as `int`, but it should
// be `int?`
not getQualifier*(stripped).(QualifiableExpr).isConditional()
) and
value = false
or
stripped instanceof NullLiteral and
value = true
or
stripped.hasValue() and
not stripped instanceof NullLiteral and
value = false
)
}
private Expr getQualifier(QualifiableExpr e) {
// `e.getQualifier()` does not work for calls to extension methods
result = e.getChildExpr(-1)
}
pragma[noinline]
private predicate typePatternMustHaveMatchingCompletion(
TypePatternExpr tpe, Type t, Type strippedType
) {
exists(Expr e, Expr stripped | mustHaveMatchingCompletion(e, tpe) |
stripped = e.stripCasts() and
t = tpe.getCheckedType() and
strippedType = stripped.getType() and
not t.containsTypeParameters() and
not strippedType.containsTypeParameters()
)
}
pragma[noinline]
private Type typePatternCommonSubTypeLeft(Type t) {
typePatternMustHaveMatchingCompletion(_, t, _) and
result.isImplicitlyConvertibleTo(t) and
not result instanceof DynamicType
}
pragma[noinline]
private Type typePatternCommonSubTypeRight(Type strippedType) {
typePatternMustHaveMatchingCompletion(_, _, strippedType) and
result.isImplicitlyConvertibleTo(strippedType) and
not result instanceof DynamicType
}
pragma[noinline]
private predicate typePatternCommonSubType(Type t, Type strippedType) {
typePatternCommonSubTypeLeft(t) = typePatternCommonSubTypeRight(strippedType)
}
/**
* Holds if pattern expression `pe` constantly matches (`value = true`) or
* constantly non-matches (`value = false`).
*/
private predicate isMatchingConstant(PatternExpr pe, boolean value) {
exists(Expr e, string exprValue, string patternValue |
mustHaveMatchingCompletion(e, pe) and
exprValue = e.stripCasts().getValue() and
patternValue = pe.getValue() and
if exprValue = patternValue then value = true else value = false
)
or
pe instanceof DiscardPatternExpr and
value = true
or
exists(Type t, Type strippedType |
not t instanceof UnknownType and
not strippedType instanceof UnknownType and
typePatternMustHaveMatchingCompletion(pe, t, strippedType) and
not typePatternCommonSubType(t, strippedType) and
value = false
)
}
private class Overflowable extends UnaryOperation {
Overflowable() {
not this instanceof UnaryBitwiseOperation and
this.getType() instanceof IntegralType
}
}
/** A control flow element that is inside a `try` block. */
private class TriedControlFlowElement extends ControlFlowElement {
TriedControlFlowElement() {
this = any(TryStmt try).getATriedElement() and
not this instanceof NonReturningCall
}
/**
* Gets an exception class that is potentially thrown by this element, if any.
*/
Class getAThrownException() {
this instanceof Overflowable and
result instanceof SystemOverflowExceptionClass
or
this.(CastExpr).getType() instanceof IntegralType and
result instanceof SystemOverflowExceptionClass
or
invalidCastCandidate(this) and
result instanceof SystemInvalidCastExceptionClass
or
this instanceof Call and
result instanceof SystemExceptionClass
or
this =
any(MemberAccess ma |
not ma.isConditional() and
ma.getQualifier() = any(Expr e | not e instanceof TypeAccess) and
result instanceof SystemNullReferenceExceptionClass
)
or
this instanceof DelegateCreation and
result instanceof SystemOutOfMemoryExceptionClass
or
this instanceof ArrayCreation and
result instanceof SystemOutOfMemoryExceptionClass
or
this =
any(AddOperation ae |
ae.getType() instanceof StringType and
result instanceof SystemOutOfMemoryExceptionClass
or
ae.getType() instanceof IntegralType and
result instanceof SystemOverflowExceptionClass
)
or
this =
any(SubOperation se |
se.getType() instanceof IntegralType and
result instanceof SystemOverflowExceptionClass
)
or
this =
any(MulOperation me |
me.getType() instanceof IntegralType and
result instanceof SystemOverflowExceptionClass
)
or
this =
any(DivOperation de |
not de.getDenominator().getValue().toFloat() != 0 and
result instanceof SystemDivideByZeroExceptionClass
)
or
this instanceof RemOperation and
result instanceof SystemDivideByZeroExceptionClass
or
this instanceof DynamicExpr and
result instanceof SystemExceptionClass
}
}
pragma[nomagic]
private ValueOrRefType getACastExprBaseType(CastExpr ce) {
result = ce.getType().(ValueOrRefType).getABaseType()
or
result = getACastExprBaseType(ce).getABaseType()
}
pragma[nomagic]
private predicate invalidCastCandidate(CastExpr ce) {
ce.getExpr().getType() = getACastExprBaseType(ce)
}
/** Gets a valid completion when argument `i` fails in assertion `a`. */
Completion assertionCompletion(Assertion a, int i) {
exists(AssertMethod am | am = a.getAssertMethod() |
if am.getAssertionFailure(i).isExit()
then result = TExitCompletion()
else
exists(Class c |
am.getAssertionFailure(i).isException(c) and
result = TThrowCompletion(c)
)
)
}
/**
* Holds if a normal completion of `e` must be a Boolean completion.
*/
private predicate mustHaveBooleanCompletion(Expr e) {
inBooleanContext(e) and
not e instanceof NonReturningCall
}
/**
* Holds if `e` is used in a Boolean context. That is, whether the value
* that `e` evaluates to determines a true/false branch successor.
*/
private predicate inBooleanContext(Expr e) {
e = any(IfStmt is).getCondition()
or
e = any(LoopStmt ls).getCondition()
or
e = any(Case c).getCondition()
or
e = any(SpecificCatchClause scc).getFilterClause()
or
e = any(LogicalNotExpr lne | inBooleanContext(lne)).getAnOperand()
or
exists(LogicalAndExpr lae |
lae.getLeftOperand() = e
or
inBooleanContext(lae) and
lae.getRightOperand() = e
)
or
exists(LogicalOrExpr lae |
lae.getLeftOperand() = e
or
inBooleanContext(lae) and
lae.getRightOperand() = e
)
or
exists(ConditionalExpr ce |
ce.getCondition() = e
or
inBooleanContext(ce) and
e in [ce.getThen(), ce.getElse()]
)
or
e = any(NullCoalescingOperation nce | inBooleanContext(nce)).getAnOperand()
or
e = any(SwitchExpr se | inBooleanContext(se)).getACase()
or
e = any(SwitchCaseExpr sce | inBooleanContext(sce)).getBody()
}
/**
* Holds if a normal completion of `e` must be a nullness completion.
*/
private predicate mustHaveNullnessCompletion(Expr e) {
inNullnessContext(e) and
not e instanceof NonReturningCall
}
/**
* Holds if `e` is used in a nullness context. That is, whether the value
* that `e` evaluates to determines a `null`/non-`null` branch successor.
*/
private predicate inNullnessContext(Expr e) {
e = any(NullCoalescingOperation nce).getLeftOperand()
or
exists(QualifiableExpr qe | qe.isConditional() | e = qe.getChildExpr(-1))
or
exists(ConditionalExpr ce | inNullnessContext(ce) | (e = ce.getThen() or e = ce.getElse()))
or
exists(NullCoalescingOperation nce | inNullnessContext(nce) | e = nce.getRightOperand())
or
e = any(SwitchExpr se | inNullnessContext(se)).getACase()
or
e = any(SwitchCaseExpr sce | inNullnessContext(sce)).getBody()
}
/**
* Holds if `pe` is the pattern inside case `c`, belonging to `switch` `s`, that
* has the matching completion.
*/
predicate switchMatching(Switch s, Case c, PatternExpr pe) {
s.getACase() = c and
pe = c.getPattern()
}
/**
* Holds if a normal completion of `cfe` must be a matching completion. Thats is,
* whether `cfe` determines a match in a `switch/if` statement or `catch` clause.
*/
private predicate mustHaveMatchingCompletion(ControlFlowElement cfe) {
switchMatching(_, _, cfe)
or
cfe instanceof SpecificCatchClause
or
cfe = any(IsExpr ie | inBooleanContext(ie)).getPattern()
or
cfe = any(RecursivePatternExpr rpe).getAChildExpr()
or
cfe = any(PositionalPatternExpr ppe).getPattern(_)
or
cfe = any(PropertyPatternExpr ppe).getPattern(_)
or
cfe = any(UnaryPatternExpr upe | mustHaveMatchingCompletion(upe)).getPattern()
or
cfe = any(BinaryPatternExpr bpe).getAnOperand()
}
/**
* Holds if `pe` must have a matching completion, and `e` is the expression
* that is being matched.
*/
private predicate mustHaveMatchingCompletion(Expr e, PatternExpr pe) {
exists(Switch s |
switchMatching(s, _, pe) and
e = s.getExpr()
)
or
e = any(IsExpr ie | pe = ie.getPattern()).getExpr() and
mustHaveMatchingCompletion(pe)
or
exists(PatternExpr mid | mustHaveMatchingCompletion(e, mid) |
pe = mid.(UnaryPatternExpr).getPattern()
or
pe = mid.(RecursivePatternExpr).getAChildExpr()
or
pe = mid.(BinaryPatternExpr).getAnOperand()
)
}
/**
* Holds if `cfe` is the element inside foreach statement `fs` that has the emptiness
* completion.
*/
predicate foreachEmptiness(ForeachStmt fs, ControlFlowElement cfe) {
cfe = fs // use `foreach` statement itself to represent the emptiness test
}
/**
* Holds if a normal completion of `cfe` must be an emptiness completion. Thats is,
* whether `cfe` determines whether to execute the body of a `foreach` statement.
*/
private predicate mustHaveEmptinessCompletion(ControlFlowElement cfe) { foreachEmptiness(_, cfe) }
/**
* A completion that represents normal evaluation of a statement or an
* expression.
*/
abstract class NormalCompletion extends Completion { }
abstract private class NonNestedNormalCompletion extends NormalCompletion { }
/** A simple (normal) completion. */
class SimpleCompletion extends NonNestedNormalCompletion, TSimpleCompletion {
override DirectSuccessor getAMatchingSuccessorType() { any() }
override string toString() { result = "normal" }
}
/**
* A completion that represents evaluation of an expression, whose value determines
* the successor. Either a Boolean completion (`BooleanCompletion`), a nullness
* completion (`NullnessCompletion`), a matching completion (`MatchingCompletion`),
* or an emptiness completion (`EmptinessCompletion`).
*/
abstract class ConditionalCompletion extends NonNestedNormalCompletion {
/** Gets the Boolean value of this completion. */
abstract boolean getValue();
/** Gets the dual completion. */
abstract ConditionalCompletion getDual();
}
/**
* A completion that represents evaluation of an expression
* with a Boolean value.
*/
class BooleanCompletion extends ConditionalCompletion {
private boolean value;
BooleanCompletion() { this = TBooleanCompletion(value) }
override boolean getValue() { result = value }
override BooleanCompletion getDual() { result = TBooleanCompletion(value.booleanNot()) }
override BooleanSuccessor getAMatchingSuccessorType() { result.getValue() = value }
override string toString() { result = value.toString() }
}
/** A Boolean `true` completion. */
class TrueCompletion extends BooleanCompletion {
TrueCompletion() { this.getValue() = true }
}
/** A Boolean `false` completion. */
class FalseCompletion extends BooleanCompletion {
FalseCompletion() { this.getValue() = false }
}
/**
* A completion that represents evaluation of an expression that is either
* `null` or non-`null`.
*/
class NullnessCompletion extends ConditionalCompletion, TNullnessCompletion {
private boolean value;
NullnessCompletion() { this = TNullnessCompletion(value) }
/** Holds if the last sub expression of this expression evaluates to `null`. */
predicate isNull() { value = true }
/** Holds if the last sub expression of this expression evaluates to a non-`null` value. */
predicate isNonNull() { value = false }
override boolean getValue() { result = value }
override NullnessCompletion getDual() { result = TNullnessCompletion(value.booleanNot()) }
override NullnessSuccessor getAMatchingSuccessorType() { result.getValue() = value }
override string toString() { if this.isNull() then result = "null" else result = "non-null" }
}
/**
* A completion that represents matching, for example a `case` statement in a
* `switch` statement.
*/
class MatchingCompletion extends ConditionalCompletion, TMatchingCompletion {
private boolean value;
MatchingCompletion() { this = TMatchingCompletion(value) }
/** Holds if there is a match. */
predicate isMatch() { value = true }
/** Holds if there is not a match. */
predicate isNonMatch() { value = false }
override boolean getValue() { result = value }
override MatchingCompletion getDual() { result = TMatchingCompletion(value.booleanNot()) }
override MatchingSuccessor getAMatchingSuccessorType() { result.getValue() = value }
override string toString() { if this.isMatch() then result = "match" else result = "no-match" }
}
/**
* A completion that represents evaluation of an emptiness test, for example
* a test in a `foreach` statement.
*/
class EmptinessCompletion extends ConditionalCompletion, TEmptinessCompletion {
private boolean value;
EmptinessCompletion() { this = TEmptinessCompletion(value) }
/** Holds if the emptiness test evaluates to `true`. */
predicate isEmpty() { value = true }
override boolean getValue() { result = value }
override EmptinessCompletion getDual() { result = TEmptinessCompletion(value.booleanNot()) }
override EmptinessSuccessor getAMatchingSuccessorType() { result.getValue() = value }
override string toString() { if this.isEmpty() then result = "empty" else result = "non-empty" }
}
/**
* A nested completion. For example, in
*
* ```csharp
* void M(bool b1, bool b2)
* {
* try
* {
* if (b1)
* throw new Exception();
* }
* finally
* {
* if (b2)
* System.Console.WriteLine("M called");
* }
* }
* ```
*
* `b2` has an outer throw completion (inherited from `throw new Exception`)
* and an inner `false` completion. `b2` also has a (normal) `true` completion.
*/
class NestedCompletion extends Completion, TNestedCompletion {
Completion inner;
Completion outer;
int nestLevel;
NestedCompletion() { this = TNestedCompletion(inner, outer, nestLevel) }
/** Gets a completion that is compatible with the inner completion. */
Completion getAnInnerCompatibleCompletion() {
result.getOuterCompletion() = this.getInnerCompletion()
}
/** Gets the level of this nested completion. */
int getNestLevel() { result = nestLevel }
override Completion getInnerCompletion() { result = inner }
override Completion getOuterCompletion() { result = outer }
override SuccessorType getAMatchingSuccessorType() { none() }
override string toString() { result = outer + " [" + inner + "] (" + nestLevel + ")" }
}
/**
* A nested completion for a loop that exists with a `break`.
*
* This completion is added for technical reasons only: when a loop
* body can complete with a break completion, the loop itself completes
* normally. However, if we choose `TSimpleCompletion` as the completion
* of the loop, we lose the information that the last element actually
* completed with a break, meaning that the control flow edge out of the
* breaking node cannot be marked with a `break` label.
*
* Example:
*
* ```csharp
* while (...) {
* ...
* break;
* }
* return;
* ```
*
* The `break` on line 3 completes with a `TBreakCompletion`, therefore
* the `while` loop can complete with a `NestedBreakCompletion`, so we
* get an edge `break --break--> return`. (If we instead used a
* `TSimpleCompletion`, we would get a less precise edge
* `break --normal--> return`.)
*/
class NestedBreakCompletion extends NormalCompletion, NestedCompletion {
NestedBreakCompletion() {
inner = TBreakCompletion() and
outer instanceof NonNestedNormalCompletion
}
override BreakCompletion getInnerCompletion() { result = inner }
override NonNestedNormalCompletion getOuterCompletion() { result = outer }
override Completion getAnInnerCompatibleCompletion() {
result = inner and
outer = TSimpleCompletion()
or
result = TNestedCompletion(outer, inner, _)
}
override SuccessorType getAMatchingSuccessorType() {
outer instanceof SimpleCompletion and
result instanceof BreakSuccessor
or
result = outer.(ConditionalCompletion).getAMatchingSuccessorType()
}
}
/**
* A completion that represents evaluation of a statement or an
* expression resulting in a return from a callable.
*/
class ReturnCompletion extends Completion {
ReturnCompletion() {
this = TReturnCompletion() or
this = TNestedCompletion(_, TReturnCompletion(), _)
}
override ReturnSuccessor getAMatchingSuccessorType() { any() }
override string toString() {
// `NestedCompletion` defines `toString()` for the other case
this = TReturnCompletion() and result = "return"
}
}
/**
* A completion that represents evaluation of a statement or an
* expression resulting in a break (in a loop or in a `switch`
* statement).
*/
class BreakCompletion extends Completion {
BreakCompletion() {
this = TBreakCompletion() or
this = TNestedCompletion(_, TBreakCompletion(), _)
}
override BreakSuccessor getAMatchingSuccessorType() { any() }
override string toString() {
// `NestedCompletion` defines `toString()` for the other case
this = TBreakCompletion() and result = "break"
}
}
/**
* A completion that represents evaluation of a statement or an
* expression resulting in a loop continuation (a `continue`
* statement).
*/
class ContinueCompletion extends Completion {
ContinueCompletion() {
this = TContinueCompletion() or
this = TNestedCompletion(_, TContinueCompletion(), _)
}
override ContinueSuccessor getAMatchingSuccessorType() { any() }
override string toString() {
// `NestedCompletion` defines `toString()` for the other case
this = TContinueCompletion() and result = "continue"
}
}
/**
* A completion that represents evaluation of a statement or an
* expression resulting in a `goto` jump.
*/
class GotoCompletion extends Completion {
private string label;
GotoCompletion() {
this = TGotoCompletion(label) or
this = TNestedCompletion(_, TGotoCompletion(label), _)
}
/** Gets the label of the `goto` completion. */
string getLabel() { result = label }
override GotoSuccessor getAMatchingSuccessorType() { any() }
override string toString() {
// `NestedCompletion` defines `toString()` for the other case
this = TGotoCompletion(label) and result = "goto(" + label + ")"
}
}
/**
* A completion that represents evaluation of a statement or an
* expression resulting in a thrown exception.
*/
class ThrowCompletion extends Completion {
private ExceptionClass ec;
ThrowCompletion() {
this = TThrowCompletion(ec) or
this = TNestedCompletion(_, TThrowCompletion(ec), _)
}
/** Gets the type of the exception being thrown. */
ExceptionClass getExceptionClass() { result = ec }
override ExceptionSuccessor getAMatchingSuccessorType() { any() }
override string toString() {
// `NestedCompletion` defines `toString()` for the other case
this = TThrowCompletion(ec) and result = "throw(" + ec + ")"
}
}
/**
* A completion that represents evaluation of a statement or an
* expression resulting in a program exit, for example
* `System.Environment.Exit(0)`.
*
* An exit completion is different from a `return` completion; the former
* exits the whole application, and exists inside `try` statements skip
* `finally` blocks.
*/
class ExitCompletion extends Completion {
ExitCompletion() {
this = TExitCompletion() or
this = TNestedCompletion(_, TExitCompletion(), _)
}
override ExitSuccessor getAMatchingSuccessorType() { any() }
override string toString() {
// `NestedCompletion` defines `toString()` for the other case
this = TExitCompletion() and result = "exit"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -9,9 +9,13 @@ import csharp
private import semmle.code.csharp.ExprOrStmtParent
private import semmle.code.csharp.commons.Assertions
private import semmle.code.csharp.frameworks.System
private import Completion
/** A call that definitely does not return (conservative analysis). */
abstract class NonReturningCall extends Call { }
abstract class NonReturningCall extends Call {
/** Gets a valid completion for this non-returning call. */
abstract Completion getACompletion();
}
private class ExitingCall extends NonReturningCall {
ExitingCall() {
@@ -19,21 +23,36 @@ private class ExitingCall extends NonReturningCall {
or
this = any(FailingAssertion fa | fa.getAssertionFailure().isExit())
}
override ExitCompletion getACompletion() { not result instanceof NestedCompletion }
}
private class ThrowingCall extends NonReturningCall {
private ThrowCompletion c;
ThrowingCall() {
this.getTarget() instanceof ThrowingCallable
or
this.(FailingAssertion).getAssertionFailure().isException(_)
or
this =
any(MethodCall mc |
mc.getTarget()
.hasFullyQualifiedName("System.Runtime.ExceptionServices", "ExceptionDispatchInfo",
"Throw")
)
not c instanceof NestedCompletion and
(
c = this.getTarget().(ThrowingCallable).getACallCompletion()
or
this.(FailingAssertion).getAssertionFailure().isException(c.getExceptionClass())
or
this =
any(MethodCall mc |
mc.getTarget()
.hasFullyQualifiedName("System.Runtime.ExceptionServices", "ExceptionDispatchInfo",
"Throw") and
(
mc.hasNoArguments() and
c.getExceptionClass() instanceof SystemExceptionClass
or
c.getExceptionClass() = mc.getArgument(0).getType()
)
)
)
}
override ThrowCompletion getACompletion() { result = c }
}
/** Holds if accessor `a` has an auto-implementation. */
@@ -88,35 +107,44 @@ private Stmt getAnExitingStmt() {
private class ThrowingCallable extends NonReturningCallable {
ThrowingCallable() {
forex(ControlFlowElement body | body = this.getBody() | body = getAThrowingElement())
forex(ControlFlowElement body | body = this.getBody() | body = getAThrowingElement(_))
}
/** Gets a valid completion for a call to this throwing callable. */
ThrowCompletion getACallCompletion() { this.getBody() = getAThrowingElement(result) }
}
private predicate directlyThrows(ThrowElement te) {
private predicate directlyThrows(ThrowElement te, ThrowCompletion c) {
c.getExceptionClass() = te.getThrownExceptionType() and
not c instanceof NestedCompletion and
// For stub implementations, there may exist proper implementations that are not seen
// during compilation, so we conservatively rule those out
not isStub(te)
}
private ControlFlowElement getAThrowingElement() {
result instanceof ThrowingCall
private ControlFlowElement getAThrowingElement(ThrowCompletion c) {
c = result.(ThrowingCall).getACompletion()
or
directlyThrows(result)
directlyThrows(result, c)
or
result = getAThrowingStmt()
result = getAThrowingStmt(c)
}
private Stmt getAThrowingStmt() {
directlyThrows(result)
private Stmt getAThrowingStmt(ThrowCompletion c) {
directlyThrows(result, c)
or
result.(ExprStmt).getExpr() = getAThrowingElement()
result.(ExprStmt).getExpr() = getAThrowingElement(c)
or
result.(BlockStmt).getFirstStmt() = getAThrowingStmt()
result.(BlockStmt).getFirstStmt() = getAThrowingStmt(c)
or
exists(IfStmt ifStmt |
exists(IfStmt ifStmt, ThrowCompletion c1, ThrowCompletion c2 |
result = ifStmt and
ifStmt.getThen() = getAThrowingStmt() and
ifStmt.getElse() = getAThrowingStmt()
ifStmt.getThen() = getAThrowingStmt(c1) and
ifStmt.getElse() = getAThrowingStmt(c2)
|
c = c1
or
c = c2
)
}

View File

@@ -0,0 +1,124 @@
/**
* INTERNAL: Do not use.
*
* Provides classes and predicates relevant for splitting the control flow graph.
*/
import csharp
private import Completion as Comp
private import Comp
private import ControlFlowGraphImpl
private import semmle.code.csharp.controlflow.ControlFlowGraph::ControlFlow as Cfg
cached
private module Cached {
private import semmle.code.csharp.Caching
cached
newtype TSplitKind = TConditionalCompletionSplitKind()
cached
newtype TSplit = TConditionalCompletionSplit(ConditionalCompletion c)
}
import Cached
/**
* A split for a control flow element. For example, a tag that determines how to
* continue execution after leaving a `finally` block.
*/
class Split extends TSplit {
/** Gets a textual representation of this split. */
string toString() { none() }
}
module ConditionalCompletionSplitting {
/**
* A split for conditional completions. For example, in
*
* ```csharp
* void M(int i)
* {
* if (x && !y)
* System.Console.WriteLine("true")
* }
* ```
*
* we record whether `x`, `y`, and `!y` evaluate to `true` or `false`, and restrict
* the edges out of `!y` and `x && !y` accordingly.
*/
class ConditionalCompletionSplit extends Split, TConditionalCompletionSplit {
ConditionalCompletion completion;
ConditionalCompletionSplit() { this = TConditionalCompletionSplit(completion) }
ConditionalCompletion getCompletion() { result = completion }
override string toString() { result = completion.toString() }
}
private class ConditionalCompletionSplitKind_ extends SplitKind, TConditionalCompletionSplitKind {
override int getListOrder() { result = 0 }
override predicate isEnabled(AstNode cfe) { this.appliesTo(cfe) }
override string toString() { result = "ConditionalCompletion" }
}
module ConditionalCompletionSplittingInput {
private import Completion as Comp
class ConditionalCompletion = Comp::ConditionalCompletion;
class ConditionalCompletionSplitKind extends ConditionalCompletionSplitKind_, TSplitKind { }
class ConditionalCompletionSplit = ConditionalCompletionSplitting::ConditionalCompletionSplit;
bindingset[parent, parentCompletion]
predicate condPropagateExpr(
AstNode parent, ConditionalCompletion parentCompletion, AstNode child,
ConditionalCompletion childCompletion
) {
child = parent.(LogicalNotExpr).getOperand() and
childCompletion.getDual() = parentCompletion
or
childCompletion = parentCompletion and
(
child = parent.(LogicalAndExpr).getAnOperand()
or
child = parent.(LogicalOrExpr).getAnOperand()
or
parent = any(ConditionalExpr ce | child = [ce.getThen(), ce.getElse()])
or
child = parent.(SwitchExpr).getACase()
or
child = parent.(SwitchCaseExpr).getBody()
or
parent =
any(NullCoalescingOperation nce |
if childCompletion instanceof NullnessCompletion
then child = nce.getRightOperand()
else child = nce.getAnOperand()
)
)
or
child = parent.(NotPatternExpr).getPattern() and
childCompletion.getDual() = parentCompletion
or
child = parent.(IsExpr).getPattern() and
parentCompletion.(BooleanCompletion).getValue() =
childCompletion.(MatchingCompletion).getValue()
or
childCompletion = parentCompletion and
(
child = parent.(AndPatternExpr).getAnOperand()
or
child = parent.(OrPatternExpr).getAnOperand()
or
child = parent.(RecursivePatternExpr).getAChildExpr()
or
child = parent.(PropertyPatternExpr).getPattern(_)
)
}
}
}

View File

@@ -126,7 +126,7 @@ private predicate nonNullDef(Ssa::ExplicitDefinition def) {
/**
* Holds if `node` is a dereference `d` of SSA definition `def`.
*/
private predicate dereferenceAt(ControlFlowNode node, Ssa::Definition def, Dereference d) {
private predicate dereferenceAt(ControlFlow::Node node, Ssa::Definition def, Dereference d) {
d = def.getAReadAtNode(node)
}
@@ -192,7 +192,9 @@ private predicate isNullDefaultArgument(Ssa::ImplicitParameterDefinition def, Al
}
/** Holds if `def` is an SSA definition that may be `null`. */
private predicate defMaybeNull(Ssa::Definition def, ControlFlowNode node, string msg, Element reason) {
private predicate defMaybeNull(
Ssa::Definition def, ControlFlow::Node node, string msg, Element reason
) {
not nonNullDef(def) and
(
// A variable compared to `null` might be `null`
@@ -222,7 +224,7 @@ private predicate defMaybeNull(Ssa::Definition def, ControlFlowNode node, string
or
// If the source of a variable is `null` then the variable may be `null`
exists(AssignableDefinition adef | adef = def.(Ssa::ExplicitDefinition).getADefinition() |
adef.getSource() = maybeNullExpr(node.asExpr()) and
adef.getSource() = maybeNullExpr(node.getAstNode()) and
reason = adef.getExpr() and
msg = "because of $@ assignment"
)
@@ -254,19 +256,19 @@ private Ssa::Definition getAnUltimateDefinition(Ssa::Definition def) {
* through an intermediate dereference that always throws a null reference
* exception.
*/
private predicate defReaches(Ssa::Definition def, ControlFlowNode cfn) {
private predicate defReaches(Ssa::Definition def, ControlFlow::Node cfn) {
exists(def.getAFirstReadAtNode(cfn))
or
exists(ControlFlowNode mid | defReaches(def, mid) |
exists(ControlFlow::Node mid | defReaches(def, mid) |
SsaImpl::adjacentReadPairSameVar(_, mid, cfn) and
not mid = any(Dereference d | d.isAlwaysNull(def.getSourceVariable())).getControlFlowNode()
not mid = any(Dereference d | d.isAlwaysNull(def.getSourceVariable())).getAControlFlowNode()
)
}
private module NullnessConfig implements ControlFlowReachability::ConfigSig {
predicate source(ControlFlowNode node, Ssa::Definition def) { defMaybeNull(def, node, _, _) }
predicate source(ControlFlow::Node node, Ssa::Definition def) { defMaybeNull(def, node, _, _) }
predicate sink(ControlFlowNode node, Ssa::Definition def) {
predicate sink(ControlFlow::Node node, Ssa::Definition def) {
exists(Dereference d |
dereferenceAt(node, def, d) and
not d instanceof NonNullExpr
@@ -281,7 +283,9 @@ private module NullnessConfig implements ControlFlowReachability::ConfigSig {
private module NullnessFlow = ControlFlowReachability::Flow<NullnessConfig>;
predicate maybeNullDeref(Dereference d, Ssa::SourceVariable v, string msg, Element reason) {
exists(Ssa::Definition origin, Ssa::Definition ssa, ControlFlowNode src, ControlFlowNode sink |
exists(
Ssa::Definition origin, Ssa::Definition ssa, ControlFlow::Node src, ControlFlow::Node sink
|
defMaybeNull(origin, src, msg, reason) and
NullnessFlow::flow(src, origin, sink, ssa) and
ssa.getSourceVariable() = v and
@@ -384,6 +388,6 @@ class Dereference extends G::DereferenceableExpr {
*/
predicate isFirstAlwaysNull(Ssa::SourceVariable v) {
this.isAlwaysNull(v) and
defReaches(v.getAnSsaDefinition(), this.getControlFlowNode())
defReaches(v.getAnSsaDefinition(), this.getAControlFlowNode())
}
}

View File

@@ -164,8 +164,10 @@ module Ssa {
*/
class Definition extends SsaImpl::Definition {
/** Gets the control flow node of this SSA definition. */
final ControlFlowNode getControlFlowNode() {
exists(BasicBlock bb, int i | this.definesAt(_, bb, i) | result = bb.getNode(0.maximum(i)))
final ControlFlow::Node getControlFlowNode() {
exists(ControlFlow::BasicBlock bb, int i | this.definesAt(_, bb, i) |
result = bb.getNode(0.maximum(i))
)
}
/**
@@ -174,7 +176,9 @@ module Ssa {
* point it is still live, without crossing another SSA definition of the
* same source variable.
*/
final predicate isLiveAtEndOfBlock(BasicBlock bb) { SsaImpl::isLiveAtEndOfBlock(this, bb) }
final predicate isLiveAtEndOfBlock(ControlFlow::BasicBlock bb) {
SsaImpl::isLiveAtEndOfBlock(this, bb)
}
/**
* Gets a read of the source variable underlying this SSA definition that
@@ -232,7 +236,7 @@ module Ssa {
* - The reads of `this.Field` on lines 10 and 11 can be reached from the phi
* node between lines 9 and 10.
*/
final AssignableRead getAReadAtNode(ControlFlowNode cfn) {
final AssignableRead getAReadAtNode(ControlFlow::Node cfn) {
result = SsaImpl::getAReadAtNode(this, cfn)
}
@@ -306,9 +310,72 @@ module Ssa {
* Subsequent reads can be found by following the steps defined by
* `AssignableRead.getANextRead()`.
*/
final AssignableRead getAFirstReadAtNode(ControlFlowNode cfn) {
final AssignableRead getAFirstReadAtNode(ControlFlow::Node cfn) {
SsaImpl::firstReadSameVar(this, cfn) and
result.getControlFlowNode() = cfn
result.getAControlFlowNode() = cfn
}
/**
* Gets a last read of the source variable underlying this SSA definition.
* That is, a read that can reach the end of the enclosing callable, or
* another SSA definition for the source variable, without passing through
* any other read. Example:
*
* ```csharp
* int Field;
*
* void SetField(int i) {
* this.Field = i;
* Use(this.Field);
* if (i > 0)
* this.Field = i - 1;
* else if (i < 0)
* SetField(1);
* Use(this.Field);
* Use(this.Field);
* }
* ```
*
* - The reads of `i` on lines 7 and 8 are the last reads for the implicit
* parameter definition on line 3.
* - The read of `this.Field` on line 5 is a last read of the definition on
* line 4.
* - The read of `this.Field` on line 11 is a last read of the phi node
* between lines 9 and 10.
*/
deprecated final AssignableRead getALastRead() { result = this.getALastReadAtNode(_) }
/**
* Gets a last read of the source variable underlying this SSA definition at
* control flow node `cfn`. That is, a read that can reach the end of the
* enclosing callable, or another SSA definition for the source variable,
* without passing through any other read. Example:
*
* ```csharp
* int Field;
*
* void SetField(int i) {
* this.Field = i;
* Use(this.Field);
* if (i > 0)
* this.Field = i - 1;
* else if (i < 0)
* SetField(1);
* Use(this.Field);
* Use(this.Field);
* }
* ```
*
* - The reads of `i` on lines 7 and 8 are the last reads for the implicit
* parameter definition on line 3.
* - The read of `this.Field` on line 5 is a last read of the definition on
* line 4.
* - The read of `this.Field` on line 11 is a last read of the phi node
* between lines 9 and 10.
*/
deprecated final AssignableRead getALastReadAtNode(ControlFlow::Node cfn) {
SsaImpl::lastReadSameVar(this, cfn) and
result.getAControlFlowNode() = cfn
}
/**
@@ -359,9 +426,7 @@ module Ssa {
* This is either an expression, for example `x = 0`, a parameter, or a
* callable. Phi nodes have no associated syntax element.
*/
Element getElement() {
result.(ControlFlowElement).getControlFlowNode() = this.getControlFlowNode()
}
Element getElement() { result = this.getControlFlowNode().getAstNode() }
/** Gets the callable to which this SSA definition belongs. */
final Callable getEnclosingCallable() {
@@ -419,7 +484,7 @@ module Ssa {
* `M2` via the call on line 6.
*/
deprecated final predicate isCapturedVariableDefinitionFlowIn(
ImplicitEntryDefinition def, ControlFlowNodes::ElementNode c, boolean additionalCalls
ImplicitEntryDefinition def, ControlFlow::Nodes::ElementNode c, boolean additionalCalls
) {
none()
}
@@ -455,7 +520,9 @@ module Ssa {
override Element getElement() { result = ad.getElement() }
override string toString() { result = "SSA def(" + this.getSourceVariable() + ")" }
override string toString() {
result = SsaImpl::getToStringPrefix(this) + "SSA def(" + this.getSourceVariable() + ")"
}
override Location getLocation() { result = ad.getLocation() }
}
@@ -469,7 +536,7 @@ module Ssa {
*/
class ImplicitDefinition extends Definition, SsaImpl::WriteDefinition {
ImplicitDefinition() {
exists(BasicBlock bb, SourceVariable v, int i | this.definesAt(v, bb, i) |
exists(ControlFlow::BasicBlock bb, SourceVariable v, int i | this.definesAt(v, bb, i) |
SsaImpl::implicitEntryDefinition(bb, v) and
i = -1
or
@@ -487,21 +554,25 @@ module Ssa {
*/
class ImplicitEntryDefinition extends ImplicitDefinition {
ImplicitEntryDefinition() {
exists(BasicBlock bb, SourceVariable v |
exists(ControlFlow::BasicBlock bb, SourceVariable v |
this.definesAt(v, bb, -1) and
SsaImpl::implicitEntryDefinition(bb, v)
)
}
/** Gets the callable that this entry definition belongs to. */
final Callable getCallable() { result = this.getBasicBlock().getEnclosingCallable() }
final Callable getCallable() { result = this.getBasicBlock().getCallable() }
override Element getElement() { result = this.getCallable() }
override string toString() {
if this.getSourceVariable().getAssignable() instanceof LocalScopeVariable
then result = "SSA capture def(" + this.getSourceVariable() + ")"
else result = "SSA entry def(" + this.getSourceVariable() + ")"
then
result =
SsaImpl::getToStringPrefix(this) + "SSA capture def(" + this.getSourceVariable() + ")"
else
result =
SsaImpl::getToStringPrefix(this) + "SSA entry def(" + this.getSourceVariable() + ")"
}
override Location getLocation() { result = this.getCallable().getLocation() }
@@ -511,7 +582,7 @@ module Ssa {
class C = ImplicitParameterDefinition;
predicate relevantLocations(ImplicitParameterDefinition def, Location l1, Location l2) {
not def.getBasicBlock() instanceof EntryBasicBlock and
not def.getBasicBlock() instanceof ControlFlow::BasicBlocks::EntryBlock and
l1 = def.getParameter().getALocation() and
l2 = def.getBasicBlock().getLocation()
}
@@ -543,7 +614,7 @@ module Ssa {
override Element getElement() { result = this.getParameter() }
override string toString() {
result = "SSA param(" + pragma[only_bind_out](this.getParameter()) + ")"
result = SsaImpl::getToStringPrefix(this) + "SSA param(" + this.getParameter() + ")"
}
override Location getLocation() {
@@ -563,7 +634,7 @@ module Ssa {
private Call c;
ImplicitCallDefinition() {
exists(BasicBlock bb, SourceVariable v, int i |
exists(ControlFlow::BasicBlock bb, SourceVariable v, int i |
this.definesAt(v, bb, i) and
SsaImpl::updatesNamedFieldOrProp(bb, i, c, v, _)
)
@@ -585,7 +656,9 @@ module Ssa {
)
}
override string toString() { result = "SSA call def(" + this.getSourceVariable() + ")" }
override string toString() {
result = SsaImpl::getToStringPrefix(this) + "SSA call def(" + this.getSourceVariable() + ")"
}
override Location getLocation() { result = this.getCall().getLocation() }
}
@@ -598,7 +671,9 @@ module Ssa {
private Definition q;
ImplicitQualifierDefinition() {
exists(BasicBlock bb, int i, SourceVariables::QualifiedFieldOrPropSourceVariable v |
exists(
ControlFlow::BasicBlock bb, int i, SourceVariables::QualifiedFieldOrPropSourceVariable v
|
this.definesAt(v, bb, i)
|
SsaImpl::variableWriteQualifier(bb, i, v, _) and
@@ -609,7 +684,10 @@ module Ssa {
/** Gets the SSA definition for the qualifier. */
final Definition getQualifierDefinition() { result = q }
override string toString() { result = "SSA qualifier def(" + this.getSourceVariable() + ")" }
override string toString() {
result =
SsaImpl::getToStringPrefix(this) + "SSA qualifier def(" + this.getSourceVariable() + ")"
}
override Location getLocation() { result = this.getQualifierDefinition().getLocation() }
}
@@ -645,11 +723,13 @@ module Ssa {
final Definition getAnInput() { this.hasInputFromBlock(result, _) }
/** Holds if `inp` is an input to this phi node along the edge originating in `bb`. */
predicate hasInputFromBlock(Definition inp, BasicBlock bb) {
predicate hasInputFromBlock(Definition inp, ControlFlow::BasicBlock bb) {
inp = SsaImpl::phiHasInputFromBlock(this, bb)
}
override string toString() { result = "SSA phi(" + this.getSourceVariable() + ")" }
override string toString() {
result = SsaImpl::getToStringPrefix(this) + "SSA phi(" + this.getSourceVariable() + ")"
}
/*
* The location of a phi node is the same as the location of the first node

View File

@@ -11,32 +11,36 @@ private import semmle.code.csharp.dataflow.internal.rangeanalysis.SignAnalysisCo
/** Holds if `e` can be positive and cannot be negative. */
predicate positiveExpr(Expr e) {
exists(ControlFlowNode cfn | cfn = e.getControlFlowNode() |
forex(ControlFlow::Node cfn | cfn = e.getAControlFlowNode() |
positive(cfn) or strictlyPositive(cfn)
)
}
/** Holds if `e` can be negative and cannot be positive. */
predicate negativeExpr(Expr e) {
exists(ControlFlowNode cfn | cfn = e.getControlFlowNode() |
forex(ControlFlow::Node cfn | cfn = e.getAControlFlowNode() |
negative(cfn) or strictlyNegative(cfn)
)
}
/** Holds if `e` is strictly positive. */
predicate strictlyPositiveExpr(Expr e) { strictlyPositive(e.getControlFlowNode()) }
predicate strictlyPositiveExpr(Expr e) {
forex(ControlFlow::Node cfn | cfn = e.getAControlFlowNode() | strictlyPositive(cfn))
}
/** Holds if `e` is strictly negative. */
predicate strictlyNegativeExpr(Expr e) { strictlyNegative(e.getControlFlowNode()) }
predicate strictlyNegativeExpr(Expr e) {
forex(ControlFlow::Node cfn | cfn = e.getAControlFlowNode() | strictlyNegative(cfn))
}
/** Holds if `e` can be positive and cannot be negative. */
predicate positive(ControlFlowNodes::ExprNode e) { Common::positive(e) }
predicate positive(ControlFlow::Nodes::ExprNode e) { Common::positive(e) }
/** Holds if `e` can be negative and cannot be positive. */
predicate negative(ControlFlowNodes::ExprNode e) { Common::negative(e) }
predicate negative(ControlFlow::Nodes::ExprNode e) { Common::negative(e) }
/** Holds if `e` is strictly positive. */
predicate strictlyPositive(ControlFlowNodes::ExprNode e) { Common::strictlyPositive(e) }
predicate strictlyPositive(ControlFlow::Nodes::ExprNode e) { Common::strictlyPositive(e) }
/** Holds if `e` is strictly negative. */
predicate strictlyNegative(ControlFlowNodes::ExprNode e) { Common::strictlyNegative(e) }
predicate strictlyNegative(ControlFlow::Nodes::ExprNode e) { Common::strictlyNegative(e) }

View File

@@ -5,25 +5,17 @@ import csharp
*/
module BaseSsa {
private import AssignableDefinitions
private import semmle.code.csharp.controlflow.BasicBlocks as BasicBlocks
private import codeql.ssa.Ssa as SsaImplCommon
cached
private module BaseSsaStage {
cached
predicate ref() { any() }
cached
predicate backref() { (exists(any(SsaDefinition def).getARead()) implies any()) }
}
/**
* Holds if the `i`th node of basic block `bb` is assignable definition `def`,
* targeting local scope variable `v`.
*/
private predicate definitionAt(
AssignableDefinition def, BasicBlock bb, int i, SsaImplInput::SourceVariable v
AssignableDefinition def, ControlFlow::BasicBlock bb, int i, SsaInput::SourceVariable v
) {
bb.getNode(i) = def.getExpr().getControlFlowNode() and
bb.getNode(i) = def.getExpr().getAControlFlowNode() and
v = def.getTarget() and
// In cases like `(x, x) = (0, 1)`, we discard the first (dead) definition of `x`
not exists(TupleAssignmentDefinition first, TupleAssignmentDefinition second | first = def |
@@ -33,9 +25,11 @@ module BaseSsa {
)
}
private predicate entryDef(Callable c, BasicBlock bb, SsaImplInput::SourceVariable v) {
exists(EntryBasicBlock entry |
c = entry.getEnclosingCallable() and
private predicate implicitEntryDef(
Callable c, ControlFlow::BasicBlocks::EntryBlock bb, SsaInput::SourceVariable v
) {
exists(ControlFlow::BasicBlocks::EntryBlock entry |
c = entry.getCallable() and
// In case `c` has multiple bodies, we want each body to get its own implicit
// entry definition. In case `c` doesn't have multiple bodies, the line below
// is simply the same as `bb = entry`, because `entry.getFirstNode().getASuccessor()`
@@ -88,59 +82,77 @@ module BaseSsa {
}
}
private module SsaImplInput implements SsaImplCommon::InputSig<Location, BasicBlock> {
private module SsaInput implements SsaImplCommon::InputSig<Location, ControlFlow::BasicBlock> {
class SourceVariable = SimpleLocalScopeVariable;
predicate variableWrite(BasicBlock bb, int i, SourceVariable v, boolean certain) {
BaseSsaStage::ref() and
predicate variableWrite(ControlFlow::BasicBlock bb, int i, SourceVariable v, boolean certain) {
exists(AssignableDefinition def |
definitionAt(def, bb, i, v) and
if def.isCertain() then certain = true else certain = false
)
or
entryDef(_, bb, v) and
implicitEntryDef(_, bb, v) and
i = -1 and
certain = true
}
predicate variableRead(BasicBlock bb, int i, SourceVariable v, boolean certain) {
predicate variableRead(ControlFlow::BasicBlock bb, int i, SourceVariable v, boolean certain) {
exists(AssignableRead read |
read.getControlFlowNode() = bb.getNode(i) and
read.getAControlFlowNode() = bb.getNode(i) and
read.getTarget() = v and
certain = true
)
}
}
private module SsaImpl = SsaImplCommon::Make<Location, Cfg, SsaImplInput>;
private module SsaImpl = SsaImplCommon::Make<Location, BasicBlocks::Cfg, SsaInput>;
private module SsaInput implements SsaImpl::SsaInputSig {
private import csharp as CS
class Expr = CS::Expr;
class Parameter = CS::Parameter;
class VariableWrite extends AssignableDefinition {
Expr asExpr() { result = this.getExpr() }
Expr getValue() { result = this.getSource() }
predicate isParameterInit(Parameter p) {
this.(ImplicitParameterDefinition).getParameter() = p
}
class Definition extends SsaImpl::Definition {
final AssignableRead getARead() {
exists(ControlFlow::BasicBlock bb, int i |
SsaImpl::ssaDefReachesRead(_, this, bb, i) and
result.getAControlFlowNode() = bb.getNode(i)
)
}
predicate explicitWrite(VariableWrite w, BasicBlock bb, int i, SsaImplInput::SourceVariable v) {
definitionAt(w, bb, i, v)
final AssignableDefinition getDefinition() {
exists(ControlFlow::BasicBlock bb, int i, SsaInput::SourceVariable v |
this.definesAt(v, bb, i) and
definitionAt(result, bb, i, v)
)
}
final predicate isImplicitEntryDefinition(SsaInput::SourceVariable v) {
exists(ControlFlow::BasicBlock bb |
this.definesAt(v, bb, -1) and
implicitEntryDef(_, bb, v)
)
}
private Definition getAPhiInputOrPriorDefinition() {
result = this.(PhiNode).getAnInput() or
SsaImpl::uncertainWriteDefinitionInput(this, result)
}
final Definition getAnUltimateDefinition() {
result = this.getAPhiInputOrPriorDefinition*() and
not result instanceof PhiNode
}
override Location getLocation() {
result = this.getDefinition().getLocation()
or
entryDef(_, bb, v) and
i = -1 and
w.isParameterInit(v)
exists(Callable c, ControlFlow::BasicBlock bb, SsaInput::SourceVariable v |
this.definesAt(v, bb, -1) and
implicitEntryDef(c, bb, v) and
result = c.getLocation()
)
}
}
module Ssa = SsaImpl::MakeSsa<SsaInput>;
class PhiNode extends SsaImpl::PhiNode, Definition {
override Location getLocation() { result = this.getBasicBlock().getLocation() }
import Ssa
final Definition getAnInput() { SsaImpl::phiHasInputFromBlock(this, result, _) }
}
}

View File

@@ -28,8 +28,8 @@ newtype TReturnKind =
private predicate hasMultipleSourceLocations(Callable c) { strictcount(getASourceLocation(c)) > 1 }
private predicate objectInitEntry(ObjectInitMethod m, ControlFlowElement first) {
exists(ControlFlow::EntryNode en |
en.getEnclosingCallable() = m and first = en.getASuccessor().getAstNode()
exists(ControlFlow::Nodes::EntryNode en |
en.getCallable() = m and first.getControlFlowNode() = en.getASuccessor()
)
}
@@ -73,12 +73,12 @@ private module Cached {
cached
newtype TDataFlowCall =
TNonDelegateCall(ControlFlowNodes::ElementNode cfn, DispatchCall dc) {
TNonDelegateCall(ControlFlow::Nodes::ElementNode cfn, DispatchCall dc) {
DataFlowImplCommon::forceCachingInSameStage() and
cfn.asExpr() = dc.getCall()
cfn.getAstNode() = dc.getCall()
} or
TExplicitDelegateLikeCall(ControlFlowNodes::ElementNode cfn, DelegateLikeCall dc) {
cfn.asExpr() = dc
TExplicitDelegateLikeCall(ControlFlow::Nodes::ElementNode cfn, DelegateLikeCall dc) {
cfn.getAstNode() = dc
} or
TSummaryCall(FlowSummary::SummarizedCallable c, FlowSummaryImpl::Private::SummaryNode receiver) {
FlowSummaryImpl::Private::summaryCallbackRange(c, receiver)
@@ -210,63 +210,60 @@ class DataFlowCallable extends TDataFlowCallable {
}
pragma[nomagic]
private BasicBlock getAMultiBodyEntryBlock() {
private ControlFlow::Nodes::ElementNode getAMultiBodyEntryNode(ControlFlow::BasicBlock bb, int i) {
this.isMultiBodied() and
exists(ControlFlowElement body, Location l |
body = this.asCallable(l).getBody() or
objectInitEntry(this.asCallable(l), body)
|
NearestLocation<NearestBodyLocationInput>::nearestLocation(body, l, _) and
result.getANode().isBefore(body)
result = body.getAControlFlowEntryNode()
) and
bb.getNode(i) = result
}
pragma[nomagic]
private ControlFlow::Nodes::ElementNode getAMultiBodyControlFlowNodePred() {
result = this.getAMultiBodyEntryNode(_, _).getAPredecessor()
or
result = this.getAMultiBodyControlFlowNodePred().getAPredecessor()
}
pragma[nomagic]
private ControlFlow::Nodes::ElementNode getAMultiBodyControlFlowNodeSuccSameBasicBlock() {
exists(ControlFlow::BasicBlock bb, int i, int j |
exists(this.getAMultiBodyEntryNode(bb, i)) and
result = bb.getNode(j) and
j > i
)
}
pragma[nomagic]
private BasicBlock getAMultiBodyControlFlowPred() {
result = this.getAMultiBodyEntryBlock().getAPredecessor()
or
result = this.getAMultiBodyControlFlowPred().getAPredecessor()
}
pragma[nomagic]
private BasicBlock getAMultiBodyBasicBlockSucc() {
result = this.getAMultiBodyEntryBlock().getASuccessor()
private ControlFlow::BasicBlock getAMultiBodyBasicBlockSucc() {
result = this.getAMultiBodyEntryNode(_, _).getBasicBlock().getASuccessor()
or
result = this.getAMultiBodyBasicBlockSucc().getASuccessor()
}
pragma[nomagic]
private BasicBlock getAMultiBodyBasicBlock() {
pragma[inline]
private ControlFlow::Nodes::ElementNode getAMultiBodyControlFlowNode() {
result =
[
this.getAMultiBodyEntryBlock(), this.getAMultiBodyControlFlowPred(),
this.getAMultiBodyBasicBlockSucc()
this.getAMultiBodyEntryNode(_, _), this.getAMultiBodyControlFlowNodePred(),
this.getAMultiBodyControlFlowNodeSuccSameBasicBlock(),
this.getAMultiBodyBasicBlockSucc().getANode()
]
}
pragma[inline]
private ControlFlowNode getAMultiBodyControlFlowNode() {
result = this.getAMultiBodyBasicBlock().getANode()
}
/** Gets a control flow node belonging to this callable. */
pragma[inline]
ControlFlowNode getAControlFlowNode() {
ControlFlow::Node getAControlFlowNode() {
result = this.getAMultiBodyControlFlowNode()
or
not this.isMultiBodied() and
result.getEnclosingCallable() = this.asCallable(_)
}
/** Gets a basic block belonging to this callable. */
pragma[inline]
BasicBlock getABasicBlock() {
result = this.getAMultiBodyBasicBlock()
or
not this.isMultiBodied() and
result.getEnclosingCallable() = this.asCallable(_)
}
/** Gets the underlying summarized callable, if any. */
FlowSummary::SummarizedCallable asSummarizedCallable() { this = TSummarizedCallable(result) }
@@ -310,7 +307,7 @@ abstract class DataFlowCall extends TDataFlowCall {
abstract DataFlowCallable getARuntimeTarget();
/** Gets the control flow node where this call happens, if any. */
abstract ControlFlowNodes::ElementNode getControlFlowNode();
abstract ControlFlow::Nodes::ElementNode getControlFlowNode();
/** Gets the data flow node corresponding to this call, if any. */
abstract DataFlow::Node getNode();
@@ -366,7 +363,7 @@ private predicate folderDist(Folder f1, Folder f2, int i) =
/** A non-delegate C# call relevant for data flow. */
class NonDelegateDataFlowCall extends DataFlowCall, TNonDelegateCall {
private ControlFlowNodes::ElementNode cfn;
private ControlFlow::Nodes::ElementNode cfn;
private DispatchCall dc;
NonDelegateDataFlowCall() { this = TNonDelegateCall(cfn, dc) }
@@ -439,7 +436,7 @@ class NonDelegateDataFlowCall extends DataFlowCall, TNonDelegateCall {
not dc.isReflection()
}
override ControlFlowNodes::ElementNode getControlFlowNode() { result = cfn }
override ControlFlow::Nodes::ElementNode getControlFlowNode() { result = cfn }
override DataFlow::ExprNode getNode() { result.getControlFlowNode() = cfn }
@@ -455,7 +452,7 @@ abstract class DelegateDataFlowCall extends DataFlowCall { }
/** An explicit delegate or function pointer call relevant for data flow. */
class ExplicitDelegateLikeDataFlowCall extends DelegateDataFlowCall, TExplicitDelegateLikeCall {
private ControlFlowNodes::ElementNode cfn;
private ControlFlow::Nodes::ElementNode cfn;
private DelegateLikeCall dc;
ExplicitDelegateLikeDataFlowCall() { this = TExplicitDelegateLikeCall(cfn, dc) }
@@ -467,7 +464,7 @@ class ExplicitDelegateLikeDataFlowCall extends DelegateDataFlowCall, TExplicitDe
none() // handled by the shared library
}
override ControlFlowNodes::ElementNode getControlFlowNode() { result = cfn }
override ControlFlow::Nodes::ElementNode getControlFlowNode() { result = cfn }
override DataFlow::ExprNode getNode() { result.getControlFlowNode() = cfn }
@@ -498,7 +495,7 @@ class SummaryCall extends DelegateDataFlowCall, TSummaryCall {
none() // handled by the shared library
}
override ControlFlowNodes::ElementNode getControlFlowNode() { none() }
override ControlFlow::Nodes::ElementNode getControlFlowNode() { none() }
override DataFlow::Node getNode() { none() }

Some files were not shown because too many files have changed in this diff Show More