Skip to content
Open
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
54 changes: 54 additions & 0 deletions unified/ql/lib/codeql/unified/internal/AstExtra.qll
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,46 @@ module Public {
override Expr getValue() { result = this.getRight() }
}

/** A compound assignment with a bitwise AND operator. */
class AssignBitwiseAndExpr extends CompoundAssignExpr {
AssignBitwiseAndExpr() { this.getOperator().getValue() = "&=" }
}

/** A compound assignment with a bitwise OR operator. */
class AssignBitwiseOrExpr extends CompoundAssignExpr {
AssignBitwiseOrExpr() { this.getOperator().getValue() = "|=" }
}

/** A compound assignment with a bitwise XOR operator. */
class AssignBitwiseXorExpr extends CompoundAssignExpr {
AssignBitwiseXorExpr() { this.getOperator().getValue() = "^=" }
}

/** A compound assignment with a short-circuiting logical AND operator. */
class AssignLogicalAndExpr extends CompoundAssignExpr {
AssignLogicalAndExpr() { this.getOperator().getValue() = "&&=" }
}

/** A compound assignment with a short-circuiting logical OR operator. */
class AssignLogicalOrExpr extends CompoundAssignExpr {
AssignLogicalOrExpr() { this.getOperator().getValue() = "||=" }
}

/** A compound assignment with a short-circuiting null-coalescing operator. */
class AssignNullCoalescingExpr extends CompoundAssignExpr {
AssignNullCoalescingExpr() { this.getOperator().getValue() = "??=" }
}

/** A bitwise AND expression. */
class BitwiseAndExpr extends BinaryExpr {
BitwiseAndExpr() { this.getOperator().getValue() = "&" }
}

/** A bitwise OR expression. */
class BitwiseOrExpr extends BinaryExpr {
BitwiseOrExpr() { this.getOperator().getValue() = "|" }
}

/** A short-circuiting logical AND expression. */
class LogicalAndExpr extends BinaryExpr {
LogicalAndExpr() { this.getOperator().getValue() = "&&" }
Expand All @@ -63,6 +103,20 @@ module Public {
LogicalNotExpr() { this.getOperator().(PrefixOperator).getValue() = "!" }
}

private predicate equalityTest(string op, boolean polarity) {
op = "==" and polarity = true
or
op = "!=" and polarity = false
}

/** An equality test expression. This includes both equals and not-equals comparisons. */
class EqualityTest extends BinaryExpr {
EqualityTest() { equalityTest(this.getOperator().getValue(), _) }

/** Gets a boolean indicating whether this is an equals test (true) or a not-equals test (false). */
boolean getPolarity() { equalityTest(this.getOperator().getValue(), result) }
}

/**
* Declaration of a local or top-level variable.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ private class ExprPositionsPluginSwift extends ExprPositionsPlugin {
exists(Block body |
body = callable.getBody() and
not exists(body.getStmt(1)) and // Check that only one statement exists
e = body.getStmt(0)
e = body.getStmt(0) and
not e instanceof ReturnExpr and
not e instanceof ThrowExpr
)
}
}
215 changes: 215 additions & 0 deletions unified/ql/lib/codeql/unified/internal/controlflow/Guards.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/**
* Provides classes and predicates for reasoning about guards and the control
* flow elements controlled by those guards.
*/
overlay[local?]
module;

private import unified
private import unified as U
private import codeql.controlflow.Guards as SharedGuards
private import codeql.controlflow.SuccessorType
private import codeql.unified.internal.typeinference.TypeInference as T
private import codeql.unified.internal.typeinference.TypeMention as TM
private import codeql.unified.internal.ExprPositions as EP

private module GuardsInput implements SharedGuards::InputSig<Location, ControlFlowNode, BasicBlock> {
class NormalExitNode = ControlFlow::NormalExitNode;

class AstNode = U::AstNode;

class Expr = U::Expr;

predicate nodeIsAfterValue(ControlFlowNode node, Expr e, ConditionalSuccessor s) {
node.isAfterValue(e, s)
}

private newtype TConstantValue =
// TODO: More cases. Chars? Enums?
TStringValue(string value) { any(Expr e).getStringValue() = value }

class ConstantValue extends TConstantValue {
string toString() { this = TStringValue(result) }
}

abstract class ConstantExpr extends Expr {
predicate isNull() { none() }

boolean asBooleanValue() { none() }

int asIntegerValue() { none() }

ConstantValue asConstantValue() { none() }
}

private class NullConstant extends ConstantExpr instanceof U::BuiltinExpr {
NullConstant() {
// TODO: This might be fine as a general purpose condition for
// identifying null literals, but if so it should moved to a more
// general location
this.getValue() = ["null", "nil"]
}

override predicate isNull() { any() }
}

private class BooleanConstant extends ConstantExpr instanceof U::BooleanLiteral {
override boolean asBooleanValue() { result.toString() = super.getValue() }
}

private class IntegerConstant extends ConstantExpr instanceof U::IntLiteral {
override int asIntegerValue() { result = super.getValue().toInt() }
}

private class StringConstant extends ConstantExpr {
StringConstant() { exists(this.getStringValue()) }

override ConstantValue asConstantValue() { result = TStringValue(this.getStringValue()) }
Comment on lines +64 to +67
}

class NonNullExpr extends Expr {
NonNullExpr() {
// TODO: Placeholder implementation. There are more cases of non-null
// expressions that should be handled. Also, (parts of) this is likely
// best handled in language-specific plugins.
exists(CallExpr call, ConstructorDeclaration constructor, ClassLikeDeclaration cls |
// Explicit or inherited Swift initializers may be failable, so this just covers the generated case.
call = this and
constructor = unique(Callable c | c = T::resolveCallTarget(call)) and
constructor.hasModifier("generated") and
cls.getAMember() = constructor and
cls.hasModifier("class") and
not exists(cls.getABaseType())
)
}
}

class Case extends AstNode instanceof U::SwitchCase {
Expr getSwitchExpr() { exists(U::SwitchExpr s | s.getValue() = result and s.getACase() = this) }

AstNode getAPattern() { result = super.getPattern() }
}

predicate nonDeconstructingSubPattern(AstNode pattern, AstNode subPattern) {
pattern.(U::ConditionalPattern).getPattern() = subPattern or
pattern.(U::ExprPattern).getExpr() = subPattern or
pattern.(U::NamedPattern).getSubPattern() = subPattern or
pattern.(U::OrPattern).getAPattern() = subPattern
}

class AndExpr extends BinaryExpr {
AndExpr() {
this instanceof BitwiseAndExpr or
this instanceof LogicalAndExpr or
this instanceof AssignBitwiseAndExpr or
this instanceof AssignLogicalAndExpr
Comment on lines +100 to +105
}
}

class OrExpr extends BinaryExpr {
OrExpr() {
this instanceof BitwiseOrExpr or
this instanceof LogicalOrExpr or
this instanceof AssignBitwiseOrExpr or
this instanceof AssignLogicalOrExpr
}
}

class NotExpr = U::LogicalNotExpr;

class IdExpr extends Expr {
IdExpr() {
this instanceof AssignExpr
or
this instanceof TypeCastExpr and
// TODO: This is Swift-specific and needs to go through a plugin
not this.(TypeCastExpr).getOperator().getValue() = "as?"
}

Expr getEqualChildExpr() {
result = this.(AssignExpr).getValue()
or
result = this.(TypeCastExpr).getExpr()
}
}

predicate equalityTest(Expr eqtest, Expr left, Expr right, boolean polarity) {
exists(U::EqualityTest eq | eq = eqtest |
eq.getLeft() = left and eq.getRight() = right and eq.getPolarity() = polarity
Comment on lines +137 to +138
)
Comment on lines +136 to +139
}

class ConditionalExpr = U::IfExpr;

class Parameter = U::Parameter;

import codeql.unified.internal.dataflow.ParameterPositions

class NonOverridableMethod extends Callable {
NonOverridableMethod() {
// TODO: The concept of non-overridability likely belongs in a language plugin
// TODO: This logic isn't quite right, but just a placeholder for now
// Swift `dynamic` functions can be replaced at runtime.
not this.hasModifier("dynamic") and
(
this instanceof ConstructorDeclaration or
this.(FunctionDeclaration).hasModifier("static") or
this.(FunctionDeclaration).hasModifier("private") or
this.(FunctionDeclaration).hasModifier("final") or
this instanceof LocalFunctionDeclaration or
// Top-level functions are classified as static members, not local functions.
this.(FunctionDeclaration) instanceof TopLevelStmt
)
}

Parameter getParameter(ParameterPosition ppos) {
result.getDeclaringCallable() = this and
ppos = getParameterPosition(result)
}

Expr getAReturnExpr() { EP::isReturnedExpr(this, result) }
}

class NonOverridableMethodCall extends Expr instanceof CallExpr {
NonOverridableMethodCall() {
unique(Callable c | c = T::resolveCallTarget(this)) instanceof NonOverridableMethod
}

NonOverridableMethod getMethod() { result = T::resolveCallTarget(this) }

Expr getArgument(ArgumentPosition apos) {
exists(Argument arg |
super.getAnArgument() = arg and
arg.getValue() = result and
apos = getArgumentPosition(arg)
)
}
}
}

private module GuardsImpl = SharedGuards::Make<Location, Cfg, GuardsInput>;

private module LogicInput_v1 implements GuardsImpl::LogicInputSig {
import Ssa

predicate additionalNullCheck(
GuardsImpl::PreGuard guard, GuardsImpl::GuardValue val, Expr e, boolean isNull
) {
exists(TypeTestExpr test, T::Type testedType |
guard = test and
e = test.getExpr() and
testedType = test.getType().(TM::TypeMention).getType() and
// In Swift, `nil is Any` and `nil is T?` can both be true.
testedType.asClass().hasModifier(["class", "actor", "struct", "enum"]) and
not testedType.asClass().getName() = "Optional" and
val.asBooleanValue() = true and
isNull = false
)
}
}

class GuardValue = GuardsImpl::GuardValue;

private module Guards_v1 = GuardsImpl::Logic<LogicInput_v1>;

class Guard = Guards_v1::Guard;
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,8 @@ module DataFlowInput implements InputSig<Location> {
|
exists(Parameter param |
param = p.asParameter() and
callable = param.getDeclaringCallable()
|
pos.asPositional() = param.getPositionalIndex()
or
pos.asNamed() = param.getExternalName()
callable = param.getDeclaringCallable() and
pos = getParameterPosition(param)
)
or
p.isImplicitReceiverParameter(callable) and
Expand Down Expand Up @@ -114,11 +111,8 @@ module DataFlowInput implements InputSig<Location> {
private predicate isArgumentNodeImpl(Node n, DataFlowCall call, ArgumentPosition pos) {
exists(Argument arg |
n.asExpr() = arg.getValue() and
call.getCallExpr().getAnArgument() = arg
|
pos.asPositional() = arg.getPositionalIndex()
or
pos.asNamed() = arg.getName()
call.getCallExpr().getAnArgument() = arg and
pos = getArgumentPosition(arg)
)
or
n.(BuilderNode).isImplicitArgument(call, pos, false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,15 @@ class ImplicitParameterPosition extends ParameterPosition {
class ImplicitArgumentPosition = ImplicitParameterPosition;

predicate parameterMatch(ParameterPosition ppos, ArgumentPosition apos) { apos = ppos }

ParameterPosition getParameterPosition(Parameter p) {
result.asPositional() = p.getPositionalIndex()
or
result.asNamed() = p.getExternalName()
}

ArgumentPosition getArgumentPosition(Argument arg) {
result.asPositional() = arg.getPositionalIndex()
or
result.asNamed() = arg.getName()
}
Loading
Loading