Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions actions/ql/lib/codeql/actions/controlflow/internal/Cfg.qll
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,28 @@ module CfgImpl {
boolean getValue() { none() }
}

class Pattern extends AstNode {
Pattern() { none() }
}

class AndPattern extends Pattern {
AndPattern() { none() }
}

class OrPattern extends Pattern {
OrPattern() { none() }
}

class NotPattern extends Pattern {
NotPattern() { none() }

Pattern getNegatedPattern() { none() }
}

class BindingPattern extends Pattern {
BindingPattern() { none() }
}

class PatternMatchExpr extends Expr {
PatternMatchExpr() { none() }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ internal static Expression Create(Context cx, PatternSyntax syntax, IExpressionP
if (cx.GetModel(syntax).GetDeclaredSymbol(singleDesignation) is ILocalSymbol symbol)
{
var type = symbol.GetAnnotatedType();
return VariableDeclaration.Create(cx, symbol, type, declPattern.Type, cx.CreateLocation(syntax.GetLocation()), false, parent, child, isPattern: true);
return VariableDeclaration.Create(cx, symbol, type, declPattern.Type, cx.CreateLocation(syntax.GetLocation()), false, parent, child);
}
throw new InternalError(singleDesignation, "Unable to get the declared symbol of the declaration pattern designation.");
case DiscardDesignationSyntax _:
Expand All @@ -59,7 +59,7 @@ internal static Expression Create(Context cx, PatternSyntax syntax, IExpressionP
if (cx.GetModel(syntax).GetDeclaredSymbol(varDesignation) is ILocalSymbol symbol)
{
var type = symbol.GetAnnotatedType();
return VariableDeclaration.Create(cx, symbol, type, null, cx.CreateLocation(syntax.GetLocation()), true, parent, child, isPattern: true);
return VariableDeclaration.Create(cx, symbol, type, null, cx.CreateLocation(syntax.GetLocation()), true, parent, child);
}

throw new InternalError(varPattern, "Unable to get the declared symbol of the var pattern designation.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public RecursivePattern(Context cx, RecursivePatternSyntax syntax, IExpressionPa
{
var type = symbol.GetAnnotatedType();

VariableDeclaration.Create(cx, symbol, type, null, cx.CreateLocation(syntax.GetLocation()), false, this, 0, isPattern: true);
VariableDeclaration.Create(cx, symbol, type, null, cx.CreateLocation(syntax.GetLocation()), false, this, 0);
}

if (syntax.PositionalPatternClause is PositionalPatternClauseSyntax posPc)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ protected Expression DeclareRangeVariable(Context cx, IExpressionParentEntity pa
cx.CreateLocation(node.GetLocation()),
true,
parent,
child
child,
createAccess: false
);

var nameLoc = cx.CreateLocation(name.GetLocation());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ internal class VariableDeclaration : Expression
{
private VariableDeclaration(IExpressionInfo info) : base(info) { }

public static VariableDeclaration Create(Context cx, ISymbol symbol, AnnotatedTypeSymbol? type, TypeSyntax? optionalSyntax, Location exprLocation, bool isVar, IExpressionParentEntity parent, int child, bool isPattern = false)
public static VariableDeclaration Create(Context cx, ISymbol symbol, AnnotatedTypeSymbol? type, TypeSyntax? optionalSyntax, Location exprLocation, bool isVar, IExpressionParentEntity parent, int child, bool createAccess = true)
{
var ret = new VariableDeclaration(new ExpressionInfo(cx, type, exprLocation, ExprKind.LOCAL_VAR_DECL, parent, child, isCompilerGenerated: false, null));
cx.Try(null, null, () =>
{
var l = LocalVariable.Create(cx, symbol);
l.PopulateManual(ret, isVar);
if (isPattern)
if (createAccess)
ret.CreateDefiningAccess(l, type);
if (optionalSyntax is not null)
TypeMention.Create(cx, optionalSyntax, ret, type);
Expand All @@ -43,6 +43,9 @@ private static VariableDeclaration CreateSingle(Context cx, DeclarationExpressio
{
var l = LocalVariable.Create(cx, variableSymbol);
l.PopulateManual(ret, node.Type.IsVar);
// An out declaration is itself the access in the QL model.
if (node.Parent is not ArgumentSyntax argument || !argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword))
ret.CreateDefiningAccess(l, type);
});
return ret;
}
Expand Down Expand Up @@ -88,7 +91,7 @@ public static Expression CreateParenthesized(Context cx, VarPatternSyntax varPat
case SingleVariableDesignationSyntax single:
if (cx.GetModel(variable).GetDeclaredSymbol(single) is ILocalSymbol local)
{
sub = Create(cx, local, local.GetAnnotatedType(), null, cx.CreateLocation(single.FixedLocation()), true, tuple, child0++, isPattern: true);
sub = Create(cx, local, local.GetAnnotatedType(), null, cx.CreateLocation(single.FixedLocation()), true, tuple, child0++);
}
else
{
Expand Down Expand Up @@ -159,6 +162,7 @@ public static VariableDeclaration Create(Context cx, CatchDeclarationSyntax d, b
var declSymbol = cx.GetModel(d).GetDeclaredSymbol(d)!;
var l = LocalVariable.Create(cx, declSymbol);
l.PopulateManual(ret, isVar);
ret.CreateDefiningAccess(l, type);
TypeMention.Create(cx, d.Type, ret, type);
});
return ret;
Expand All @@ -172,10 +176,10 @@ public static VariableDeclaration CreateDeclarator(Context cx, VariableDeclarato
var declSymbol = cx.GetModel(d).GetDeclaredSymbol(d)!;
var localVar = LocalVariable.Create(cx, declSymbol);
localVar.PopulateManual(ret, isVar);
ret.CreateDefiningAccess(localVar, type);

if (d.Initializer is not null)
{
ret.CreateDefiningAccess(localVar, type);
Create(cx, d.Initializer.Value, ret, 1);
}

Expand Down
2 changes: 1 addition & 1 deletion csharp/ql/consistency-queries/SsaConsistency.ql
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
exists(SsaExplicitWrite def |
d = def.getDefinition().(AssignableDefinitions::LocalVariableDefinition).getDeclaration()
|
not d = any(ForEachStmt fs).getVariableDeclExpr() and
not exists(ForEachStmt fs, int i | d.getVariable() = fs.getVariable(i)) and
not d = any(SpecificCatchClause scc).getVariableDeclExpr() and
not d.getVariable().getType() instanceof Struct and
not d instanceof PatternExpr and
Expand Down
9 changes: 6 additions & 3 deletions csharp/ql/lib/Linq/Helpers.qll
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,10 @@ private module LinqFilterOpportunity<linqCandidateSig/2 linqCandidate> {
// The linq candidate expression accesses the loop variable, and the
// candidate doesn't access an in, out, or ref parameter.
exists(Expr candidate | linqCandidate(s, candidate) |
fes.getVariable().getAnAccess() = candidate.getAChildExpr*() and
exists(AssignableRead read |
read = fes.getVariable().getAnAccess() and
read = candidate.getAChildExpr*()
) and
acceptableForLinqCapture(candidate)
)
}
Expand All @@ -146,8 +149,8 @@ private module LinqMapOpportunity<linqCandidateSig/2 linqCandidate> {
// The linq candidate (and only the candidate) expression accesses the loop variable and the
// candidate doesn't access an in, out, or ref parameter.
exists(Expr candidate | linqCandidate(s, candidate) |
forex(VariableAccess va | va = fes.getVariable().getAnAccess() |
va = candidate.getAChildExpr*()
forex(AssignableRead read | read = fes.getVariable().getAnAccess() |
read = candidate.getAChildExpr*()
) and
acceptableForLinqCapture(candidate)
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: fix
---
* The C# extractor now records defining accesses for local variable declarations without initializers and for deconstruction, `foreach`, and `catch` variables.
3 changes: 1 addition & 2 deletions csharp/ql/lib/definitions.qll
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,7 @@ private class MethodUse extends Use, QualifiableExpr {
private class AccessUse extends Access, Use {
AccessUse() {
not this.getTarget().(Parameter).getCallable() instanceof Accessor and
not this = any(LocalVariableDeclAndInitExpr d).getLeftOperand() and
not this = any(AssignableDefinitions::PatternDefinition d).getTargetAccess() and
not this = any(LocalVariableDeclExpr d).getAccess() and
not this.isImplicit() and
not this instanceof MethodAccess and // handled by `MethodUse`
not this instanceof TypeAccess and // handled by `TypeMentionUse`
Expand Down
10 changes: 7 additions & 3 deletions csharp/ql/lib/semmle/code/csharp/Assignable.qll
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ module AssignableInternal {
or
def = TAddressOfDefinition(result)
or
def = TPatternDefinition(result)
def = TPatternDefinition(any(LocalVariablePatternDecl decl | decl.getAccess() = result))
or
def = TAssignOperationDefinition(result)
or
Expand Down Expand Up @@ -385,10 +385,15 @@ module AssignableInternal {
or
def = TTupleAssignmentDefinition(_, result)
or
def =
TTupleAssignmentDefinition(_, any(LocalVariableDeclExpr decl | decl.getAccess() = result))
or
def = TOutRefDefinition(result)
or
def = TMutationDefinition(any(MutatorOperation mo | mo.getOperand() = result))
or
def = TLocalVariableDefinition(any(LocalVariableDeclExpr decl | decl.getAccess() = result))
or
def = TAddressOfDefinition(any(AddressOfExpr aoe | aoe.getOperand() = result))
or
def = TPatternDefinition(any(LocalVariablePatternDecl decl | decl.getAccess() = result))
Expand Down Expand Up @@ -476,8 +481,7 @@ class AssignableDefinition extends TAssignableDefinition {

/**
* Gets the access used in the definition of the underlying assignable,
* if any. For example, an uninitialized local variable declaration or an
* implicit parameter definition has no associated access.
* if any. For example, an implicit parameter definition has no associated access.
*/
final AssignableAccess getTargetAccess() { result = getTargetAccess(this) }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ private module Input implements InputSig1, InputSig2 {

predicate matchAll(Ast::Case c) { c.(SwitchCaseExpr).matchesAll() }

predicate patternPerformsTest(Ast::Pattern pattern) {
not pattern instanceof RecursivePatternExpr
}

predicate patternIsExhaustive(Ast::Pattern pattern) { pattern instanceof DiscardPatternExpr }

private newtype TLabel =
TLblGoto(string label) { any(GotoLabelStmt goto).getLabel() = label } or
TLblSwitchCase(string value) { any(GotoCaseStmt goto).getLabel() = value } or
Expand Down
53 changes: 19 additions & 34 deletions csharp/ql/lib/semmle/code/csharp/controlflow/Guards.qll
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ private module GuardsInput implements SharedGuards::InputSig<Location, ControlFl
ct.getComparisonKind().isInequality() and polarity = false
)
or
// todo: handled in shared lib?
exists(IsExpr ie, PatternExpr pat |
ie = eqtest and
ie.getExpr() = left and
Expand Down Expand Up @@ -190,6 +191,16 @@ private module GuardsImpl = SharedGuards::Make<Location, Cfg, GuardsInput>;

class GuardValue = GuardsImpl::GuardValue;

private PatternExpr getSameSubPattern(PatternExpr pattern) {
result = pattern
or
result = getSameSubPattern(pattern).(AndPatternExpr).getAnOperand()
or
result = getSameSubPattern(pattern).(OrPatternExpr).getAnOperand()
or
result = getSameSubPattern(pattern).(NotPatternExpr).getPattern()
}

private module LogicInput implements GuardsImpl::LogicInputSig {
import Ssa

Expand Down Expand Up @@ -217,22 +228,14 @@ private module LogicInput implements GuardsImpl::LogicInputSig {
isNull = false
)
or
guard =
any(PatternMatch pm |
e instanceof DereferenceableExpr and
e = pm.getExpr() and
(
val.asBooleanValue().booleanNot() = patternMatchesNull(pm.getPattern()) and
isNull = false
or
exists(TypePatternExpr tpe |
// E.g. `x is string` where `x` has type `string`
typePattern(guard, tpe, tpe.getCheckedType()) and
val.asBooleanValue() = false and
isNull = true
)
)
)
exists(PatternMatch pm |
e instanceof DereferenceableExpr and
e = pm.getExpr() and
guard = getSameSubPattern(pm.getPattern())
|
val.asMatchValue() = true and
isNull = patternMatchesNull(guard)
)
or
e.(DereferenceableExpr).hasNullableType() and
guard =
Expand Down Expand Up @@ -355,24 +358,6 @@ private boolean patternMatchesNull(PatternExpr pat) {
not pat instanceof OrPatternExpr and
not pat instanceof AndPatternExpr and
result = false
or
result = patternMatchesNull(pat.(NotPatternExpr).getPattern()).booleanNot()
or
exists(OrPatternExpr ope | pat = ope |
result =
patternMatchesNull(ope.getLeftOperand()).booleanOr(patternMatchesNull(ope.getRightOperand()))
)
or
exists(AndPatternExpr ape | pat = ape |
result =
patternMatchesNull(ape.getLeftOperand()).booleanAnd(patternMatchesNull(ape.getRightOperand()))
)
}

pragma[nomagic]
private predicate typePattern(PatternMatch pm, TypePatternExpr tpe, Type t) {
tpe = pm.getPattern() and
t = pm.getExpr().getType()
}

pragma[nomagic]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ module Ast implements AstSig<Location> {

additional predicate skipControlFlow(AstNode e) {
e instanceof TypeAccess and
not e instanceof TypeAccessPatternExpr and
// not e instanceof TypeAccessPatternExpr and
not any(CS::SpecificCatchClause sc).getTypeAccess() = e
or
not e.getFile().fromSource()
Expand Down Expand Up @@ -295,6 +295,24 @@ module Ast implements AstSig<Location> {
boolean getValue() { result = this.getBoolValue() }
}

final class Pattern = PatternImpl;

abstract private class PatternImpl extends AstNode { }

private class PatternExprPattern extends PatternImpl, CS::PatternExpr { }

class AndPattern extends Pattern instanceof CS::AndPatternExpr { }

class OrPattern extends Pattern instanceof CS::OrPatternExpr { }

class NotPattern extends Pattern instanceof CS::NotPatternExpr {
Pattern getNegatedPattern() { result = super.getPattern() }
}

class BindingPattern extends PatternImpl {
BindingPattern() { this = any(CS::VariablePatternExpr vp).getAccess() }
}

final private class FinalIsExpr = CS::IsExpr;

class PatternMatchExpr extends FinalIsExpr {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,9 @@ private module Impl {
* true.
*/
predicate isEquality(ExprNode e1, ExprNode e2, boolean polarity) {
exists(Expr e1_, Expr e2_ |
e1 = unique(ExprNode cfn | hasChild(this, e1_, _, cfn) | cfn) and
e2 = unique(ExprNode cfn | hasChild(this, e2_, _, cfn) | cfn) and
super.isEquality(e1_, e2_, any(G::GuardValue gv | gv.asBooleanValue() = polarity))
)
super
.isEquality(e1.getExpr(), e2.getExpr(),
any(G::GuardValue gv | gv.asBooleanValue() = polarity))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ where
a = any(AssignExpr ass | ass.getRightOperand() instanceof ObjectCreation).getLeftOperand() or
a =
any(LocalVariableDeclAndInitExpr ass | ass.getRightOperand() instanceof ObjectCreation)
.getLeftOperand()
.getLeftOperand() or
a =
any(LocalVariableDeclExpr decl |
not decl.hasInitializer() and
not decl.isOutArgument()
).getAccess()
) and
not v = any(ForEachStmt fs).getVariable() and
not v = any(BindingPatternExpr vpe).getVariableDeclExpr().getVariable() and
Expand Down
Loading
Loading