diff --git a/unified/ql/lib/codeql/unified/internal/ClassLikeElement.qll b/unified/ql/lib/codeql/unified/internal/ClassLikeElement.qll new file mode 100644 index 000000000000..1637f64ab964 --- /dev/null +++ b/unified/ql/lib/codeql/unified/internal/ClassLikeElement.qll @@ -0,0 +1,87 @@ +/** + * Provides the `ClassLikeElement` class, the canonical representative of a class, struct, enum, etc. + */ +overlay[local?] +module; + +private import unified +private import codeql.unified.internal.StaticNameBinding as N +private import codeql.unified.internal.mad.LegacyMaD as MaD + +/** + * Gets the model-only type extended by the extension `ext`, provided that the extended + * type could not be resolved to a declaration. + */ +pragma[nomagic] +private MaD::TypeSelector getExtendedTypeSelector(ClassLikeDeclaration ext) { + not exists(N::getExtendedDeclaration(ext)) and + N::trackTypeSelectorThroughAliases(result) = N::getNodeFromRef(ext.getExtensionTarget()) +} + +cached +private newtype TClassLikeElement = + TClassLikeDeclarationElement(ClassLikeDeclaration decl) { not exists(decl.getExtensionTarget()) } or + TTypeSelectorElement(MaD::TypeSelector selector) { + selector != "" and + not exists(selector.getDeclaration()) and + not selector.isMetaType() + } + +/** + * A class-like entity, such as a class, struct, enum, or protocol. + * + * This is the canonical representative of a class-like entity, unifying its + * primary declaration with any extensions of it. Types that are only known from + * a model (and have no declaration in the database) are represented by their type selector. + */ +class ClassLikeElement extends TClassLikeElement { + /** Gets the primary (non-extension) declaration of this class, if any. */ + ClassLikeDeclaration asClassLikeDeclaration() { this = TClassLikeDeclarationElement(result) } + + /** Gets the type selector of this class, if it is only known from a model. */ + private MaD::TypeSelector asTypeSelector() { this = TTypeSelectorElement(result) } + + /** + * Gets a declaration of this class, that is, either its primary declaration or an extension of it. + */ + cached + ClassLikeDeclaration getADeclaration() { + result = this.asClassLikeDeclaration() + or + N::getExtendedDeclaration(result) = this.asClassLikeDeclaration() + or + getExtendedTypeSelector(result) = this.asTypeSelector() + } + + /** Gets a member of this class, including members declared in extensions. */ + Member getAMember() { result = this.getADeclaration().getAMember() } + + /** Gets the name of this class. */ + string getName() { + result = this.asClassLikeDeclaration().getName() + or + result = this.asTypeSelector().getHead() + } + + /** Gets the qualified name of this class. */ + string getQualifiedName() { + result = this.asClassLikeDeclaration().getQualifiedName() + or + result = this.asTypeSelector() + } + + /** Gets a textual representation of this element. */ + string toString() { + result = this.asClassLikeDeclaration().toString() + or + result = this.asTypeSelector() + } + + /** Gets the location of this element. */ + Location getLocation() { + result = this.asClassLikeDeclaration().getLocation() + or + exists(this.asTypeSelector()) and + result instanceof EmptyLocation + } +} diff --git a/unified/ql/lib/codeql/unified/internal/FacadeAst.qll b/unified/ql/lib/codeql/unified/internal/FacadeAst.qll index 01aa78812b82..3cbee919049a 100644 --- a/unified/ql/lib/codeql/unified/internal/FacadeAst.qll +++ b/unified/ql/lib/codeql/unified/internal/FacadeAst.qll @@ -15,6 +15,29 @@ module Unified { private import Ast::Unified as G import G + private string getTypeReferenceName(Expr expr) { + result = expr.(Identifier).getValue() + or + exists(MemberAccessExpr access | + expr = access and + result = getTypeReferenceName(access.getBase()) + "." + access.getMemberName() + ) + or + exists(GenericTypeExpr generic | + expr = generic and + result = getTypeReferenceName(generic.getBase()) + ) + } + + private string getExpandedTypeReferenceName(Expr expr) { + exists(TypeAliasDeclaration alias | NameBinding::getTypeFromRef(expr) = alias.getNameNode() | + result = getExpandedTypeReferenceName(alias.getType()) + ) + or + not exists(TypeAliasDeclaration alias | NameBinding::getTypeFromRef(expr) = alias.getNameNode()) and + result = getTypeReferenceName(expr) + } + /** The base class for all AST nodes. */ class AstNode extends G::AstNode { /** Gets the file containing this AST node. */ @@ -225,13 +248,56 @@ module Unified { string getQualifiedName(Member m) { result = getQualifiedName(getDeclaringClass(m)) + "." + m.getNameOrFallback() or + exists(ClassLikeDeclaration nested, ClassLikeDeclaration extension | + m = nested and + nested = extension.getAMember() and + not exists(getDeclaringClass(m)) + | + result = + getExpandedTypeReferenceName(extension.getExtensionTarget()) + "." + + nested.getNameOrFallback() + ) + or + not exists(getDeclaringClass(m)) and + not exists(ClassLikeDeclaration nested, ClassLikeDeclaration extension | + nested = m and + nested = extension.getAMember() and + exists(getExpandedTypeReferenceName(extension.getExtensionTarget())) + ) and + result = m.getNameOrFallback() + } + } + + private module QualifiedNameForToString { + string getQualifiedName(Member m) { + result = getQualifiedName(getDeclaringClass(m)) + "." + m.getNameOrFallback() + or + exists(ClassLikeDeclaration nested, ClassLikeDeclaration extension | + m = nested and + nested = extension.getAMember() and + not exists(getDeclaringClass(m)) + | + result = + getTypeReferenceName(extension.getExtensionTarget()) + "." + nested.getNameOrFallback() + ) + or not exists(getDeclaringClass(m)) and + not exists(ClassLikeDeclaration nested, ClassLikeDeclaration extension | + nested = m and + nested = extension.getAMember() and + exists(getTypeReferenceName(extension.getExtensionTarget())) + ) and result = m.getNameOrFallback() } } private ClassLikeDeclaration getParentClass(Member m) { - result.getAMemberIncludingExtensions() = m + exists(ClassLikeDeclaration cls | cls.getAMember() = m | + not exists(cls.getExtensionTarget()) and + result = cls + or + result = NameBinding::getExtendedDeclaration(cls) + ) } private ClassLikeDeclaration getEnclosingClass(Member m) { result.getAMember() = m } @@ -241,7 +307,7 @@ module Unified { * it suitable for use in `toString` predicates. */ private predicate getQualifiedNameForToString = - QualifiedName::getQualifiedName/1; + QualifiedNameForToString::getQualifiedName/1; class ClassLikeDeclaration extends G::ClassLikeDeclaration { /** Gets the name of this declaration. */ @@ -253,6 +319,12 @@ module Unified { result = this.getABaseType().getType().(TypeMention::TypeMention).getClassLikeDeclaration() } + /** + * Gets the class-like element declared by this declaration, or extended by it if + * this is an extension. + */ + U::ClassLikeElement getClassLikeElement() { this = result.getADeclaration() } + /** * Gets the target of this extension class, or this class itself if it is not an extension. */ @@ -261,20 +333,7 @@ module Unified { not exists(this.getExtensionTarget()) and result = this or - exists(NameBinding::NamespaceNode ns | - ns.isStaticMemberNamespace(result) and - ns.getAnExtension().isStaticMemberNamespace(this) - ) - } - - /** - * Gets a member of this class, including members from extensions. - */ - Member getAMemberIncludingExtensions() { - exists(ClassLikeDeclaration cls | - this = cls.resolve() and - result = cls.getAMember() - ) + result = NameBinding::getExtendedDeclaration(this) } override string toString() { diff --git a/unified/ql/lib/codeql/unified/internal/StaticNameBinding.qll b/unified/ql/lib/codeql/unified/internal/StaticNameBinding.qll index e89af066eb09..1cd424d5b523 100644 --- a/unified/ql/lib/codeql/unified/internal/StaticNameBinding.qll +++ b/unified/ql/lib/codeql/unified/internal/StaticNameBinding.qll @@ -503,6 +503,13 @@ class NamespaceNode extends NameBindingNode { NameBindingNode getMember(string name) { result = this.getMember(name, _) } } +private predicate typeAliasValueStep(NameBindingNode node1, NameBindingNode node2) { + exists(TypeAliasDeclaration decl | + node1 = getNodeFromRef(decl.getType()) and + node2.isIdentifier(decl.getNameNode()) + ) +} + private module TrackNamespaceInput implements TrackInputSig { predicate shouldTrack(NameBindingNode node) { node instanceof NamespaceNode } @@ -511,11 +518,7 @@ private module TrackNamespaceInput implements TrackInputSig { } predicate additionalValueStep(NameBindingNode node1, NameBindingNode node2) { - // Namespace-tracking goes through aliases, but declaration-tracking does not - exists(TypeAliasDeclaration decl | - node1 = getNodeFromRef(decl.getType()) and - node2.isIdentifier(decl.getNameNode()) - ) + typeAliasValueStep(node1, node2) } } @@ -554,6 +557,16 @@ private module TrackNameBindingInput implements TrackInputSig { private module TrackNameBinding = Track; +private module TrackTypeSelectorThroughAliasesInput implements TrackInputSig { + predicate shouldTrack(NameBindingNode node) { node.isTypeSelector(_) } + + predicate additionalValueStep(NameBindingNode node1, NameBindingNode node2) { + typeAliasValueStep(node1, node2) + } +} + +private module TrackTypeSelectorThroughAliases = Track; + /** Gets a name-binding node that may refer to the given declaration. */ private NameBindingNode trackNameBinding(NameBinding decl) { exists(NameBindingNode start | @@ -570,6 +583,14 @@ NameBindingNode trackTypeSelector(MaD::TypeSelector type) { ) } +/** Gets a name-binding node that may refer to the given model type through type aliases. */ +NameBindingNode trackTypeSelectorThroughAliases(MaD::TypeSelector type) { + exists(NameBindingNode start | + start.isTypeSelector(type) and + result = TrackTypeSelectorThroughAliases::track(start) + ) +} + /** Holds if `node` should be included in the debug view. */ private signature predicate relevantNodeSig(AstNode node); @@ -709,15 +730,30 @@ private module FolderHeuristic { } } -private ClassLikeDeclaration resolveExtensionTarget(ClassLikeDeclaration cls) { - trackNameBinding(result.getNameNode()) = getNodeFromRef(cls.getExtensionTarget()) +/** + * Gets the non-extension class-like declaration extended by the extension `ext`. + * + * Consider using `ClassLikeElement` instead of this predicate. + */ +cached +ClassLikeDeclaration getExtendedDeclaration(ClassLikeDeclaration ext) { + CachedStage::ref() and + not exists(result.getExtensionTarget()) and + exists(NamespaceNode ns | + ns.isStaticMemberNamespace(result) and + ns.getAnExtension().isStaticMemberNamespace(ext) + ) } -private ClassLikeDeclaration tryResolveExtensionTarget(ClassLikeDeclaration cls) { - result = resolveExtensionTarget(cls) +/** + * Gets the class in whose namespace unqualified member accesses in `scope` should be resolved: + * the extended declaration if `scope` is a resolvable extension, otherwise `scope` itself. + */ +private ClassLikeDeclaration getMemberLookupClass(ClassLikeDeclaration scope) { + result = getExtendedDeclaration(scope) or - not exists(resolveExtensionTarget(cls)) and - result = cls + not exists(getExtendedDeclaration(scope)) and + result = scope } /** @@ -749,7 +785,7 @@ private predicate unqualifiedMemberAccessCand( exists(NamespaceNode namespace, string name | name = access.getName() and accessingClass = - tryResolveExtensionTarget(LocalNameBindingOutput::getAnUncertainScope(access, name)) + getMemberLookupClass(LocalNameBindingOutput::getAnUncertainScope(access, name)) | instanceAccess = true and namespace.isInstanceMemberNamespace(accessingClass) and @@ -940,5 +976,7 @@ private module CachedStage { (exists(any(UnqualifiedMemberAccess u).getImplicitQualifierVariable()) implies any()) or (exists(getStaticBindingTargetFromIdentifier(_)) implies any()) + or + (exists(getExtendedDeclaration(_)) implies any()) } } diff --git a/unified/ql/lib/codeql/unified/internal/mad/LegacyMaD.qll b/unified/ql/lib/codeql/unified/internal/mad/LegacyMaD.qll index 9eff59255e78..ead3c0ab3b66 100644 --- a/unified/ql/lib/codeql/unified/internal/mad/LegacyMaD.qll +++ b/unified/ql/lib/codeql/unified/internal/mad/LegacyMaD.qll @@ -155,9 +155,9 @@ private predicate callableSelector( ) { name = callable.getName() and argLabels = getArgLabelsFromCallable(callable) and - exists(ClassLikeDeclaration cls, TypeSelector baseType | - callable = cls.getAMemberIncludingExtensions() and - isSubclassOfType(cls, baseType) + exists(ClassLikeElement cls, TypeSelector baseType | + callable = cls.getAMember() and + isSubclassOfType(cls.asClassLikeDeclaration(), baseType) | // Static members are members of the meta type if NameBindingPlugin::isStaticMember(callable) @@ -433,8 +433,8 @@ class TypeSelector extends string { /** Holds if this is the meta type of some type. */ predicate isMetaType() { isMetaTypeOf(this, _) } - /** Gets a static reference to this type. */ - AstNode getAStaticRef() { + /** Gets a static reference to this type, not including references via type aliases. */ + AstNode getAnUnexpandedStaticRef() { N::trackTypeSelector(this) = N::getNodeFromRef(result) or // When the class has a declaration in the database, such as a built-in or stub class in a test case, @@ -442,11 +442,21 @@ class TypeSelector extends string { N::getStaticBindingTargetFromRef(result) = this.getDeclaration().getNameNode() } + /** Gets a static reference to this type, possibly via type aliases. */ + AstNode getAStaticRef() { + N::trackTypeSelectorThroughAliases(this) = N::getNodeFromRef(result) + or + N::getExpandedTypeFromRef(result) = this.getDeclaration().getNameNode() + } + /** Gets the declaration of this type, if any. */ ClassLikeDeclaration getDeclaration() { result.getQualifiedName() = this and not exists(result.getExtensionTarget()) } + /** Gets the class-like element corresponding to this type. */ + ClassLikeElement getClassLikeElement() { result.getQualifiedName() = this } + /** Gets the declaration of a proper subtype of this type (not the type itself). */ ClassLikeDeclaration getASubtypeDeclaration() { result.getABaseClass*().getABaseType().getType() = this.getAStaticRef() @@ -455,11 +465,7 @@ class TypeSelector extends string { /** Gets a `Type` corresponding to instances of this type. */ T::Type getAnInstanceType(boolean subtype) { subtype = false and - ( - result.(Types::ModelType).getTypeSelector() = this - or - result.asClass() = this.getDeclaration() - ) + result.(Types::ClassLikeType).getClassLikeElement() = this.getClassLikeElement() or subtype = true and result.asClass() = this.getASubtypeDeclaration() @@ -473,6 +479,12 @@ class TypeSelector extends string { CallExpr getAConstructorCall() { constructorCallSelector(result, this, _, _) } } +/** Gets the type selector of `element`, if it is only known from a model. */ +TypeSelector getTypeSelector(ClassLikeElement element) { + result.getClassLikeElement() = element and + not exists(element.asClassLikeDeclaration()) +} + private predicate isAccessPath(string path) { legacySourceModel(_, _, _, _, _, _, path, _, _) // output or diff --git a/unified/ql/lib/codeql/unified/internal/typeinference/Type.qll b/unified/ql/lib/codeql/unified/internal/typeinference/Type.qll index 8f0174e3110d..a897911c57ff 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/Type.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/Type.qll @@ -8,7 +8,6 @@ private import TypeMention private import TypeInference private import codeql.unified.internal.StaticNameBinding private import codeql.unified.internal.ParameterEx -private import codeql.unified.internal.mad.LegacyMaD as MaD /** * Holds if `a` is an associated type of `c`, in which case we model it @@ -44,7 +43,8 @@ predicate associatedTypeParameterInherited( private predicate isNestedType(Member m, Identifier nested, ClassLikeDeclaration parent) { exists(parent.getNameNode()) and nested = m.getNameNode() and - m = parent.getAMemberIncludingExtensions() and + parent = parent.getClassLikeElement().asClassLikeDeclaration() and + m = parent.getClassLikeElement().getAMember() and ( exists(m.(ClassLikeDeclaration).getNameNode()) or @@ -54,10 +54,7 @@ private predicate isNestedType(Member m, Identifier nested, ClassLikeDeclaration cached newtype TType = - TClassLikeDeclarationType(ClassLikeDeclaration c) { - CachedStage::ref() and - exists(c.getNameNode()) - } or + TClassLikeType(ClassLikeElement e) { CachedStage::ref() } or TAliasType(TypeAliasDeclaration alias) or TClosureParameterPseudoType(ParameterEx p) { p.isFunctionExprParameter(_, _) and @@ -70,10 +67,6 @@ newtype TType = associatedTypeParameter(c, a, inherited) } or TParentTypeParameterType(Member m) { isNestedType(m, _, _) } or - TModelType(MaD::TypeSelector selector) { - not exists(selector.getDeclaration()) and - not selector.isMetaType() - } or TUnknownType() or TUnknownTypeTypeParameter(int i) { i in [0 .. 20] } @@ -106,7 +99,7 @@ abstract private class TypeImpl extends TType { } /** Gets the parent type of this nested type, if any. */ - ClassLikeDeclarationType getParentType() { + ClassLikeType getParentType() { result.getClassLikeDeclaration() = this.getATypeParameter().(ParentTypeParameterType).getParent() } @@ -121,36 +114,41 @@ abstract private class TypeImpl extends TType { abstract Location getLocation(); /** Gets the class whose instances are described by this type. */ - ClassLikeDeclaration asClass() { this = TClassLikeDeclarationType(result) } + ClassLikeDeclaration asClass() { result = this.(ClassLikeType).getClassLikeDeclaration() } } /** - * A type representing a class-like declaration. + * A type representing a class-like element, that is, either a class-like declaration + * or a type that is only known from a models-as-data row. */ -class ClassLikeDeclarationType extends TypeImpl, TClassLikeDeclarationType { - ClassLikeDeclaration c; +class ClassLikeType extends TypeImpl, TClassLikeType { + private ClassLikeElement e; - ClassLikeDeclarationType() { this = TClassLikeDeclarationType(c) } + ClassLikeType() { this = TClassLikeType(e) } - ClassLikeDeclaration getClassLikeDeclaration() { result = c } + /** Gets the class-like element represented by this type. */ + ClassLikeElement getClassLikeElement() { result = e } - string getName() { result = c.getName() } + /** Gets the primary declaration of this type, if any. */ + ClassLikeDeclaration getClassLikeDeclaration() { result = e.asClassLikeDeclaration() } - override Identifier getNameNode() { result = c.getNameNode() } + string getName() { result = e.getName() } + + override Identifier getNameNode() { result = this.getClassLikeDeclaration().getNameNode() } override TypeParameter getPositionalTypeParameter(int i) { - result = TTypeParameterType(c.getTypeParameter(i)) + result = TTypeParameterType(this.getClassLikeDeclaration().getTypeParameter(i)) } override TypeParameter getATypeParameter() { result = super.getATypeParameter() or - result = TAssociatedTypeParameterType(c, _, _) + result = TAssociatedTypeParameterType(this.getClassLikeDeclaration(), _, _) } - override string toString() { result = c.getQualifiedName() } + override string toString() { result = e.getQualifiedName() } - override Location getLocation() { result = c.getLocation() } + override Location getLocation() { result = e.getLocation() } } /** @@ -177,26 +175,6 @@ class AliasType extends TypeImpl, TAliasType { override Location getLocation() { result = alias.getLocation() } } -/** - * A type described by a type selector in a models-as-data row. - */ -class ModelType extends TypeImpl, TModelType { - private MaD::TypeSelector selector; - - ModelType() { this = TModelType(selector) } - - /** Gets the type selector describing this type. */ - MaD::TypeSelector getTypeSelector() { result = selector } - - override TypeParameter getPositionalTypeParameter(int i) { none() } - - override Identifier getNameNode() { none() } - - override string toString() { result = selector } - - override Location getLocation() { result instanceof EmptyLocation } -} - /** * A pseudo type that does not correspond to any concrete type in the source code. */ diff --git a/unified/ql/lib/codeql/unified/internal/typeinference/TypeAbstraction.qll b/unified/ql/lib/codeql/unified/internal/typeinference/TypeAbstraction.qll index 4695189f9d1c..26c13d49faed 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/TypeAbstraction.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/TypeAbstraction.qll @@ -10,7 +10,7 @@ abstract class TypeAbstraction extends AstNode { } /** - * A class-like declaration. Unlike `ClassLikeDeclarationType`, this includes + * A class-like declaration. Unlike `ClassLikeType`, this includes * declarations that do not define a new type, such as `extension`s in Swift. */ private class ClassLikeDeclarationTypeAbstraction extends TypeAbstraction instanceof Unified::ClassLikeDeclaration diff --git a/unified/ql/lib/codeql/unified/internal/typeinference/TypeInference.qll b/unified/ql/lib/codeql/unified/internal/typeinference/TypeInference.qll index be0c801ae311..37ab52b41408 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/TypeInference.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/TypeInference.qll @@ -21,6 +21,7 @@ private import codeql.typeinference.internal.TypeInference private import codeql.unified.internal.ParameterEx private import codeql.unified.internal.ExprPositions private import codeql.unified.internal.NameBinding +private import codeql.unified.internal.mad.LegacyMaD as MaD private import utils.test.InlineExpectationsTest private import Type private import Type as T @@ -591,12 +592,7 @@ module Input3 implements InputSig3 { Callable getTargetViaStaticNameBinding() { // object creation (including enum constructors): `String(42)`, `Optional.Some(42)` exists(ClassLikeDeclaration cls | - cls = - this.getCallee() - .(TypeMention) - .getType() - .(ClassLikeDeclarationType) - .getClassLikeDeclaration() and + cls = this.getCallee().(TypeMention).getType().(ClassLikeType).getClassLikeDeclaration() and result.isInstanceMemberOf(cls, _) and result.asCallable() instanceof ConstructorDeclaration ) @@ -845,7 +841,7 @@ module Input3 implements InputSig3 { private predicate needsContextualTyping(Invocation i, TypePath path) { exists( Callable constructor, Argument receiver, TypePath enumPrefixPath, - ClassLikeDeclarationType receiverType, TypePath path0 + ClassLikeType receiverType, TypePath path0 | constructionReceiver(i, constructor, receiver, enumPrefixPath) and receiverType = inferType(receiver) and @@ -856,8 +852,7 @@ module Input3 implements InputSig3 { or // inherited constructor exists( - ClassLikeDeclarationType declType, TypeAbstraction abs, TypeMention constraint, - TypeParameter tp + ClassLikeType declType, TypeAbstraction abs, TypeMention constraint, TypeParameter tp | declType = constructor.getDeclaringType().getType() and BaseTypes::rootTypesSatisfaction(receiverType, declType, abs, _, constraint) and @@ -901,7 +896,7 @@ module Input3 implements InputSig3 { result instanceof UnknownType or path.isEmpty() and - n = result.(ModelType).getTypeSelector().getAConstructorCall() + n = MaD::getTypeSelector(result.(ClassLikeType).getClassLikeElement()).getAConstructorCall() } predicate allowContextualInference(TypeMention tm, TypePath path) { @@ -938,7 +933,7 @@ module Input3 implements InputSig3 { path.isEmpty() or exists(ClassLikeDeclaration c | - c = n.(SuperExpr).getEnclosingClass().resolve() and + c = n.(SuperExpr).getEnclosingClass().getClassLikeElement().asClassLikeDeclaration() and result = c.getBaseType(0).getType().(TypeMention).getTypeAt(path) ) or diff --git a/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePluginSwift.qll b/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePluginSwift.qll index ecb52be938fa..02174affe342 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePluginSwift.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePluginSwift.qll @@ -9,15 +9,15 @@ private import TypeInference private import TypeInferencePlugin as Plugin private import codeql.unified.internal.Builtins -private class StructType extends ClassLikeDeclarationType { - StructType() { c.getAModifier().getValue() = "struct" } +private class StructType extends ClassLikeType { + StructType() { this.getClassLikeDeclaration().getAModifier().getValue() = "struct" } } -private class EnumType extends ClassLikeDeclarationType { - EnumType() { c.getAModifier().getValue() = "enum" } +private class EnumType extends ClassLikeType { + EnumType() { this.getClassLikeDeclaration().getAModifier().getValue() = "enum" } } -private class BuiltinType extends ClassLikeDeclarationType { +private class BuiltinType extends ClassLikeType { BuiltinType() { this.getClassLikeDeclaration() instanceof BuiltinClassLikeDeclaration } } diff --git a/unified/ql/lib/codeql/unified/internal/typeinference/TypeMention.qll b/unified/ql/lib/codeql/unified/internal/typeinference/TypeMention.qll index 702a7351f276..4fe5e03042d4 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/TypeMention.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/TypeMention.qll @@ -4,6 +4,7 @@ private import TypeInference private import TypeInferencePlugin as Plugin private import codeql.unified.internal.StaticNameBinding private import codeql.unified.internal.ExprPositions +private import codeql.unified.internal.mad.LegacyMaD as MaD final class TypeMention = TypeMentionImpl; @@ -56,7 +57,7 @@ abstract private class TypeMentionImpl extends AstNode { ) { this.aliasRefHasEnclosingType(prefix, ptp, path, t) or - exists(ClassLikeDeclarationType sub, TypeMention base | + exists(ClassLikeType sub, TypeMention base | this.aliasRefHasEnclosingTypeInclBases(prefix, ptp, TypePath::nil(), sub) and base = sub.getClassLikeDeclaration().getABaseType().getType() | @@ -121,7 +122,7 @@ abstract private class TypeMentionImpl extends AstNode { * Gets the class-like declaration mentioned by this type mention, if any. */ ClassLikeDeclaration getClassLikeDeclaration() { - result = this.getExpandedType().(ClassLikeDeclarationType).getClassLikeDeclaration() + result = this.getExpandedType().(ClassLikeType).getClassLikeDeclaration() } /** @@ -254,7 +255,7 @@ class ExprTypeMention extends TypeMentionImpl, Expr { not this = any(GenericTypeExpr g).getBase() and not this instanceof FunctionExpr and not this instanceof TupleExpr and - exists(ClassLikeDeclarationType t | + exists(ClassLikeType t | t = this.getUnexpandedType() and result = t.getATypeParameter() and path = TypePath::singleton(result) and @@ -281,7 +282,8 @@ class ExprTypeMention extends TypeMentionImpl, Expr { or result.(Plugin::TupleType).getArity() = this.(TupleExpr).getNumberOfElements() or - result.(ModelType).getTypeSelector().getAStaticRef() = this + MaD::getTypeSelector(result.(ClassLikeType).getClassLikeElement()).getAnUnexpandedStaticRef() = + this } override Type getUnexpandedType() { diff --git a/unified/ql/lib/unified.qll b/unified/ql/lib/unified.qll index ff3cc986a73e..48bd8e69a689 100644 --- a/unified/ql/lib/unified.qll +++ b/unified/ql/lib/unified.qll @@ -6,6 +6,7 @@ import codeql.Locations import codeql.files.FileSystem import codeql.unified.internal.Ast::UnifiedFinal import codeql.unified.internal.AstExtra::Public +import codeql.unified.internal.ClassLikeElement import codeql.unified.internal.ControlFlowGraph::Public import codeql.unified.internal.NameBinding::Public import codeql.unified.internal.dataflow.DataFlowPublic diff --git a/unified/ql/lib/utils/test/TestUtils.qll b/unified/ql/lib/utils/test/TestUtils.qll index 2b50c033878e..fc4699756a51 100644 --- a/unified/ql/lib/utils/test/TestUtils.qll +++ b/unified/ql/lib/utils/test/TestUtils.qll @@ -14,12 +14,12 @@ private string defaultName(NameBinding decl) { or not exists(getTupleFieldName(decl)) and name = decl.getName() | - exists(ClassLikeDeclaration cls | - decl.getDeclaration() = cls.getAMemberIncludingExtensions() and + exists(ClassLikeElement cls | + decl.getDeclaration() = cls.getAMember() and result = cls.getQualifiedName() + "." + name ) or - not decl.getDeclaration() = any(ClassLikeDeclaration cls).getAMemberIncludingExtensions() and + not decl.getDeclaration() = any(ClassLikeElement cls).getAMember() and result = name ) } diff --git a/unified/ql/src/queries/security/CWE-312/CleartextLogging.ql b/unified/ql/src/queries/security/CWE-312/CleartextLogging.ql index 73c2660c5d61..9a31ec02fd52 100644 --- a/unified/ql/src/queries/security/CWE-312/CleartextLogging.ql +++ b/unified/ql/src/queries/security/CWE-312/CleartextLogging.ql @@ -37,8 +37,8 @@ predicate heuristicSink(DataFlow::Node node) { ( logLikeHeuristic(f.getName()) or - exists(ClassLikeDeclaration type | - f = type.getAMemberIncludingExtensions() and + exists(ClassLikeElement type | + f = type.getAMember() and logLikeHeuristic(type.getName()) ) ) and diff --git a/unified/ql/test/library-tests/class-like-element/test.expected b/unified/ql/test/library-tests/class-like-element/test.expected new file mode 100644 index 000000000000..636f7dc01f3f --- /dev/null +++ b/unified/ql/test/library-tests/class-like-element/test.expected @@ -0,0 +1,2 @@ +| ModelOnly | extensionMember | +| ModelOnly.Nested | | diff --git a/unified/ql/test/library-tests/class-like-element/test.ext.json b/unified/ql/test/library-tests/class-like-element/test.ext.json new file mode 100644 index 000000000000..2400ac32b900 --- /dev/null +++ b/unified/ql/test/library-tests/class-like-element/test.ext.json @@ -0,0 +1,15 @@ +{ + "extensions": [ + { + "addsTo": { + "pack": "codeql/unified-all", + "extensible": "legacySourceModel" + }, + "data": [ + ["", "ModelOnly", false, "modeled(_:)", "", "", "Parameter[0]", "test", "manual"], + ["", "ModelOnly.Nested", false, "modeled(_:)", "", "", "Parameter[0]", "nested-test", "manual"], + ["", "", false, "topLevel(_:)", "", "", "Parameter[0]", "test", "manual"] + ] + } + ] +} diff --git a/unified/ql/test/library-tests/class-like-element/test.ql b/unified/ql/test/library-tests/class-like-element/test.ql new file mode 100644 index 000000000000..1e0387092b24 --- /dev/null +++ b/unified/ql/test/library-tests/class-like-element/test.ql @@ -0,0 +1,31 @@ +import unified + +predicate relevantElement(string name, string memberName) { + exists(ClassLikeElement element, Member member | + element.getQualifiedName() = "ModelOnly" and + member = element.getAMember() and + member.getNameNode().getValue() = "extensionMember" + | + name = element.getQualifiedName() and + memberName = member.getNameNode().getValue() + ) + or + exists(ClassLikeElement element | + element.getQualifiedName() = "" and + name = "(empty root)" and + memberName = "" + ) + or + exists(ClassLikeElement element, ClassLikeDeclaration nested | + element.getQualifiedName() = "ModelOnly.Nested" and + nested.getName() = "Nested" and + element.asClassLikeDeclaration() = nested and + count(ClassLikeElement other | other.getQualifiedName() = "ModelOnly.Nested") = 1 and + name = element.getQualifiedName() and + memberName = "" + ) +} + +from string name, string memberName +where relevantElement(name, memberName) +select name, memberName diff --git a/unified/ql/test/library-tests/class-like-element/test.swift b/unified/ql/test/library-tests/class-like-element/test.swift new file mode 100644 index 000000000000..0444d632f59d --- /dev/null +++ b/unified/ql/test/library-tests/class-like-element/test.swift @@ -0,0 +1,15 @@ +typealias ExtensionAlias = ModelOnly + +extension ExtensionAlias { + func extensionMember() {} +} + +extension ExtensionAlias { + struct Nested {} +} + +func topLevel(_ value: String) {} + +func useTopLevel(_ value: String) { + topLevel(value) +} diff --git a/unified/ql/test/library-tests/mad/test.expected b/unified/ql/test/library-tests/mad/test.expected index 7fce70fc8931..dd7f20f2f04e 100644 --- a/unified/ql/test/library-tests/mad/test.expected +++ b/unified/ql/test/library-tests/mad/test.expected @@ -47,6 +47,11 @@ isSink | test.swift:287:27:287:32 | string | static-sink | | test.swift:290:29:290:34 | string | instance-sink | | test.swift:291:20:291:25 | string | static-sink | +| test.swift:347:5:347:21 | ... .arguments | command-injection | +| test.swift:348:34:348:39 | string | optional-init-sink | +| test.swift:349:30:349:35 | string | model-only-init-sink | +| test.swift:350:35:350:40 | string | model-only-init-sink | +| test.swift:351:40:351:45 | string | model-only-init-sink | isSource | test.swift:4:5:4:27 | String(...) | remote | | test.swift:5:5:5:44 | String(...) | remote | diff --git a/unified/ql/test/library-tests/mad/test.ext.json b/unified/ql/test/library-tests/mad/test.ext.json index f0fbc464bd7e..0c00c3ed817c 100644 --- a/unified/ql/test/library-tests/mad/test.ext.json +++ b/unified/ql/test/library-tests/mad/test.ext.json @@ -31,7 +31,8 @@ ["", "OptionalTest", true, "mixed(_:x?:)", "", "", "Argument[0]", "optional-mixed-sink", "manual"], ["", "OptionalInit", true, "init(value:flag?:)", "", "", "Argument[value:]", "optional-init-sink", "manual"], ["", "StaticTest", true, "instanceSink(_:)", "", "", "Argument[0]", "instance-sink", "manual"], - ["", "StaticTest.Type", true, "staticSink(_:)", "", "", "Argument[0]", "static-sink", "manual"] + ["", "StaticTest.Type", true, "staticSink(_:)", "", "", "Argument[0]", "static-sink", "manual"], + ["", "ModelOnlyInit", true, "init(value:)", "", "", "Argument[value:]", "model-only-init-sink", "manual"] ] } ] diff --git a/unified/ql/test/library-tests/mad/test.swift b/unified/ql/test/library-tests/mad/test.swift index f7ca0bb5fad4..b9c1de7e4694 100644 --- a/unified/ql/test/library-tests/mad/test.swift +++ b/unified/ql/test/library-tests/mad/test.swift @@ -336,3 +336,17 @@ class InstanceEncryptMethods: RNEncryptor { func encryptData(_ data: String, with: String, password: String, iv: String, encryptionSalt: String, hmacSalt: String) {} func encryptData(_ data: String, withSettings: String, password: String, IV: String, encryptionSalt: String, HMACSalt: String) {} } + +typealias OptionalInitAlias = OptionalInit +typealias ModelOnlyInitAlias = ModelOnlyInit +typealias ProcessAlias = Process + +class ProcessSubclassViaAlias: ProcessAlias {} + +func testTypeAliases(string: String, process: ProcessSubclassViaAlias) { + process.arguments = [string] // $ isSink=command-injection + _ = OptionalInitAlias(value: string) // $ isSink=optional-init-sink + _ = ModelOnlyInit(value: string) // $ isSink=model-only-init-sink + _ = ModelOnlyInitAlias(value: string) // $ isSink=model-only-init-sink + _ = ModelOnlyInitAlias.init(value: string) // $ isSink=model-only-init-sink +}