diff --git a/unified/extractor/src/languages/swift/swift.rs b/unified/extractor/src/languages/swift/swift.rs index d5fd7fbc1e31..fc9d15b1ea37 100644 --- a/unified/extractor/src/languages/swift/swift.rs +++ b/unified/extractor/src/languages/swift/swift.rs @@ -1543,6 +1543,13 @@ fn translation_rules() -> Vec> { => (member_access_expr base: {base} member_name_node: (identifier #{name})) ), + // A metatype (`T.Type`, `P.Protocol`) is represented like a qualified type, + // as a member access on the base type. + rule!( + (metatypeType baseType: @base metatypeSpecifier: @@specifier) + => + (member_access_expr base: {base} member_name_node: (identifier #{specifier})) + ), // Sugared types desugar to `generic_type_expr`: `T?` -> Optional, // `[T]` -> Array, `[K: V]` -> Dictionary. rule!( @@ -1845,7 +1852,6 @@ fn translation_rules() -> Vec> { rule!((inlineArrayType) => (unsupported_node "")), rule!((keyPathExpr) => (unsupported_node "")), rule!((macroDecl) => (unsupported_node "")), - rule!((metatypeType) => (unsupported_node "")), rule!((namedOpaqueReturnType) => (unsupported_node "")), rule!((operatorDecl) => (unsupported_node "")), rule!((packElementExpr) => (unsupported_node "")), diff --git a/unified/extractor/tests/corpus/swift/types/metatype.output b/unified/extractor/tests/corpus/swift/types/metatype.output new file mode 100644 index 000000000000..c8cced8982f1 --- /dev/null +++ b/unified/extractor/tests/corpus/swift/types/metatype.output @@ -0,0 +1,130 @@ +func f(a: Foo.Type, b: Outer.Inner.Type, c: [Int].Type, d: P.Protocol) {} + +--- + +sourceFile + endOfFileToken: endOfFile + statements: + codeBlockItem + item: + functionDecl + attributes: + body: + codeBlock + leftBrace: { + rightBrace: } + statements: + modifiers: + name: identifier "f" + signature: + functionSignature + parameterClause: + functionParameterClause + leftParen: ( + rightParen: ) + parameters: + functionParameter + colon: : + attributes: + modifiers: + trailingComma: , + type: + metatypeType + baseType: + identifierType + name: identifier "Foo" + period: . + metatypeSpecifier: Type + firstName: identifier "a" + functionParameter + colon: : + attributes: + modifiers: + trailingComma: , + type: + metatypeType + baseType: + memberType + name: identifier "Inner" + baseType: + identifierType + name: identifier "Outer" + period: . + period: . + metatypeSpecifier: Type + firstName: identifier "b" + functionParameter + colon: : + attributes: + modifiers: + trailingComma: , + type: + metatypeType + baseType: + arrayType + leftSquare: [ + rightSquare: ] + element: + identifierType + name: identifier "Int" + period: . + metatypeSpecifier: Type + firstName: identifier "c" + functionParameter + colon: : + attributes: + modifiers: + type: + metatypeType + baseType: + identifierType + name: identifier "P" + period: . + metatypeSpecifier: Protocol + firstName: identifier "d" + funcKeyword: func + +--- + +top_level source="⟨body⟩" + body: + block source="⟨stmt⟩" + stmt: + function_declaration source="func ⟨name_node⟩(⟨parameter⟩, ⟨parameter⟩, ⟨parameter⟩, ⟨parameter⟩) ⟨body⟩" + name_node: identifier "f" source="f" + parameter: + parameter source="⟨external_name_node⟩⟨pattern⟩: ⟨type⟩" + external_name_node: identifier "a" source="a" + type: + member_access_expr source="⟨base⟩.⟨member_name_node⟩" + base: identifier "Foo" source="Foo" + member_name_node: identifier "Type" source="Type" + pattern: identifier "a" source="a" + parameter source="⟨external_name_node⟩⟨pattern⟩: ⟨type⟩" + external_name_node: identifier "b" source="b" + type: + member_access_expr source="⟨base⟩.⟨member_name_node⟩" + base: + member_access_expr source="⟨base⟩.⟨member_name_node⟩" + base: identifier "Outer" source="Outer" + member_name_node: identifier "Inner" source="Inner" + member_name_node: identifier "Type" source="Type" + pattern: identifier "b" source="b" + parameter source="⟨external_name_node⟩⟨pattern⟩: ⟨type⟩" + external_name_node: identifier "c" source="c" + type: + member_access_expr source="⟨base⟩.⟨member_name_node⟩" + base: + generic_type_expr source="[⟨type_argument⟩]" + base: identifier "Array" source="" + type_argument: identifier "Int" source="Int" + member_name_node: identifier "Type" source="Type" + pattern: identifier "c" source="c" + parameter source="⟨external_name_node⟩⟨pattern⟩: ⟨type⟩" + external_name_node: identifier "d" source="d" + type: + member_access_expr source="⟨base⟩.⟨member_name_node⟩" + base: identifier "P" source="P" + member_name_node: identifier "Protocol" source="Protocol" + pattern: identifier "d" source="d" + body: block "{}" source="{}" diff --git a/unified/extractor/tests/corpus/swift/types/metatype.swift b/unified/extractor/tests/corpus/swift/types/metatype.swift new file mode 100644 index 000000000000..9d85c5c98119 --- /dev/null +++ b/unified/extractor/tests/corpus/swift/types/metatype.swift @@ -0,0 +1 @@ +func f(a: Foo.Type, b: Outer.Inner.Type, c: [Int].Type, d: P.Protocol) {} diff --git a/unified/ql/lib/codeql/unified/internal/AnalysisQuality.qll b/unified/ql/lib/codeql/unified/internal/AnalysisQuality.qll index 9c4b9ee89f17..f7bbcbaf3b49 100644 --- a/unified/ql/lib/codeql/unified/internal/AnalysisQuality.qll +++ b/unified/ql/lib/codeql/unified/internal/AnalysisQuality.qll @@ -53,6 +53,8 @@ module StaticNameResolutionStats implements EntityStatsSig { NameBindingNode getTarget() { result.asIdentifier() = getStaticBindingTargetFromIdentifier(this) or + result = this.(UnqualifiedMemberAccess).getTargetNode() + or result.isModuleScopeNode(_) and result.(NamespaceNode).ref().isIdentifier(this) or 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..ef8e531e8cbe --- /dev/null +++ b/unified/ql/lib/codeql/unified/internal/ClassLikeElement.qll @@ -0,0 +1,86 @@ +/** + * 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::trackTypeSelector(result) = N::getNodeFromRef(ext.getExtensionTarget()) +} + +cached +private newtype TClassLikeElement = + TClassLikeDeclarationElement(ClassLikeDeclaration decl) { not exists(decl.getExtensionTarget()) } or + TTypeSelectorElement(MaD::TypeSelector selector) { + 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. */ + 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 7fdaec2508a8..31f13d126e56 100644 --- a/unified/ql/lib/codeql/unified/internal/FacadeAst.qll +++ b/unified/ql/lib/codeql/unified/internal/FacadeAst.qll @@ -229,7 +229,12 @@ module Unified { } 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 } @@ -251,6 +256,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. */ @@ -259,20 +270,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..ba25d30f0cbd 100644 --- a/unified/ql/lib/codeql/unified/internal/StaticNameBinding.qll +++ b/unified/ql/lib/codeql/unified/internal/StaticNameBinding.qll @@ -23,7 +23,8 @@ private newtype TNameBindingNode = TModuleScope(ModuleScopeRepr repr) or TFolderScope(Folder folder) or TModuleRoot() or - TTypeSelector(MaD::TypeSelector type) + TTypeSelector(MaD::TypeSelector type) or + TMemberSelector(MaD::MemberSelector member) /** * A node in a graph, in which name-binding rules are represented as edges between nodes. @@ -63,8 +64,17 @@ class NameBindingNode extends TNameBindingNode { /** Holds if this represents the root namespace in which all named modules are members. */ predicate isModuleRoot() { this = TModuleRoot() } + /** + * Holds if this represents the members of the given type from a model. + * + * Static members are members of the meta type, such as `Foo.Type`, whose node also + * represents references to the type `Foo` itself. + */ predicate isTypeSelector(MaD::TypeSelector type) { this = TTypeSelector(type) } + /** Holds if this represents the member identified by `member` from a model. */ + predicate isMemberSelector(MaD::MemberSelector member) { this = TMemberSelector(member) } + /** * Gets an AST node wrapped by this name-binding node, if such a node exists. * @@ -112,6 +122,10 @@ class NameBindingNode extends TNameBindingNode { exists(MaD::TypeSelector type | this.isTypeSelector(type) and result = "TypeSelector(" + type + ")" ) + or + exists(MaD::MemberSelector member | + this.isMemberSelector(member) and result = "MemberSelector(" + member + ")" + ) } Location getLocation() { @@ -233,12 +247,32 @@ predicate storeStep(NameBindingNode node1, string name, NameBindingNode node2) { or FolderHeuristic::storeStep(node1, name, node2) or - exists(MaD::TypeSelector type | - node1.isTypeSelector(type.append(name)) and - node2.isTypeSelector(type) + // A nested type is a static member of its enclosing type, and a reference to it is a value + // of its meta type + exists(MaD::TypeSelector type, MaD::TypeSelector nested | + nested = type.append(name) and + not nested.isMetaType() and + node1.isTypeSelector(nested.getMetaType()) and + node2.isTypeSelector(getMetaTypeOrRoot(type)) + ) + or + exists(MaD::MemberSelector member | + node1.isMemberSelector(member) and + name = member.getName() and + node2.isTypeSelector(member.getTypeString()) ) } +/** + * Gets the meta type of `type`, whose members are accessible through a reference to `type`, + * or the root type selector itself if `type` is the root. + */ +private MaD::TypeSelector getMetaTypeOrRoot(MaD::TypeSelector type) { + result = type.getMetaType() + or + type = "" and result = "" +} + predicate valueStep(NameBindingNode node1, NameBindingNode node2) { exists(PotentialLocalNameAccess access | access.isBindingSite() and @@ -394,6 +428,12 @@ private predicate isInheritableMemberNode(NameBindingNode node) { node.isIdentifier(decl) and isInheritableMember(decl.getDeclaration()) ) + or + // Members from a model are inherited if the model applies to subtypes + exists(MaD::MemberSelector member | + node.isMemberSelector(member) and + member.getSubtypesFlag() = true + ) } /** A name-binding node that can have members. */ @@ -408,6 +448,8 @@ class NamespaceNode extends NameBindingNode { this.isInstanceMemberNamespace(_) or this.isStaticMemberNamespace(_) + or + this.isTypeSelector(_) } /** Gets a name-binding node that may refer to this namespace. */ @@ -422,15 +464,20 @@ class NamespaceNode extends NameBindingNode { /** Gets an own (non-inherited) member of this namespace of the given name. */ NameBindingNode getOwnMember(string name) { result = this.getOwnMember(name, _) } - /** If this is the static namespace for a class, gets the corresponding instance namespace. */ + /** If this is the static namespace for a class or model type, gets the corresponding instance namespace. */ NamespaceNode toInstanceNamespace() { exists(ClassLikeDeclaration cls | this.isStaticMemberNamespace(cls) and result.isInstanceMemberNamespace(cls) ) + or + exists(MaD::TypeSelector type | + this.isTypeSelector(type.getMetaType()) and + result.isTypeSelector(type) + ) } - /** If this is the instance namespace for a class, gets the corresponding static namespace. */ + /** If this is the instance namespace for a class or model type, gets the corresponding static namespace. */ NamespaceNode toStaticNamespace() { result.toInstanceNamespace() = this } private NamespaceNode getAnExtension1() { extensionStep(result, this.ref()) } @@ -549,6 +596,8 @@ private module TrackNameBindingInput implements TrackInputSig { ) or node.isTypeSelector(_) + or + node.isMemberSelector(_) } } @@ -562,10 +611,22 @@ private NameBindingNode trackNameBinding(NameBinding decl) { ) } -/** Gets a name-binding node that may refer to the given type from a model. */ +/** + * Gets a name-binding node that may refer to the given type from a model. + * + * A reference to a type is a value of its meta type, so this tracks the node of the meta type. + */ NameBindingNode trackTypeSelector(MaD::TypeSelector type) { exists(NameBindingNode start | - start.isTypeSelector(type) and + start.isTypeSelector(getMetaTypeOrRoot(type)) and + result = TrackNameBinding::track(start) + ) +} + +/** Gets a name-binding node that may refer to the given member from a model. */ +NameBindingNode trackMemberSelector(MaD::MemberSelector member) { + exists(NameBindingNode start | + start.isMemberSelector(member) and result = TrackNameBinding::track(start) ) } @@ -709,15 +770,71 @@ 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 +} + +/** + * A name-binding node that can be the target of an unqualified member access, that is, + * a member declaration, or a type or member from a model. + */ +final class MemberTargetNode extends NameBindingNode { + MemberTargetNode() { + this.asIdentifier() instanceof NameBinding + or + this.isTypeSelector(_) + or + this.isMemberSelector(_) + } +} + +/** + * Gets a namespace in which unqualified member accesses in `scope` should be looked up. + * + * `instanceAccess` indicates whether this is the namespace of instance members or static members. + */ +private NamespaceNode getMemberLookupNamespace(ClassLikeDeclaration scope, boolean instanceAccess) { + exists(ClassLikeDeclaration cls | cls = getMemberLookupClass(scope) | + instanceAccess = true and + result.isInstanceMemberNamespace(cls) + or + instanceAccess = false and + result.isStaticMemberNamespace(cls) + ) + or + // An extension of a type that is only known from a model + exists(MaD::TypeSelector type | + not exists(getExtendedDeclaration(scope)) and + trackTypeSelector(type) = getNodeFromRef(scope.getExtensionTarget()) + | + instanceAccess = true and + result.isTypeSelector(type) + or + instanceAccess = false and + result.isTypeSelector(type.getMetaType()) + ) } /** @@ -727,37 +844,31 @@ private ClassLikeDeclaration tryResolveExtensionTarget(ClassLikeDeclaration cls) * or as a static member. */ private predicate unqualifiedMemberAccessCand( - PotentialLocalNameAccess access, boolean instanceAccess, NameBinding target, + PotentialLocalNameAccess access, boolean instanceAccess, MemberTargetNode target, ClassLikeDeclaration accessingClass ) { not access instanceof NameBinding and ( // Resolved by local scoping - exists(LocalName local | - target.getLocalName() = local and + exists(LocalName local, NameBinding binding | + target.isIdentifier(binding) and + binding.getLocalName() = local and access.getLocalName() = local and - target.getDeclaration() = accessingClass.getAMember() + binding.getDeclaration() = accessingClass.getAMember() | instanceAccess = true and - isInstanceMember(target.getDeclaration()) + isInstanceMember(binding.getDeclaration()) or instanceAccess = false and - isStaticMember(target.getDeclaration()) + isStaticMember(binding.getDeclaration()) ) or // Resolved in an uncertain scope - exists(NamespaceNode namespace, string name | + exists(string name, ClassLikeDeclaration scope | name = access.getName() and - accessingClass = - tryResolveExtensionTarget(LocalNameBindingOutput::getAnUncertainScope(access, name)) - | - instanceAccess = true and - namespace.isInstanceMemberNamespace(accessingClass) and - namespace.getMember(name).isIdentifier(target) - or - instanceAccess = false and - namespace.isStaticMemberNamespace(accessingClass) and - namespace.getMember(name).isIdentifier(target) + scope = LocalNameBindingOutput::getAnUncertainScope(access, name) and + accessingClass = getMemberLookupClass(scope) and + getMemberLookupNamespace(scope, instanceAccess).getMember(name) = target ) ) } @@ -774,7 +885,7 @@ private int unqualifiedMemberAccessDepth(PotentialLocalNameAccess access) { */ cached predicate unqualifiedMemberAccess( - PotentialLocalNameAccess access, boolean instanceAccess, NameBinding target, + PotentialLocalNameAccess access, boolean instanceAccess, MemberTargetNode target, ClassLikeDeclaration accessingClass ) { CachedStage::ref() and @@ -804,15 +915,21 @@ module Public { */ class UnqualifiedMemberAccess extends Identifier, MemberAccessImpl { private boolean instanceAccess; - private NameBinding target; + private MemberTargetNode target; private ClassLikeDeclaration accessingClass; UnqualifiedMemberAccess() { unqualifiedMemberAccess(this, instanceAccess, target, accessingClass) } - /** Gets the name binding of the member being accessed. */ - NameBinding getTarget() { result = target } + /** + * Gets the name-binding node of the member being accessed, which is either a member + * declaration, or a type or member from a model. + */ + MemberTargetNode getTargetNode() { result = target } + + /** Gets the name binding of the member being accessed, if it is declared in the database. */ + NameBinding getTarget() { target.isIdentifier(result) } /** Gets the enclosing class whose (possibly inherited) member is being accessed. */ ClassLikeDeclaration getAccessingClass() { result = accessingClass } @@ -940,5 +1057,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/dataflow/FlowSummary.qll b/unified/ql/lib/codeql/unified/internal/dataflow/FlowSummary.qll index 5e4bdde541e4..2f0ef3c6a150 100644 --- a/unified/ql/lib/codeql/unified/internal/dataflow/FlowSummary.qll +++ b/unified/ql/lib/codeql/unified/internal/dataflow/FlowSummary.qll @@ -6,7 +6,7 @@ private import codeql.unified.internal.mad.LegacyMaD as LegacyMaD private import codeql.dataflow.internal.AccessPathSyntax as AccessPathSyntax module FlowSummaryInput implements InputSig { - class SummarizedCallableBase extends LegacyMaD::Selector { + class SummarizedCallableBase extends LegacyMaD::MemberSelector { SummarizedCallableBase() { LegacyMaD::normalizedSummaryModel(this, _, _, _, _) } Location getLocation() { none() } diff --git a/unified/ql/lib/codeql/unified/internal/mad/LegacyMaD.qll b/unified/ql/lib/codeql/unified/internal/mad/LegacyMaD.qll index 92d68e6315b2..14efe975f8e9 100644 --- a/unified/ql/lib/codeql/unified/internal/mad/LegacyMaD.qll +++ b/unified/ql/lib/codeql/unified/internal/mad/LegacyMaD.qll @@ -7,6 +7,7 @@ private import codeql.dataflow.internal.AccessPathSyntax private import codeql.unified.internal.typeinference.TypeInference as T private import codeql.unified.internal.typeinference.Type as Types private import codeql.unified.internal.StaticNameBinding as N +private import codeql.unified.internal.NameBindingPlugin as NameBindingPlugin private import codeql.unified.internal.dataflow.DataFlowCall private import codeql.unified.internal.dataflow.DataFlowNode @@ -97,8 +98,12 @@ private predicate constructorCallSelector(CallExpr call, TypeSelector type, stri argLabels = getArgLabelsFromCall(call) } -private predicate isSubclassOfType(ClassLikeDeclaration cls, string typeName) { - typeName = any(Selector s).getTypeString() and +private predicate isSubclassOfType(ClassLikeDeclaration cls, TypeSelector typeName) { + ( + typeName = any(MemberSelector s).getTypeString() + or + typeName.getMetaType() = any(MemberSelector s).getTypeString() + ) and ( getQualifiedNameFromExpr(cls.getABaseType().getType()) = typeName or @@ -127,9 +132,14 @@ private predicate callableSelector( ) { name = callable.getName() and argLabels = getArgLabelsFromCallable(callable) and - exists(ClassLikeDeclaration cls | - callable = cls.getAMemberIncludingExtensions() and - isSubclassOfType(cls, type) + 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) + then type = baseType.getMetaType() + else type = baseType ) } @@ -146,12 +156,12 @@ private predicate isRawPropertyName(string name) { pragma[nomagic] private predicate propertyAccessSelector(MemberAccess access, T::Type baseType, string name) { name = access.getMemberName() and - name = any(Selector s).getPropertyName() and + name = any(MemberSelector s).getPropertyName() and not access = any(CallExpr call).getCallee() and baseType = T::inferBaseType(access) } -private newtype TSelector = +private newtype TMemberSelector = MkCallSelector(string type, boolean subtypes, string name, string argLabels, string argTypes) { exists(string rawName | legacySourceModel(_, type, subtypes, rawName, argTypes, _, _, _, _) @@ -174,8 +184,11 @@ private newtype TSelector = /** * A tuple from a model that identifies call sites, callables, or property accesses. + * + * Static members are members of the meta type, so their type is written as, for example, + * `String.Type`. */ -class Selector extends TSelector { +class MemberSelector extends TMemberSelector { string getTypeString() { this = MkCallSelector(result, _, _, _, _) or this = MkPropertySelector(result, _, _) } @@ -240,6 +253,9 @@ class Selector extends TSelector { /** * Holds if `access` is an access to the property identified by this selector, as determined * by the inferred type of its base. + * + * For a static property, the type is a meta type such as `Foo.Type`, so the base must be a + * reference to the type `Foo` itself. */ predicate matchesPropertyAccess(MemberAccess access) { exists(TypeSelector type, boolean subtypes, string name | @@ -256,7 +272,7 @@ class Selector extends TSelector { /** Gets the `n`th `.`-separated component in the given `type` string. */ pragma[nomagic] private string getTypeComponent(string type, int n) { - type = any(Selector s).getTypeString() and + type = any(MemberSelector s).getTypeString() and result = type.splitAt(".", n) } @@ -278,9 +294,21 @@ private string typeSelectorCons(string qualifier, string component) { splitTypeString(_, _, qualifier, component, result) } -/** A type, or prefix thereof, mentioned in a model. */ +/** Holds if `meta` names the meta type of `type`, as in `Foo.Type` for `Foo`. */ +private predicate isMetaTypeOf(string meta, string type) { + splitTypeString(_, _, _, _, type) and + type != "" and + meta = type + ".Type" +} + +/** + * A type, or prefix thereof, mentioned in a model, or the meta type of such a type. + * + * The meta type of `Foo` is named `Foo.Type`. Its instances are references to the type `Foo` + * itself, and its members are the static members of `Foo`. + */ class TypeSelector extends string { - TypeSelector() { splitTypeString(_, _, _, _, this) } + TypeSelector() { splitTypeString(_, _, _, _, this) or isMetaTypeOf(this, _) } TypeSelector append(string component) { result = typeSelectorCons(this, component) } @@ -288,6 +316,12 @@ class TypeSelector extends string { string getHead() { this = typeSelectorCons(_, result) } + /** Gets the meta type of this type, as in `Foo.Type` for `Foo`. */ + TypeSelector getMetaType() { isMetaTypeOf(result, this) } + + /** Holds if this is the meta type of some type. */ + predicate isMetaType() { isMetaTypeOf(this, _) } + /** Gets a static reference to this type. */ AstNode getAStaticRef() { N::trackTypeSelector(this) = N::getNodeFromRef(result) @@ -302,22 +336,34 @@ class TypeSelector extends string { result.getQualifiedName() = this and not exists(result.getExtensionTarget()) } + /** Gets the class-like element corresponding to this type. */ + ClassLikeElement getClassLikeElement() { + result.asTypeSelector() = this + or + result.asClassLikeDeclaration() = this.getDeclaration() + } + /** Gets the declaration of a proper subtype of this type (not the type itself). */ ClassLikeDeclaration getASubtypeDeclaration() { result.getABaseClass*().getABaseType().getType() = this.getAStaticRef() } - /** Gets a `Type` corresponding to instances of this type. */ + /** + * Gets a `Type` corresponding to instances of this type. + * + * The instances of a meta type `Foo.Type` are references to the type `Foo`, whose type is + * the `MetaType` of `Foo`. + */ 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() + or + exists(TypeSelector type | this = type.getMetaType() | + result.(Types::MetaType).getInstanceType() = type.getAnInstanceType(subtype) + ) } /** @@ -432,7 +478,7 @@ private DataFlow::Node getSinkFromPropertyAccess(MemberAccess access, AccessPath } private predicate normalizedSourceModel( - Selector selector, AccessPath output, string kind, string provenance + MemberSelector selector, AccessPath output, string kind, string provenance ) { exists(string type, boolean subtypes, string rawName, string argTypes | legacySourceModel(_, type, subtypes, rawName, argTypes, _, output, kind, provenance) @@ -447,7 +493,7 @@ private predicate normalizedSourceModel( } private predicate normalizedSinkModel( - Selector selector, AccessPath output, string kind, string provenance + MemberSelector selector, AccessPath output, string kind, string provenance ) { exists(string type, boolean subtypes, string rawName, string argTypes | legacySinkModel(_, type, subtypes, rawName, argTypes, _, output, kind, provenance) @@ -462,7 +508,7 @@ private predicate normalizedSinkModel( } predicate normalizedSummaryModel( - Selector selector, string input, string output, string kind, string provenance + MemberSelector selector, string input, string output, string kind, string provenance ) { exists( string type, boolean subtypes, string rawName, string name, string argLabels, string argTypes @@ -477,7 +523,7 @@ predicate normalizedSummaryModel( * Gets a flow source with the given `kind` and `provenance`. */ DataFlow::Node getASource(string kind, string provenance) { - exists(Selector selector, AccessPath output | + exists(MemberSelector selector, AccessPath output | normalizedSourceModel(selector, output, kind, provenance) | exists(DataFlowCall call | @@ -501,7 +547,7 @@ DataFlow::Node getASource(string kind, string provenance) { * Gets a sink with the given `kind` and `provenance`. */ DataFlow::Node getASink(string kind, string provenance) { - exists(Selector selector, AccessPath input | + exists(MemberSelector selector, AccessPath input | normalizedSinkModel(selector, input, kind, provenance) | exists(DataFlowCall call | @@ -533,7 +579,7 @@ module Public { } private module Debug { - query predicate invalidAccessPath(Selector selector, AccessPathToken ap) { + query predicate invalidAccessPath(MemberSelector selector, AccessPathToken ap) { ( normalizedSourceModel(selector, ap, _, _) or diff --git a/unified/ql/lib/codeql/unified/internal/typeinference/Type.qll b/unified/ql/lib/codeql/unified/internal/typeinference/Type.qll index 4e5de7422b33..f89e000f7606 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/Type.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/Type.qll @@ -44,7 +44,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,11 +55,16 @@ private predicate isNestedType(Member m, Identifier nested, ClassLikeDeclaration cached newtype TType = - TClassLikeDeclarationType(ClassLikeDeclaration c) { + TClassLikeType(ClassLikeElement e) { CachedStage::ref() and - exists(c.getNameNode()) + ( + exists(e.asClassLikeDeclaration().getNameNode()) + or + exists(e.asTypeSelector()) + ) } or TAliasType(TypeAliasDeclaration alias) or + TMetaType(ClassLikeElement e) { exists(TClassLikeType(e)) } or TClosureParameterPseudoType(ParameterEx p) { p.isFunctionExprParameter(_, _) and not exists(p.getType()) @@ -70,7 +76,6 @@ newtype TType = associatedTypeParameter(c, a, inherited) } or TParentTypeParameterType(Member m) { isNestedType(m, _, _) } or - TModelType(MaD::TypeSelector selector) { not exists(selector.getDeclaration()) } or TUnknownType() or TUnknownTypeTypeParameter(int i) { i in [0 .. 20] } @@ -103,7 +108,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() } @@ -118,36 +123,70 @@ 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; + + ClassLikeType() { this = TClassLikeType(e) } - ClassLikeDeclarationType() { this = TClassLikeDeclarationType(c) } + /** Gets the class-like element represented by this type. */ + ClassLikeElement getClassLikeElement() { result = e } - ClassLikeDeclaration getClassLikeDeclaration() { result = c } + /** Gets the primary declaration of this type, if any. */ + ClassLikeDeclaration getClassLikeDeclaration() { result = e.asClassLikeDeclaration() } - string getName() { result = c.getName() } + /** Gets the type selector describing this type, if it is only known from a model. */ + MaD::TypeSelector getTypeSelector() { result = e.asTypeSelector() } - 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 = e.getLocation() } +} + +/** + * A type representing a class-like element itself, as opposed to instances of it. + * + * For example, in `Foo.bar`, the base `Foo` has the meta type of `Foo`. In Swift, this + * corresponds to the type `Foo.Type`. + */ +class MetaType extends TypeImpl, TMetaType { + private ClassLikeElement e; + + MetaType() { this = TMetaType(e) } + + /** Gets the class-like element whose meta type this is. */ + ClassLikeElement getClassLikeElement() { result = e } + + /** Gets the type of instances of the class-like element, as opposed to the element itself. */ + ClassLikeType getInstanceType() { result.getClassLikeElement() = e } + + override Identifier getNameNode() { none() } + + override TypeParameter getPositionalTypeParameter(int i) { none() } + + override string toString() { result = e.getQualifiedName() + ".Type" } - override Location getLocation() { result = c.getLocation() } + override Location getLocation() { result = e.getLocation() } } /** @@ -174,26 +213,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 d4f8f7a50c55..e28d94be3842 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/TypeInference.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/TypeInference.qll @@ -217,6 +217,15 @@ module Input3 implements InputSig3 { ) } + pragma[nomagic] + predicate isStaticMemberOf(ClassLikeDeclaration cls, string name) { + exists(NamespaceNode ns, Identifier i | + ns.isStaticMemberNamespace(cls) and + ns.getMember(name).isIdentifier(i) and + i = this.getNameNode() + ) + } + Unified::Callable asCallable() { this = TCallableDeclaration(result) } } @@ -306,10 +315,26 @@ module Input3 implements InputSig3 { } pragma[nomagic] - private Declaration lookupInstanceMember(MemberAccessExpr mae) { + private predicate lookupStaticMember0(MemberAccessExpr mae, ClassLikeDeclaration cls, string name) { + not exists(getStaticBindingTargetFromRef(mae)) and // if a static member can be resolved, use it + cls = inferType(mae.getBase()).(MetaType).getInstanceType().getClassLikeDeclaration() and + name = mae.getMemberName() + } + + /** + * Gets the member accessed by `mae`, based on the inferred type of its base. + * + * If the base is an instance of a class, this is an instance member of that class. If the base + * has a meta type, such as `X.Type`, this is a static member of `X`. + */ + pragma[nomagic] + private Declaration lookupMember(MemberAccessExpr mae) { exists(ClassLikeDeclaration cls, string name | lookupMember0(mae, cls, name) and result.isInstanceMemberOf(cls, name) + or + lookupStaticMember0(mae, cls, name) and + result.isStaticMemberOf(cls, name) ) } @@ -324,7 +349,7 @@ module Input3 implements InputSig3 { override Field getField() { // mutual recursion; resolving qualified fields requires resolving types and vice versa - result = lookupInstanceMember(this) + result = lookupMember(this) or // also mutual recursion exists(TupleType tuple, string name | @@ -591,12 +616,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 ) @@ -611,7 +631,7 @@ module Input3 implements InputSig3 { Callable getTarget() { ( // mutual recursion; call with explicit receiver: `obj.foo(42)` - result = lookupInstanceMember(this.getCallee()) + result = lookupMember(this.getCallee()) or // mutual recursion; call to a function expression: `callback(42)` result.asCallable() = this.getInvokeTarget(_) @@ -635,7 +655,7 @@ module Input3 implements InputSig3 { * otherwise updated in place. */ Callable getSetterTarget() { - result = [lookupInstanceMember(this.getCallee()), this.getTargetViaStaticNameBinding()] and + result = [lookupMember(this.getCallee()), this.getTargetViaStaticNameBinding()] and result.asCallable() instanceof SetterMethodDeclaration } @@ -845,7 +865,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 +876,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 +920,7 @@ module Input3 implements InputSig3 { result instanceof UnknownType or path.isEmpty() and - n = result.(ModelType).getTypeSelector().getAConstructorCall() + n = result.(ClassLikeType).getTypeSelector().getAConstructorCall() } predicate allowContextualInference(TypeMention tm, TypePath path) { @@ -938,7 +957,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 @@ -985,11 +1004,23 @@ Type inferVariableType(LocalVariable variable) { result = Input3::inferTypeFromVariable(variable, _) } -/** Gets the type of the given base of `access`. */ +/** + * Gets the type of the given base of `access`. + * + * If the base is a reference to a class-like type, as in `Foo.bar`, or is an implicit + * reference to the enclosing type in a static context, the result is a `MetaType`. + */ Type inferBaseType(MemberAccess access) { result = inferType(access.(MemberAccessExpr).getBase()) or + result.(MetaType).getInstanceType() = access.(MemberAccessExpr).getBase().(TypeMention).getType() + or result = inferVariableType(access.(UnqualifiedMemberAccess).getImplicitQualifierVariable()) + or + exists(UnqualifiedMemberAccess uma | uma = access | + not uma.isInstanceAccess() and + result.(MetaType).getClassLikeElement() = uma.getAccessingClass().getClassLikeElement() + ) } module Consistency = M3::Consistency; diff --git a/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePlugin.qll b/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePlugin.qll index 097b2edfb6b2..559153b571db 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePlugin.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePlugin.qll @@ -92,6 +92,11 @@ class TypeInferencePlugin extends Unit { /** Gets the inferred type for the given AST node and type path. */ Type inferType(AstNode n, TypePath path) { none() } + + /** + * Gets the operand of `e` if `e` is a mention of a meta type, such as `X` in `X.Type`. + */ + Expr getMetaTypeOperand(Expr e) { none() } } class BoolType extends Type { @@ -128,6 +133,9 @@ TypePath getFunctionExprReturnTypePath(Type t) { result = any(TypeInferencePlugin pl).getFunctionExprReturnTypePath(t) } +/** Gets the operand of `e` if `e` is a mention of a meta type, such as `X` in `X.Type`. */ +Expr getMetaTypeOperand(Expr e) { result = any(TypeInferencePlugin p).getMetaTypeOperand(e) } + class TupleType extends Type { int arity; diff --git a/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePluginSwift.qll b/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePluginSwift.qll index ecb52be938fa..144f13215bd9 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePluginSwift.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/TypeInferencePluginSwift.qll @@ -7,17 +7,18 @@ module; private import Type private import TypeInference private import TypeInferencePlugin as Plugin +private import TypeMention 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 } } @@ -159,5 +160,17 @@ private class SwiftTypeInferencePlugin extends Plugin::TypeInferencePlugin { n instanceof BinaryExpr and result = inferTypeAlias(n.(BinaryExpr).getLeft(), path) and result = inferTypeAlias(n.(BinaryExpr).getRight(), path) + or + // `X.self` evaluates to the type `X` itself, whose type is the meta type `X.Type` + exists(MemberAccessExpr mae | n = mae | + mae.getMemberName() = "self" and + result.(MetaType).getInstanceType() = mae.getBase().(TypeMention).getType() and + path.isEmpty() + ) + } + + override Expr getMetaTypeOperand(Expr e) { + e.(MemberAccessExpr).getMemberName() = "Type" and + result = e.(MemberAccessExpr).getBase() } } diff --git a/unified/ql/lib/codeql/unified/internal/typeinference/TypeMention.qll b/unified/ql/lib/codeql/unified/internal/typeinference/TypeMention.qll index 702a7351f276..41bb7157a489 100644 --- a/unified/ql/lib/codeql/unified/internal/typeinference/TypeMention.qll +++ b/unified/ql/lib/codeql/unified/internal/typeinference/TypeMention.qll @@ -56,7 +56,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 +121,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 +254,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 +281,15 @@ class ExprTypeMention extends TypeMentionImpl, Expr { or result.(Plugin::TupleType).getArity() = this.(TupleExpr).getNumberOfElements() or - result.(ModelType).getTypeSelector().getAStaticRef() = this + result.(ClassLikeType).getTypeSelector().getAStaticRef() = this + or + // A meta type, such as `X.Type`, unless `Type` refers to a nested type named `Type` + not exists(getTypeFromRef(this)) and + exists(Expr operand | operand = Plugin::getMetaTypeOperand(this) | + result.(MetaType).getInstanceType().getNameNode() = getExpandedTypeFromRef(operand) + or + result.(MetaType).getInstanceType().getTypeSelector().getAStaticRef() = operand + ) } override Type getUnexpandedType() { diff --git a/unified/ql/lib/ext/database.model.json b/unified/ql/lib/ext/database.model.json index 50f26fcb8fa7..8f2e2c799adf 100644 --- a/unified/ql/lib/ext/database.model.json +++ b/unified/ql/lib/ext/database.model.json @@ -35,7 +35,7 @@ ["", "QueryType", true, "upsert(_:onConflictOf:)", "", "", "Argument[0]", "database-store", "manual"], ["", "QueryType", true, "upsert(_:onConflictOf:setValues:)", "", "", "Argument[0]", "database-store", "manual"], ["", "QueryType", true, "upsert(_:onConflictOf:setValues:)", "", "", "Argument[setValues:]", "database-store", "manual"], - ["", "Connection.Location", true, "uri(_:parameters:)", "", "", "Argument[0]", "path-injection", "manual"], + ["", "Connection.Location.Type", true, "uri(_:parameters:)", "", "", "Argument[0]", "path-injection", "manual"], // GRDB ["", "Database", true, "changePassphrase(_:)", "", "", "Argument[0]", "encryption-key", "manual"], ["", "Database", true, "usePassphrase(_:)", "", "", "Argument[0]", "encryption-key", "manual"], @@ -59,26 +59,26 @@ ["", "SQLRequest", true, "init(stringInterpolation:)", "", "", "Argument[stringInterpolation:]", "sql-injection", "manual"], ["", "SQLStatementCursor", true, "init(database:sql:arguments:prepFlags:)", "", "", "Argument[sql:]", "sql-injection", "manual"], ["", "SQLStatementCursor", true, "init(database:sql:arguments:prepFlags:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "Row", true, "fetchAll(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "Row", true, "fetchCursor(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "Row", true, "fetchOne(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "Row", true, "fetchSet(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "TableRecord", true, "filter(sql:arguments:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "TableRecord", true, "order(sql:arguments:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "TableRecord", true, "select(sql:arguments:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "TableRecord", true, "select(sql:arguments:as:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "DatabaseValueConvertible", true, "fetchAll(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "DatabaseValueConvertible", true, "fetchCursor(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "DatabaseValueConvertible", true, "fetchOne(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "DatabaseValueConvertible", true, "fetchSet(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "FetchableRecord", true, "fetchAll(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "FetchableRecord", true, "fetchCursor(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "FetchableRecord", true, "fetchOne(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "FetchableRecord", true, "fetchSet(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "FetchableRecord", true, "fetchAll(_:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "FetchableRecord", true, "fetchCursor(_:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "FetchableRecord", true, "fetchOne(_:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], - ["", "FetchableRecord", true, "fetchSet(_:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "Row.Type", true, "fetchAll(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "Row.Type", true, "fetchCursor(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "Row.Type", true, "fetchOne(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "Row.Type", true, "fetchSet(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "TableRecord.Type", true, "filter(sql:arguments:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "TableRecord.Type", true, "order(sql:arguments:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "TableRecord.Type", true, "select(sql:arguments:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "TableRecord.Type", true, "select(sql:arguments:as:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "DatabaseValueConvertible.Type", true, "fetchAll(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "DatabaseValueConvertible.Type", true, "fetchCursor(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "DatabaseValueConvertible.Type", true, "fetchOne(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "DatabaseValueConvertible.Type", true, "fetchSet(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "FetchableRecord.Type", true, "fetchAll(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "FetchableRecord.Type", true, "fetchCursor(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "FetchableRecord.Type", true, "fetchOne(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "FetchableRecord.Type", true, "fetchSet(_:sql:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "FetchableRecord.Type", true, "fetchAll(_:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "FetchableRecord.Type", true, "fetchCursor(_:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "FetchableRecord.Type", true, "fetchOne(_:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], + ["", "FetchableRecord.Type", true, "fetchSet(_:arguments:adapter:)", "", "", "Argument[arguments:]", "database-store", "manual"], ["", "Statement", true, "execute(arguments:)", "", "", "Argument[arguments:]", "database-store", "manual"], ["", "Statement", true, "setArguments(_:)", "", "", "Argument[0]", "database-store", "manual"], ["", "CommonTableExpression", true, "init(recursive:named:columns:sql:arguments:)", "", "", "Argument[arguments:]", "database-store", "manual"], diff --git a/unified/ql/lib/ext/format-string.model.yml b/unified/ql/lib/ext/format-string.model.yml index bf95df4f5efa..128280aa95a9 100644 --- a/unified/ql/lib/ext/format-string.model.yml +++ b/unified/ql/lib/ext/format-string.model.yml @@ -7,20 +7,20 @@ extensions: - ["", "String", true, "init(format:arguments:)", "", "", "Argument[format:]", "format-string", "manual"] - ["", "String", true, "init(format:locale:_:)", "", "", "Argument[format:]", "format-string", "manual"] - ["", "String", true, "init(format:locale:arguments:)", "", "", "Argument[format:]", "format-string", "manual"] - - ["", "String", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "format-string", "manual"] + - ["", "String.Type", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "format-string", "manual"] - ["", "NSString", true, "init(format:_:)", "", "", "Argument[format:]", "format-string", "manual"] - ["", "NSString", true, "init(format:arguments:)", "", "", "Argument[format:]", "format-string", "manual"] - ["", "NSString", true, "init(format:locale:_:)", "", "", "Argument[format:]", "format-string", "manual"] - ["", "NSString", true, "init(format:locale:arguments:)", "", "", "Argument[format:]", "format-string", "manual"] - - ["", "NSString", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "format-string", "manual"] + - ["", "NSString.Type", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "format-string", "manual"] - ["", "NSMutableString", true, "init(format:_:)", "", "", "Argument[format:]", "format-string", "manual"] - ["", "NSMutableString", true, "init(format:arguments:)", "", "", "Argument[format:]", "format-string", "manual"] - ["", "NSMutableString", true, "init(format:locale:_:)", "", "", "Argument[format:]", "format-string", "manual"] - ["", "NSMutableString", true, "init(format:locale:arguments:)", "", "", "Argument[format:]", "format-string", "manual"] - - ["", "NSMutableString", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "format-string", "manual"] + - ["", "NSMutableString.Type", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "format-string", "manual"] - ["", "NSMutableString", true, "appendFormat(_:_:)", "", "", "Argument[0]", "format-string", "manual"] - ["", "StringProtocol", true, "appendingFormat(_:_:)", "", "", "Argument[0]", "format-string", "manual"] - - ["", "NSException", true, "raise(_:format:arguments:)", "", "", "Argument[format:]", "format-string", "manual"] + - ["", "NSException.Type", true, "raise(_:format:arguments:)", "", "", "Argument[format:]", "format-string", "manual"] - ["", "", false, "NSLog(_:_:)", "", "", "Argument[0]", "format-string", "manual"] - ["", "", false, "NSLogv(_:_:)", "", "", "Argument[0]", "format-string", "manual"] - ["", "", false, "printf(_:_:)", "", "", "Argument[0]", "format-string", "manual"] diff --git a/unified/ql/lib/ext/legacy-swift.model.json b/unified/ql/lib/ext/legacy-swift.model.json index 7719aa749f20..3f3653bb9ce6 100644 --- a/unified/ql/lib/ext/legacy-swift.model.json +++ b/unified/ql/lib/ext/legacy-swift.model.json @@ -36,9 +36,9 @@ ["", "NSString", true, "length", "", "", "", "nsstring-length", "manual"], ["", "NSString", true, "init(contentsOf:)", "", "", "ReturnValue", "remote", "manual"], ["", "NSString", true, "init(contentsOfFile:)", "", "", "ReturnValue", "local", "manual"], - ["", "NSString", true, "string(withContentsOf:)", "", "", "ReturnValue", "remote", "manual"], + ["", "NSString.Type", true, "string(withContentsOf:)", "", "", "ReturnValue", "remote", "manual"], ["", "NSString", true, "init(contentsOf:encoding:)", "", "", "ReturnValue", "remote", "manual"], - ["", "NSString", true, "string(withContentsOfFile:)", "", "", "ReturnValue", "local", "manual"], + ["", "NSString.Type", true, "string(withContentsOfFile:)", "", "", "ReturnValue", "local", "manual"], ["", "NSString", true, "init(contentsOfFile:encoding:)", "", "", "ReturnValue", "local", "manual"], ["", "NSString", true, "init(contentsOf:usedEncoding:)", "", "", "ReturnValue", "remote", "manual"], ["", "NSString", true, "init(contentsOfFile:usedEncoding:)", "", "", "ReturnValue", "local", "manual"], @@ -109,7 +109,7 @@ ["", "NSData", true, "init(contentsOf:)", "", "", "Argument[contentsOf:]", "path-injection", "manual"], ["", "NSData", true, "init(contentsOfFile:)", "", "", "Argument[contentsOfFile:]", "path-injection", "manual"], ["", "NSData", true, "init(contentsOf:options:)", "", "", "Argument[contentsOf:]", "path-injection", "manual"], - ["", "NSData", true, "dataWithContentsOfMappedFile(_:)", "", "", "Argument[0]", "path-injection", "manual"], + ["", "NSData.Type", true, "dataWithContentsOfMappedFile(_:)", "", "", "Argument[0]", "path-injection", "manual"], ["", "NSData", true, "init(contentsOfFile:options:)", "", "", "Argument[contentsOfFile:]", "path-injection", "manual"], ["", "NSData", true, "init(contentsOfMappedFile:)", "", "", "Argument[contentsOfMappedFile:]", "path-injection", "manual"], ["", "NSData", true, "write(to:options:)", "", "", "Argument[to:]", "path-injection", "manual"], @@ -185,7 +185,7 @@ ["", "URLSessionConfiguration", false, "tlsMaximumSupportedProtocolVersion", "", "", "PostUpdate", "tls-protocol-version", "manual"], ["", "URLSessionConfiguration", false, "tlsMinimumSupportedProtocolVersion", "", "", "PostUpdate", "tls-protocol-version", "manual"], ["", "NWConnection", true, "send(content:contentContext:isComplete:completion:)", "", "", "Argument[content:]", "transmission", "manual"], - ["", "Zip", true, "unzipFile(_:destination:overwrite:password:progress:fileOutputHandler:)", "", "", "Argument[0]", "unsafe-unpack", "manual"], + ["", "Zip.Type", true, "unzipFile(_:destination:overwrite:password:progress:fileOutputHandler:)", "", "", "Argument[0]", "unsafe-unpack", "manual"], ["", "NSRange", true, "init(location:length:)", "", "", "Argument[location:,length:]", "nsstring-length", "manual"], ["", "NSUserScriptTask", true, "init(url:)", "", "", "Argument[url:]", "command-injection", "manual"], ["", "NSUserUnixTask", true, "execute(withArguments:completionHandler:)", "", "", "Argument[withArguments:]", "command-injection", "manual"], @@ -195,10 +195,10 @@ ["", "Process", true, "environment", "", "", "PostUpdate", "command-injection", "manual"], ["", "Process", true, "executableURL", "", "", "PostUpdate", "command-injection", "manual"], ["", "Process", true, "launchPath", "", "", "PostUpdate", "command-injection", "manual"], - ["", "Process", true, "launchedProcess(launchPath:arguments:)", "", "", "Argument[launchPath:,arguments:]", "command-injection", "manual"], + ["", "Process.Type", true, "launchedProcess(launchPath:arguments:)", "", "", "Argument[launchPath:,arguments:]", "command-injection", "manual"], // Calls may omit the defaulted terminationHandler argument. - ["", "Process", true, "run(_:arguments:)", "", "", "Argument[0,arguments:]", "command-injection", "manual"], - ["", "Process", true, "run(_:arguments:terminationHandler:)", "", "", "Argument[0,arguments:]", "command-injection", "manual"], + ["", "Process.Type", true, "run(_:arguments:)", "", "", "Argument[0,arguments:]", "command-injection", "manual"], + ["", "Process.Type", true, "run(_:arguments:terminationHandler:)", "", "", "Argument[0,arguments:]", "command-injection", "manual"], ["", "Process", true, "standardError", "", "", "PostUpdate", "command-injection", "manual"], ["", "Process", true, "standardInput", "", "", "PostUpdate", "command-injection", "manual"], ["", "Process", true, "standardOutput", "", "", "PostUpdate", "command-injection", "manual"], @@ -214,20 +214,20 @@ ["", "JSContext", true, "evaluateScript(_:)", "", "", "Argument[0]", "code-injection", "manual"], ["", "JSContext", true, "evaluateScript(_:withSourceURL:)", "", "", "Argument[0]", "code-injection", "manual"], ["", "", false, "JSEvaluateScript(_:_:_:_:_:_:)", "", "", "Argument[1]", "code-injection", "manual"], - ["", "Digest", true, "md5(_:)", "", "", "Argument[0]", "weak-hash-input-MD5", "manual"], - ["", "Digest", true, "sha1(_:)", "", "", "Argument[0]", "weak-hash-input-SHA1", "manual"], - ["", "Digest", true, "sha2(_:variant:)", "", "", "Argument[0]", "weak-password-hash-input-SHA2", "manual"], - ["", "Digest", true, "sha224(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA224", "manual"], - ["", "Digest", true, "sha256(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA256", "manual"], - ["", "Digest", true, "sha3(_:variant:)", "", "", "Argument[0]", "weak-password-hash-input-SHA3", "manual"], - ["", "Digest", true, "sha384(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA384", "manual"], - ["", "Digest", true, "sha512(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA512", "manual"], - ["", "Insecure.MD5", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-hash-input-MD5", "manual"], - ["", "Insecure.MD5", true, "hash(data:)", "", "", "Argument[data:]", "weak-hash-input-MD5", "manual"], + ["", "Digest.Type", true, "md5(_:)", "", "", "Argument[0]", "weak-hash-input-MD5", "manual"], + ["", "Digest.Type", true, "sha1(_:)", "", "", "Argument[0]", "weak-hash-input-SHA1", "manual"], + ["", "Digest.Type", true, "sha2(_:variant:)", "", "", "Argument[0]", "weak-password-hash-input-SHA2", "manual"], + ["", "Digest.Type", true, "sha224(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA224", "manual"], + ["", "Digest.Type", true, "sha256(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA256", "manual"], + ["", "Digest.Type", true, "sha3(_:variant:)", "", "", "Argument[0]", "weak-password-hash-input-SHA3", "manual"], + ["", "Digest.Type", true, "sha384(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA384", "manual"], + ["", "Digest.Type", true, "sha512(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA512", "manual"], + ["", "Insecure.MD5.Type", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-hash-input-MD5", "manual"], + ["", "Insecure.MD5.Type", true, "hash(data:)", "", "", "Argument[data:]", "weak-hash-input-MD5", "manual"], ["", "Insecure.MD5", true, "update(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-hash-input-MD5", "manual"], ["", "Insecure.MD5", true, "update(data:)", "", "", "Argument[data:]", "weak-hash-input-MD5", "manual"], - ["", "Insecure.SHA1", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-hash-input-SHA1", "manual"], - ["", "Insecure.SHA1", true, "hash(data:)", "", "", "Argument[data:]", "weak-hash-input-SHA1", "manual"], + ["", "Insecure.SHA1.Type", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-hash-input-SHA1", "manual"], + ["", "Insecure.SHA1.Type", true, "hash(data:)", "", "", "Argument[data:]", "weak-hash-input-SHA1", "manual"], ["", "Insecure.SHA1", true, "update(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-hash-input-SHA1", "manual"], ["", "Insecure.SHA1", true, "update(data:)", "", "", "Argument[data:]", "weak-hash-input-SHA1", "manual"], ["", "MD5", true, "callAsFunction(_:)", "", "", "Argument[0]", "weak-hash-input-MD5", "manual"], @@ -249,9 +249,9 @@ ["", "Logger", true, "notice(_:)", "", "", "Argument[0]", "log-injection", "manual"], ["", "Logger", true, "trace(_:)", "", "", "Argument[0]", "log-injection", "manual"], ["", "NSException", true, "init(name:reason:userInfo:)", "", "", "Argument[reason:]", "log-injection", "manual"], - ["", "NSException", true, "raise(_:format:arguments:)", "", "", "Argument[format:,arguments:]", "log-injection", "manual"], - ["", "SHA256", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA256", "manual"], - ["", "SHA256", true, "hash(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA256", "manual"], + ["", "NSException.Type", true, "raise(_:format:arguments:)", "", "", "Argument[format:,arguments:]", "log-injection", "manual"], + ["", "SHA256.Type", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA256", "manual"], + ["", "SHA256.Type", true, "hash(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA256", "manual"], ["", "SHA256", true, "update(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA256", "manual"], ["", "SHA256", true, "update(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA256", "manual"], ["", "SHA2", true, "callAsFunction(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA2", "manual"], @@ -259,28 +259,28 @@ ["", "SHA2", true, "update(withBytes:isLast:)", "", "", "Argument[withBytes:]", "weak-password-hash-input-SHA2", "manual"], ["", "SHA2", true, "process32(block:currentHash:)", "", "", "Argument[block:]", "weak-password-hash-input-SHA2", "manual"], ["", "SHA2", true, "process64(block:currentHash:)", "", "", "Argument[block:]", "weak-password-hash-input-SHA2", "manual"], - ["", "SHA384", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA384", "manual"], - ["", "SHA384", true, "hash(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA384", "manual"], + ["", "SHA384.Type", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA384", "manual"], + ["", "SHA384.Type", true, "hash(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA384", "manual"], ["", "SHA384", true, "update(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA384", "manual"], ["", "SHA384", true, "update(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA384", "manual"], ["", "SHA3", true, "callAsFunction(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA2", "manual"], ["", "SHA3", true, "calculate(for:)", "", "", "Argument[for:]", "weak-password-hash-input-SHA2", "manual"], ["", "SHA3", true, "process(block:currentHash:)", "", "", "Argument[block:]", "weak-password-hash-input-SHA2", "manual"], ["", "SHA3", true, "update(withBytes:isLast:)", "", "", "Argument[withBytes:]", "weak-password-hash-input-SHA2", "manual"], - ["", "SHA512", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA512", "manual"], - ["", "SHA512", true, "hash(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA512", "manual"], + ["", "SHA512.Type", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA512", "manual"], + ["", "SHA512.Type", true, "hash(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA512", "manual"], ["", "SHA512", true, "update(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA512", "manual"], ["", "SHA512", true, "update(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA512", "manual"], - ["", "ArchiveByteStream", true, "fileStream(fd:automaticClose:)", "", "", "Argument[fd:]", "path-injection", "manual"], - ["", "ArchiveByteStream", true, "fileStream(path:mode:options:permissions:)", "", "", "Argument[path:]", "path-injection", "manual"], - ["", "ArchiveByteStream", true, "withFileStream(fd:automaticClose:_:)", "", "", "Argument[fd:]", "path-injection", "manual"], - ["", "ArchiveByteStream", true, "withFileStream(path:mode:options:permissions:_:)", "", "", "Argument[path:]", "path-injection", "manual"], + ["", "ArchiveByteStream.Type", true, "fileStream(fd:automaticClose:)", "", "", "Argument[fd:]", "path-injection", "manual"], + ["", "ArchiveByteStream.Type", true, "fileStream(path:mode:options:permissions:)", "", "", "Argument[path:]", "path-injection", "manual"], + ["", "ArchiveByteStream.Type", true, "withFileStream(fd:automaticClose:_:)", "", "", "Argument[fd:]", "path-injection", "manual"], + ["", "ArchiveByteStream.Type", true, "withFileStream(path:mode:options:permissions:_:)", "", "", "Argument[path:]", "path-injection", "manual"], ["", "Bundle", true, "init(url:)", "", "", "Argument[url:]", "path-injection", "manual"], ["", "Bundle", true, "init(path:)", "", "", "Argument[path:]", "path-injection", "manual"], ["", "NIOFileHandle", true, "init(path:)", "", "", "Argument[path:]", "path-injection", "manual"], ["", "NIOFileHandle", true, "init(descriptor:)", "", "", "Argument[descriptor:]", "path-injection", "manual"], ["", "NIOFileHandle", true, "init(path:mode:flags:)", "", "", "Argument[path:]", "path-injection", "manual"], - ["", "NSKeyedUnarchiver", true, "unarchiveObject(withFile:)", "", "", "Argument[withFile:]", "path-injection", "manual"] + ["", "NSKeyedUnarchiver.Type", true, "unarchiveObject(withFile:)", "", "", "Argument[withFile:]", "path-injection", "manual"] ] }, { @@ -557,8 +557,8 @@ ["", "String", true, "split(maxSplits:omittingEmptySubsequences:whereSeparator:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "String", true, "init(stringLiteral:)", "", "", "Argument[stringLiteral:]", "ReturnValue", "taint", "manual"], ["", "String", true, "init(stringInterpolation:)", "", "", "Argument[stringInterpolation:]", "ReturnValue", "taint", "manual"], - ["", "String", true, "decodeCString(_:as:repairingInvalidCodeUnits:)", "", "", "Argument[0]", "ReturnValue.TupleElement[0]", "taint", "manual"], - ["", "String", true, "decodeCString(_:as:repairingInvalidCodeUnits:)", "", "", "Argument[0].CollectionElement", "ReturnValue.TupleElement[0]", "taint", "manual"], + ["", "String.Type", true, "decodeCString(_:as:repairingInvalidCodeUnits:)", "", "", "Argument[0]", "ReturnValue.TupleElement[0]", "taint", "manual"], + ["", "String.Type", true, "decodeCString(_:as:repairingInvalidCodeUnits:)", "", "", "Argument[0].CollectionElement", "ReturnValue.TupleElement[0]", "taint", "manual"], ["", "String", true, "init(validatingUTF8:)", "", "", "Argument[validatingUTF8:]", "ReturnValue.OptionalSome", "taint", "manual"], ["", "String", true, "init(validatingUTF8:)", "", "", "Argument[validatingUTF8:].CollectionElement", "ReturnValue.OptionalSome", "taint", "manual"], ["", "String", true, "enumerated()", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], @@ -596,8 +596,8 @@ ["", "String", true, "init(format:locale:arguments:)", "", "", "Argument[arguments:].CollectionElement", "ReturnValue", "taint", "manual"], ["", "String", true, "init(utf8String:)", "", "", "Argument[utf8String:]", "ReturnValue.OptionalSome", "taint", "manual"], ["", "String", true, "init(utf8String:)", "", "", "Argument[utf8String:].CollectionElement", "ReturnValue.OptionalSome", "taint", "manual"], - ["", "String", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "ReturnValue", "taint", "manual"], - ["", "String", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[1].CollectionElement", "ReturnValue", "taint", "manual"], + ["", "String.Type", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "ReturnValue", "taint", "manual"], + ["", "String.Type", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[1].CollectionElement", "ReturnValue", "taint", "manual"], ["", "String", true, "init(bytes:encoding:)", "", "", "Argument[bytes:].CollectionElement", "ReturnValue.OptionalSome", "taint", "manual"], ["", "String", true, "init(contendsOf:usedEncoding:)", "", "", "Argument[contendsOf:]", "ReturnValue", "taint", "manual"], ["", "String", true, "init(decoding:)", "", "", "Argument[decoding:]", "ReturnValue", "taint", "manual"], @@ -750,10 +750,10 @@ ["", "Strideable", true, "distance(to:)", "", "", "Argument[self,to:]", "ReturnValue", "taint", "manual"], ["", "FloatingPoint", true, "init(_:)", "", "", "Argument[0]", "ReturnValue", "taint", "manual"], ["", "FloatingPoint", true, "rounded(_:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], - ["", "FloatingPoint", true, "maximumMagnitude(_:_:)", "", "", "Argument[0,1]", "ReturnValue", "taint", "manual"], - ["", "FloatingPoint", true, "minimumMagnitude(_:_:)", "", "", "Argument[0,1]", "ReturnValue", "taint", "manual"], - ["", "FloatingPoint", true, "maximum(_:_:)", "", "", "Argument[0,1]", "ReturnValue", "taint", "manual"], - ["", "FloatingPoint", true, "minimum(_:_:)", "", "", "Argument[0,1]", "ReturnValue", "taint", "manual"], + ["", "FloatingPoint.Type", true, "maximumMagnitude(_:_:)", "", "", "Argument[0,1]", "ReturnValue", "taint", "manual"], + ["", "FloatingPoint.Type", true, "minimumMagnitude(_:_:)", "", "", "Argument[0,1]", "ReturnValue", "taint", "manual"], + ["", "FloatingPoint.Type", true, "maximum(_:_:)", "", "", "Argument[0,1]", "ReturnValue", "taint", "manual"], + ["", "FloatingPoint.Type", true, "minimum(_:_:)", "", "", "Argument[0,1]", "ReturnValue", "taint", "manual"], ["", "FloatingPoint", true, "addProduct(_:_:)", "", "", "Argument[self,0,1]", "Argument[self]", "taint", "manual"], ["", "FloatingPoint", true, "addingProduct(_:_:)", "", "", "Argument[self,0,1]", "ReturnValue", "taint", "manual"], ["", "FloatingPoint", true, "squareRoot()", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], @@ -827,11 +827,11 @@ ["", "URL", true, "bookmarkData(options:includingResourceValuesForKeys:relativeTo:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "URL", true, "bookmarkData(options:includingResourceValuesForKeys:relativeTo:)", "", "", "Argument[includingResourceValuesForKeys:].OptionalSome.CollectionElement", "ReturnValue", "taint", "manual"], ["", "URL", true, "bookmarkData(options:includingResourceValuesForKeys:relativeTo:)", "", "", "Argument[relativeTo:].OptionalSome", "ReturnValue", "taint", "manual"], - ["", "URL", true, "bookmarkData(withContentsOf:)", "", "", "Argument[withContentsOf:]", "ReturnValue", "taint", "manual"], + ["", "URL.Type", true, "bookmarkData(withContentsOf:)", "", "", "Argument[withContentsOf:]", "ReturnValue", "taint", "manual"], ["", "URL", true, "deletingLastPathComponent()", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "URL", true, "deletingPathExtension()", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "URL", true, "fragment(percentEncoded:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], - ["", "URL", true, "homeDirectory(forUser:)", "", "", "Argument[forUser:]", "ReturnValue", "taint", "manual"], + ["", "URL.Type", true, "homeDirectory(forUser:)", "", "", "Argument[forUser:]", "ReturnValue", "taint", "manual"], ["", "URL", true, "host(percentEncoded:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "URL", true, "init(_:isDirectory:)", "", "", "Argument[0]", "ReturnValue.OptionalSome", "taint", "manual"], ["", "URL", true, "init(dataRepresentation:relativeTo:isAbsolute:)", "", "", "Argument[dataRepresentation:]", "ReturnValue", "taint", "manual"], @@ -864,7 +864,7 @@ ["", "URL", true, "query(percentEncoded:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "URL", true, "resolvingSymlinksInPath()", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "URL", true, "resourceValues(forKeys:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], - ["", "URL", true, "resourceValues(forKeys:fromBookmarkData:)", "", "", "Argument[fromBookmarkData:]", "ReturnValue", "taint", "manual"], + ["", "URL.Type", true, "resourceValues(forKeys:fromBookmarkData:)", "", "", "Argument[fromBookmarkData:]", "ReturnValue", "taint", "manual"], ["", "URL", true, "setResourceValues(_:)", "", "", "Argument[0]", "Argument[self]", "taint", "manual"], ["", "URL", true, "setTemporaryResourceValue(_:forKey:)", "", "", "Argument[self,0]", "Argument[self]", "taint", "manual"], ["", "URL", true, "user(percentEncoded:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], @@ -879,7 +879,7 @@ ["", "NSData", true, "base64EncodedString(options:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "NSData", true, "base64Encoding()", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "NSData", true, "compressed(using:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], - ["", "NSData", true, "dataWithContentsOfMappedFile(_:)", "", "", "Argument[0]", "ReturnValue", "taint", "manual"], + ["", "NSData.Type", true, "dataWithContentsOfMappedFile(_:)", "", "", "Argument[0]", "ReturnValue", "taint", "manual"], ["", "NSData", true, "decompressed(using:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "NSData", true, "enumerateBytes(_:)", "", "", "Argument[self]", "Argument[0].Parameter[0]", "taint", "manual"], ["", "NSData", true, "getBytes(_:)", "", "", "Argument[self]", "Argument[0]", "taint", "manual"], @@ -903,9 +903,9 @@ ["", "NSString", true, "appending(_:)", "", "", "Argument[self,0]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "init(contentsOf:)", "", "", "Argument[contentsOf:]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "init(contentsOfFile:)", "", "", "Argument[contentsOfFile:]", "ReturnValue", "taint", "manual"], - ["", "NSString", true, "string(withContentsOf:)", "", "", "Argument[withContentsOf:]", "ReturnValue", "taint", "manual"], + ["", "NSString.Type", true, "string(withContentsOf:)", "", "", "Argument[withContentsOf:]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "init(contentsOf:encoding:)", "", "", "Argument[contentsOf:]", "ReturnValue", "taint", "manual"], - ["", "NSString", true, "string(withContentsOfFile:)", "", "", "Argument[withContentsOfFile:]", "ReturnValue", "taint", "manual"], + ["", "NSString.Type", true, "string(withContentsOfFile:)", "", "", "Argument[withContentsOfFile:]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "init(contentsOfFile:encoding:)", "", "", "Argument[contentsOfFile:]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "init(contentsOf:usedEncoding:)", "", "", "Argument[contentsOf:]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "init(contentsOfFile:usedEncoding:)", "", "", "Argument[contentsOfFile:]", "ReturnValue", "taint", "manual"], @@ -954,13 +954,13 @@ ["", "NSString", true, "init(format:locale:arguments:)", "", "", "Argument[format:]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "init(format:locale:arguments:)", "", "", "Argument[arguments:]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "init(utf8String:)", "", "", "Argument[utf8String:]", "ReturnValue", "taint", "manual"], - ["", "NSString", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "ReturnValue", "taint", "manual"], - ["", "NSString", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[1].CollectionElement", "ReturnValue", "taint", "manual"], + ["", "NSString.Type", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[0]", "ReturnValue", "taint", "manual"], + ["", "NSString.Type", true, "localizedStringWithFormat(_:_:)", "", "", "Argument[1].CollectionElement", "ReturnValue", "taint", "manual"], ["", "NSString", true, "lossyCString()", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "lowercased(with:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "padding(toLength:withPad:startingAt:)", "", "", "Argument[withPad:]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "padding(toLength:withPad:startingAt:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], - ["", "NSString", true, "path(withComponents:)", "", "", "Argument[withComponents:].CollectionElement", "ReturnValue", "taint", "manual"], + ["", "NSString.Type", true, "path(withComponents:)", "", "", "Argument[withComponents:].CollectionElement", "ReturnValue", "taint", "manual"], ["", "NSString", true, "propertyList()", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "propertyListFromStringsFileFormat()", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "replacingCharacters(in:with:)", "", "", "Argument[with:]", "ReturnValue", "taint", "manual"], @@ -970,9 +970,9 @@ ["", "NSString", true, "replacingOccurrences(of:with:options:range:)", "", "", "Argument[with:]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "replacingOccurrences(of:with:options:range:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "replacingPercentEscapes(using:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], - ["", "NSString", true, "string(withCString:)", "", "", "Argument[withCString:]", "ReturnValue", "taint", "manual"], - ["", "NSString", true, "string(withCString:length:)", "", "", "Argument[withCString:]", "ReturnValue", "taint", "manual"], - ["", "NSString", true, "stringEncoding(for:encodingOptions:convertedString:usedLossyCompression:)", "", "", "Argument[for:]", "Argument[convertedString:]", "taint", "manual"], + ["", "NSString.Type", true, "string(withCString:)", "", "", "Argument[withCString:]", "ReturnValue", "taint", "manual"], + ["", "NSString.Type", true, "string(withCString:length:)", "", "", "Argument[withCString:]", "ReturnValue", "taint", "manual"], + ["", "NSString.Type", true, "stringEncoding(for:encodingOptions:convertedString:usedLossyCompression:)", "", "", "Argument[for:]", "Argument[convertedString:]", "taint", "manual"], ["", "NSString", true, "strings(byAppendingPaths:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], ["", "NSString", true, "strings(byAppendingPaths:)", "", "", "Argument[byAppendingPaths:].CollectionElement", "ReturnValue", "taint", "manual"], ["", "NSString", true, "substring(from:)", "", "", "Argument[self]", "ReturnValue", "taint", "manual"], diff --git a/unified/ql/lib/unified.qll b/unified/ql/lib/unified.qll index 7aed5441f0f7..2c2da0796c58 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/test/library-tests/dataflow/metatypes.swift b/unified/ql/test/library-tests/dataflow/metatypes.swift new file mode 100644 index 000000000000..7f9ef74f3ad5 --- /dev/null +++ b/unified/ql/test/library-tests/dataflow/metatypes.swift @@ -0,0 +1,54 @@ +class MetaBase { + static func staticId(_ x: String) -> String { return x } + + class func classId(_ x: String) -> String { return x } + + static func staticSink(_ x: String) { + sink(x) // $ hasValueFlow=meta.static-sink + } + + func instanceId(_ x: String) -> String { return x } +} + +class MetaSub: MetaBase { + override class func classId(_ x: String) -> String { return "safe" } +} + +func testMetaTypeParameter(t: MetaBase.Type) { + sink(t.staticId(source("meta.1"))) // $ hasValueFlow=meta.1 + sink(t.classId(source("meta.2"))) // $ hasValueFlow=meta.2 + t.staticSink(source("meta.static-sink")) +} + +func testMetaTypeLocal() { + let t: MetaBase.Type = MetaBase.self + sink(t.staticId(source("meta.3"))) // $ hasValueFlow=meta.3 +} + +func testSelfExpr() { + let t = MetaBase.self + sink(t.staticId(source("meta.4"))) // $ hasValueFlow=meta.4 +} + +func testSubclassMetaType(t: MetaSub.Type) { + sink(t.staticId(source("meta.5"))) // $ hasValueFlow=meta.5 +} + +func testExplicitTypeReference() { + sink(MetaBase.staticId(source("meta.6"))) // $ hasValueFlow=meta.6 + sink(MetaBase.classId(source("meta.7"))) // $ hasValueFlow=meta.7 +} + +class MetaDispatchBase { + class func classSink(_ x: String) {} +} + +class MetaDispatchSub: MetaDispatchBase { + override class func classSink(_ x: String) { + sink(x) // $ hasValueFlow=meta.dispatch.1 + } +} + +func testClassMemberOverride(t: MetaDispatchSub.Type) { + t.classSink(source("meta.dispatch.1")) +} diff --git a/unified/ql/test/library-tests/dataflow/test.expected b/unified/ql/test/library-tests/dataflow/test.expected index a62cbc8e9020..a4a9d46dd432 100644 --- a/unified/ql/test/library-tests/dataflow/test.expected +++ b/unified/ql/test/library-tests/dataflow/test.expected @@ -428,6 +428,26 @@ edges | implicit-self.swift:85:9:85:14 | [incoming] ... .x | implicit-self.swift:85:9:85:12 | [post] self [x] | provenance | | | implicit-self.swift:85:29:85:43 | source(...) | implicit-self.swift:85:9:85:14 | [incoming] ... .x | provenance | | | implicit-self.swift:87:14:87:17 | self [x] | implicit-self.swift:87:14:87:19 | ... .x | provenance | | +| metatypes.swift:2:28:2:28 | x | metatypes.swift:2:58:2:58 | x | provenance | | +| metatypes.swift:4:26:4:26 | x | metatypes.swift:4:56:4:56 | x | provenance | | +| metatypes.swift:6:30:6:30 | x | metatypes.swift:7:14:7:14 | x | provenance | | +| metatypes.swift:18:21:18:36 | source(...) | metatypes.swift:2:28:2:28 | x | provenance | | +| metatypes.swift:18:21:18:36 | source(...) | metatypes.swift:18:10:18:37 | ... .staticId(...) | provenance | | +| metatypes.swift:19:20:19:35 | source(...) | metatypes.swift:4:26:4:26 | x | provenance | | +| metatypes.swift:19:20:19:35 | source(...) | metatypes.swift:19:10:19:36 | ... .classId(...) | provenance | | +| metatypes.swift:20:18:20:43 | source(...) | metatypes.swift:6:30:6:30 | x | provenance | | +| metatypes.swift:25:21:25:36 | source(...) | metatypes.swift:2:28:2:28 | x | provenance | | +| metatypes.swift:25:21:25:36 | source(...) | metatypes.swift:25:10:25:37 | ... .staticId(...) | provenance | | +| metatypes.swift:30:21:30:36 | source(...) | metatypes.swift:2:28:2:28 | x | provenance | | +| metatypes.swift:30:21:30:36 | source(...) | metatypes.swift:30:10:30:37 | ... .staticId(...) | provenance | | +| metatypes.swift:34:21:34:36 | source(...) | metatypes.swift:2:28:2:28 | x | provenance | | +| metatypes.swift:34:21:34:36 | source(...) | metatypes.swift:34:10:34:37 | ... .staticId(...) | provenance | | +| metatypes.swift:38:28:38:43 | source(...) | metatypes.swift:2:28:2:28 | x | provenance | | +| metatypes.swift:38:28:38:43 | source(...) | metatypes.swift:38:10:38:44 | ... .staticId(...) | provenance | | +| metatypes.swift:39:27:39:42 | source(...) | metatypes.swift:4:26:4:26 | x | provenance | | +| metatypes.swift:39:27:39:42 | source(...) | metatypes.swift:39:10:39:43 | ... .classId(...) | provenance | | +| metatypes.swift:47:37:47:37 | x | metatypes.swift:48:14:48:14 | x | provenance | | +| metatypes.swift:53:17:53:41 | source(...) | metatypes.swift:47:37:47:37 | x | provenance | | | modified-expressions.swift:2:9:2:16 | original | modified-expressions.swift:3:27:3:34 | original | provenance | | | modified-expressions.swift:2:20:2:35 | source(...) | modified-expressions.swift:2:9:2:16 | original | provenance | | | modified-expressions.swift:3:9:3:16 | borrowed | modified-expressions.swift:4:10:4:17 | borrowed | provenance | | @@ -1220,6 +1240,30 @@ nodes | implicit-self.swift:86:14:86:14 | x | semmle.label | x | | implicit-self.swift:87:14:87:17 | self [x] | semmle.label | self [x] | | implicit-self.swift:87:14:87:19 | ... .x | semmle.label | ... .x | +| metatypes.swift:2:28:2:28 | x | semmle.label | x | +| metatypes.swift:2:58:2:58 | x | semmle.label | x | +| metatypes.swift:4:26:4:26 | x | semmle.label | x | +| metatypes.swift:4:56:4:56 | x | semmle.label | x | +| metatypes.swift:6:30:6:30 | x | semmle.label | x | +| metatypes.swift:7:14:7:14 | x | semmle.label | x | +| metatypes.swift:18:10:18:37 | ... .staticId(...) | semmle.label | ... .staticId(...) | +| metatypes.swift:18:21:18:36 | source(...) | semmle.label | source(...) | +| metatypes.swift:19:10:19:36 | ... .classId(...) | semmle.label | ... .classId(...) | +| metatypes.swift:19:20:19:35 | source(...) | semmle.label | source(...) | +| metatypes.swift:20:18:20:43 | source(...) | semmle.label | source(...) | +| metatypes.swift:25:10:25:37 | ... .staticId(...) | semmle.label | ... .staticId(...) | +| metatypes.swift:25:21:25:36 | source(...) | semmle.label | source(...) | +| metatypes.swift:30:10:30:37 | ... .staticId(...) | semmle.label | ... .staticId(...) | +| metatypes.swift:30:21:30:36 | source(...) | semmle.label | source(...) | +| metatypes.swift:34:10:34:37 | ... .staticId(...) | semmle.label | ... .staticId(...) | +| metatypes.swift:34:21:34:36 | source(...) | semmle.label | source(...) | +| metatypes.swift:38:10:38:44 | ... .staticId(...) | semmle.label | ... .staticId(...) | +| metatypes.swift:38:28:38:43 | source(...) | semmle.label | source(...) | +| metatypes.swift:39:10:39:43 | ... .classId(...) | semmle.label | ... .classId(...) | +| metatypes.swift:39:27:39:42 | source(...) | semmle.label | source(...) | +| metatypes.swift:47:37:47:37 | x | semmle.label | x | +| metatypes.swift:48:14:48:14 | x | semmle.label | x | +| metatypes.swift:53:17:53:41 | source(...) | semmle.label | source(...) | | modified-expressions.swift:2:9:2:16 | original | semmle.label | original | | modified-expressions.swift:2:20:2:35 | source(...) | semmle.label | source(...) | | modified-expressions.swift:3:9:3:16 | borrowed | semmle.label | borrowed | @@ -1564,6 +1608,13 @@ subpaths | fields.swift:62:10:62:12 | sub [field] | fields.swift:53:15:53:19 | super [field] | fields.swift:53:15:53:25 | ... .field | fields.swift:62:10:62:18 | ... .field | | flow-summaries.swift:54:35:54:48 | source(...) | flow-summaries.swift:54:53:54:53 | y | flow-summaries.swift:54:65:54:65 | y | flow-summaries.swift:54:10:54:67 | ... .throughCallback(...) | | flow-summaries.swift:55:35:55:48 | source(...) | flow-summaries.swift:55:53:55:53 | y | flow-summaries.swift:55:65:55:71 | ... + ... | flow-summaries.swift:55:10:55:73 | ... .throughCallback(...) | +| metatypes.swift:18:21:18:36 | source(...) | metatypes.swift:2:28:2:28 | x | metatypes.swift:2:58:2:58 | x | metatypes.swift:18:10:18:37 | ... .staticId(...) | +| metatypes.swift:19:20:19:35 | source(...) | metatypes.swift:4:26:4:26 | x | metatypes.swift:4:56:4:56 | x | metatypes.swift:19:10:19:36 | ... .classId(...) | +| metatypes.swift:25:21:25:36 | source(...) | metatypes.swift:2:28:2:28 | x | metatypes.swift:2:58:2:58 | x | metatypes.swift:25:10:25:37 | ... .staticId(...) | +| metatypes.swift:30:21:30:36 | source(...) | metatypes.swift:2:28:2:28 | x | metatypes.swift:2:58:2:58 | x | metatypes.swift:30:10:30:37 | ... .staticId(...) | +| metatypes.swift:34:21:34:36 | source(...) | metatypes.swift:2:28:2:28 | x | metatypes.swift:2:58:2:58 | x | metatypes.swift:34:10:34:37 | ... .staticId(...) | +| metatypes.swift:38:28:38:43 | source(...) | metatypes.swift:2:28:2:28 | x | metatypes.swift:2:58:2:58 | x | metatypes.swift:38:10:38:44 | ... .staticId(...) | +| metatypes.swift:39:27:39:42 | source(...) | metatypes.swift:4:26:4:26 | x | metatypes.swift:4:56:4:56 | x | metatypes.swift:39:10:39:43 | ... .classId(...) | | subscripts.swift:21:12:21:25 | source(...) | subscripts.swift:15:19:15:21 | key | subscripts.swift:16:19:16:21 | key | subscripts.swift:21:10:21:26 | ... .subscript(...) | | subscripts.swift:45:5:45:15 | ... .subscript(...) | subscripts.swift:41:27:41:34 | newValue | subscripts.swift:41:19:41:23 | field | subscripts.swift:46:10:46:10 | c [field] | | subscripts.swift:45:5:45:15 | ... .subscript(...) | subscripts.swift:41:27:41:34 | newValue | subscripts.swift:41:19:41:23 | field | subscripts.swift:47:10:47:10 | c [field] | @@ -1720,6 +1771,15 @@ testFailures | implicit-self.swift:80:14:80:19 | ... .x | implicit-self.swift:78:24:78:38 | source(...) | implicit-self.swift:80:14:80:19 | ... .x | $@ | implicit-self.swift:78:24:78:38 | source(...) | source(...) | | implicit-self.swift:86:14:86:14 | x | implicit-self.swift:85:29:85:43 | source(...) | implicit-self.swift:86:14:86:14 | x | $@ | implicit-self.swift:85:29:85:43 | source(...) | source(...) | | implicit-self.swift:87:14:87:19 | ... .x | implicit-self.swift:85:29:85:43 | source(...) | implicit-self.swift:87:14:87:19 | ... .x | $@ | implicit-self.swift:85:29:85:43 | source(...) | source(...) | +| metatypes.swift:7:14:7:14 | x | metatypes.swift:20:18:20:43 | source(...) | metatypes.swift:7:14:7:14 | x | $@ | metatypes.swift:20:18:20:43 | source(...) | source(...) | +| metatypes.swift:18:10:18:37 | ... .staticId(...) | metatypes.swift:18:21:18:36 | source(...) | metatypes.swift:18:10:18:37 | ... .staticId(...) | $@ | metatypes.swift:18:21:18:36 | source(...) | source(...) | +| metatypes.swift:19:10:19:36 | ... .classId(...) | metatypes.swift:19:20:19:35 | source(...) | metatypes.swift:19:10:19:36 | ... .classId(...) | $@ | metatypes.swift:19:20:19:35 | source(...) | source(...) | +| metatypes.swift:25:10:25:37 | ... .staticId(...) | metatypes.swift:25:21:25:36 | source(...) | metatypes.swift:25:10:25:37 | ... .staticId(...) | $@ | metatypes.swift:25:21:25:36 | source(...) | source(...) | +| metatypes.swift:30:10:30:37 | ... .staticId(...) | metatypes.swift:30:21:30:36 | source(...) | metatypes.swift:30:10:30:37 | ... .staticId(...) | $@ | metatypes.swift:30:21:30:36 | source(...) | source(...) | +| metatypes.swift:34:10:34:37 | ... .staticId(...) | metatypes.swift:34:21:34:36 | source(...) | metatypes.swift:34:10:34:37 | ... .staticId(...) | $@ | metatypes.swift:34:21:34:36 | source(...) | source(...) | +| metatypes.swift:38:10:38:44 | ... .staticId(...) | metatypes.swift:38:28:38:43 | source(...) | metatypes.swift:38:10:38:44 | ... .staticId(...) | $@ | metatypes.swift:38:28:38:43 | source(...) | source(...) | +| metatypes.swift:39:10:39:43 | ... .classId(...) | metatypes.swift:39:27:39:42 | source(...) | metatypes.swift:39:10:39:43 | ... .classId(...) | $@ | metatypes.swift:39:27:39:42 | source(...) | source(...) | +| metatypes.swift:48:14:48:14 | x | metatypes.swift:53:17:53:41 | source(...) | metatypes.swift:48:14:48:14 | x | $@ | metatypes.swift:53:17:53:41 | source(...) | source(...) | | modified-expressions.swift:4:10:4:17 | borrowed | modified-expressions.swift:2:20:2:35 | source(...) | modified-expressions.swift:4:10:4:17 | borrowed | $@ | modified-expressions.swift:2:20:2:35 | source(...) | source(...) | | modified-expressions.swift:10:10:10:17 | consumed | modified-expressions.swift:8:20:8:36 | source(...) | modified-expressions.swift:10:10:10:17 | consumed | $@ | modified-expressions.swift:8:20:8:36 | source(...) | source(...) | | modified-expressions.swift:16:10:16:15 | copied | modified-expressions.swift:14:20:14:33 | source(...) | modified-expressions.swift:16:10:16:15 | copied | $@ | modified-expressions.swift:14:20:14:33 | source(...) | source(...) | diff --git a/unified/ql/test/library-tests/mad-builtins/test.expected b/unified/ql/test/library-tests/mad-builtins/test.expected index 5962215f217a..e10b91e24b46 100644 --- a/unified/ql/test/library-tests/mad-builtins/test.expected +++ b/unified/ql/test/library-tests/mad-builtins/test.expected @@ -4,5 +4,8 @@ isSink | test.swift:17:5:17:21 | ... .arguments | command-injection | | test.swift:18:5:18:23 | ... .arguments | command-injection | | test.swift:21:5:21:26 | ... .arguments | command-injection | +| test.swift:26:9:26:18 | launchPath | command-injection | +| test.swift:27:9:27:17 | arguments | command-injection | +| test.swift:28:9:28:17 | [post] arguments | command-injection | isSource | test.swift:12:9:12:22 | ... .text | local | diff --git a/unified/ql/test/library-tests/mad-builtins/test.swift b/unified/ql/test/library-tests/mad-builtins/test.swift index cd23768e7149..d6a539381399 100644 --- a/unified/ql/test/library-tests/mad-builtins/test.swift +++ b/unified/ql/test/library-tests/mad-builtins/test.swift @@ -23,8 +23,8 @@ func testPropertiesWithoutStubs( extension Process { func testImplicitSelfSink(string: String) { - launchPath = string // $ MISSING: isSink=command-injection - arguments = [string] // $ MISSING: isSink=command-injection - arguments.append(string) // $ MISSING: isSink=command-injection + launchPath = string // $ isSink=command-injection + arguments = [string] // $ isSink=command-injection + arguments.append(string) // $ isSink=command-injection } } diff --git a/unified/ql/test/library-tests/mad-static-members/test.expected b/unified/ql/test/library-tests/mad-static-members/test.expected new file mode 100644 index 000000000000..04f436057c31 --- /dev/null +++ b/unified/ql/test/library-tests/mad-static-members/test.expected @@ -0,0 +1,50 @@ +baseMetaType +| test.swift:4:9:4:23 | ... .init | StaticTest.Type | +| test.swift:5:9:5:31 | ... .staticMethod | StaticTest.Type | +| test.swift:6:9:6:29 | ... .staticProp | StaticTest.Type | +| test.swift:7:9:7:25 | ... .Nested | StaticTest.Type | +| test.swift:7:9:7:42 | ... .nestedStaticProp | StaticTest.Nested.Type | +| test.swift:9:9:9:33 | ... .instanceMethod | StaticTest.Type | +| test.swift:10:9:10:31 | ... .instanceProp | StaticTest.Type | +| test.swift:11:9:11:30 | ... .unknownProp | StaticTest.Type | +| test.swift:21:13:21:22 | staticProp | StaticTestSub.Type | +| test.swift:25:13:25:22 | staticProp | StaticTestSub.Type | +| test.swift:31:9:31:34 | ... .staticMethod | StaticTestSub.Type | +| test.swift:32:9:32:32 | ... .staticProp | StaticTestSub.Type | +| test.swift:33:9:33:26 | ... .init | StaticTestSub.Type | +| test.swift:34:9:34:34 | ... .instanceProp | StaticTestSub.Type | +| test.swift:45:13:45:22 | staticProp | StaticTest.Type | +| test.swift:49:13:49:22 | staticProp | StaticTest.Type | +| test.swift:50:13:50:24 | staticMethod | StaticTest.Type | +| test.swift:60:13:60:23 | staticField | DeclaredType.Type | +| test.swift:69:9:69:32 | ... .staticField | DeclaredType.Type | +instanceMember +| StaticTest | init | +| StaticTest | instanceMethod | +| StaticTest | instanceProp | +| StaticTestSub | init | +| StaticTestSub | instanceMethod | +| StaticTestSub | instanceProp | +staticMember +| test.swift:5:9:5:31 | ... .staticMethod | StaticTest.Type.staticMethod | +| test.swift:6:9:6:29 | ... .staticProp | StaticTest.Type.staticProp | +| test.swift:7:9:7:42 | ... .nestedStaticProp | StaticTest.Nested.Type.nestedStaticProp | +| test.swift:21:13:21:22 | staticProp | StaticTest.Type.staticProp | +| test.swift:25:13:25:22 | staticProp | StaticTest.Type.staticProp | +| test.swift:31:9:31:34 | ... .staticMethod | StaticTest.Type.staticMethod | +| test.swift:32:9:32:32 | ... .staticProp | StaticTest.Type.staticProp | +| test.swift:38:5:38:9 | NSLog | .NSLog | +| test.swift:45:13:45:22 | staticProp | StaticTest.Type.staticProp | +| test.swift:49:13:49:22 | staticProp | StaticTest.Type.staticProp | +| test.swift:50:13:50:24 | staticMethod | StaticTest.Type.staticMethod | +unqualified +| test.swift:20:13:20:24 | instanceProp | StaticTest.instanceProp | +| test.swift:21:13:21:22 | staticProp | StaticTest.Type.staticProp | +| test.swift:25:13:25:22 | staticProp | StaticTest.Type.staticProp | +| test.swift:26:13:26:24 | instanceProp | StaticTest.instanceProp | +| test.swift:43:13:43:24 | instanceProp | StaticTest.instanceProp | +| test.swift:44:13:44:26 | instanceMethod | StaticTest.instanceMethod | +| test.swift:45:13:45:22 | staticProp | StaticTest.Type.staticProp | +| test.swift:49:13:49:22 | staticProp | StaticTest.Type.staticProp | +| test.swift:50:13:50:24 | staticMethod | StaticTest.Type.staticMethod | +| test.swift:51:13:51:24 | instanceProp | StaticTest.instanceProp | diff --git a/unified/ql/test/library-tests/mad-static-members/test.ext.json b/unified/ql/test/library-tests/mad-static-members/test.ext.json new file mode 100644 index 000000000000..6c0cd86f8012 --- /dev/null +++ b/unified/ql/test/library-tests/mad-static-members/test.ext.json @@ -0,0 +1,19 @@ +{ + "extensions": [ + { + "addsTo": { + "pack": "codeql/unified-all", + "extensible": "legacySourceModel" + }, + "data": [ + // namespace, type, subtypes, name, signature, ext, output, kind, provenance + ["", "StaticTest", true, "init(x:)", "", "", "ReturnValue", "test", "manual"], + ["", "StaticTest.Type", true, "staticMethod(_:)", "", "", "ReturnValue", "test", "manual"], + ["", "StaticTest", true, "instanceMethod(_:)", "", "", "ReturnValue", "test", "manual"], + ["", "StaticTest.Type", true, "staticProp", "", "", "", "test", "manual"], + ["", "StaticTest", true, "instanceProp", "", "", "", "test", "manual"], + ["", "StaticTest.Nested.Type", true, "nestedStaticProp", "", "", "", "test", "manual"] + ] + } + ] +} diff --git a/unified/ql/test/library-tests/mad-static-members/test.ql b/unified/ql/test/library-tests/mad-static-members/test.ql new file mode 100644 index 000000000000..6e86affeacaf --- /dev/null +++ b/unified/ql/test/library-tests/mad-static-members/test.ql @@ -0,0 +1,43 @@ +private import unified +private import codeql.unified.internal.StaticNameBinding as N +private import codeql.unified.internal.mad.LegacyMaD as MaD +private import codeql.unified.internal.typeinference.TypeInference as T +private import codeql.unified.internal.typeinference.Type as Types + +query predicate staticMember(AstNode ref, string member) { + exists(MaD::MemberSelector selector | + N::trackMemberSelector(selector) = N::getNodeFromRef(ref) and + exists(ref.getFile().getRelativePath()) and + member = selector.getTypeString() + "." + selector.getName() + ) +} + +query predicate instanceMember(string type, string member) { + exists(N::NamespaceNode namespace, MaD::TypeSelector typeSelector, N::NameBindingNode node | + namespace.isTypeSelector(typeSelector) and + not typeSelector.isMetaType() and + node = namespace.getMember(member) and + node.isMemberSelector(_) and + type = typeSelector and + type.matches("StaticTest%") + ) + or + exists(N::NamespaceNode namespace, ClassLikeDeclaration cls, N::NameBindingNode node | + namespace.isInstanceMemberNamespace(cls) and + node = namespace.getMember(member) and + node.isMemberSelector(_) and + type = cls.getName() + ) +} + +query predicate unqualified(UnqualifiedMemberAccess access, string member) { + exists(MaD::MemberSelector selector | + access.getTargetNode().isMemberSelector(selector) and + member = selector.getTypeString() + "." + selector.getName() + ) +} + +query predicate baseMetaType(MemberAccess access, string type) { + type = T::inferBaseType(access).(Types::MetaType).toString() and + exists(access.getFile().getRelativePath()) +} diff --git a/unified/ql/test/library-tests/mad-static-members/test.qlref b/unified/ql/test/library-tests/mad-static-members/test.qlref new file mode 100644 index 000000000000..ab6773f15f90 --- /dev/null +++ b/unified/ql/test/library-tests/mad-static-members/test.qlref @@ -0,0 +1,2 @@ +query: test.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/unified/ql/test/library-tests/mad-static-members/test.swift b/unified/ql/test/library-tests/mad-static-members/test.swift new file mode 100644 index 000000000000..e05983e874fa --- /dev/null +++ b/unified/ql/test/library-tests/mad-static-members/test.swift @@ -0,0 +1,71 @@ +// `StaticTest` and `StaticTest.Nested` are not declared in the test codebase; they are only known from the models. + +func testStaticMembers(obj: StaticTest) { + _ = StaticTest.init(x: 1) // $ baseMetaType=StaticTest.Type // not a static member: constructors are not members of the meta type + _ = StaticTest.staticMethod(1) // $ baseMetaType=StaticTest.Type staticMember=StaticTest.Type.staticMethod + _ = StaticTest.staticProp // $ baseMetaType=StaticTest.Type staticMember=StaticTest.Type.staticProp + _ = StaticTest.Nested.nestedStaticProp // $ baseMetaType=StaticTest.Nested.Type baseMetaType=StaticTest.Type staticMember=StaticTest.Nested.Type.nestedStaticProp + + _ = StaticTest.instanceMethod(1) // $ baseMetaType=StaticTest.Type // not a static member + _ = StaticTest.instanceProp // $ baseMetaType=StaticTest.Type // not a static member + _ = StaticTest.unknownProp // $ baseMetaType=StaticTest.Type // not in a model + + // Accesses through an instance are not resolved by name binding + _ = obj.staticMethod(1) + _ = obj.staticProp +} + +class StaticTestSub: StaticTest { + func testInstanceContextInSubclass() { + _ = instanceProp // $ unqualified=StaticTest.instanceProp + _ = staticProp // $ baseMetaType=StaticTestSub.Type staticMember=StaticTest.Type.staticProp SPURIOUS: unqualified=StaticTest.Type.staticProp // not accessible from an instance context + } + + static func testStaticContextInSubclass() { + _ = staticProp // $ baseMetaType=StaticTestSub.Type unqualified=StaticTest.Type.staticProp staticMember=StaticTest.Type.staticProp + _ = instanceProp // $ SPURIOUS: unqualified=StaticTest.instanceProp // not accessible from a static context + } +} + +func testInheritedStaticMembers() { + _ = StaticTestSub.staticMethod(1) // $ baseMetaType=StaticTestSub.Type staticMember=StaticTest.Type.staticMethod + _ = StaticTestSub.staticProp // $ baseMetaType=StaticTestSub.Type staticMember=StaticTest.Type.staticProp + _ = StaticTestSub.init(x: 1) // $ baseMetaType=StaticTestSub.Type // not a static member: constructors are not members of the meta type + _ = StaticTestSub.instanceProp // $ baseMetaType=StaticTestSub.Type // not a static member +} + +func testTopLevelFunctions(string: String) { + NSLog(string) // $ staticMember=.NSLog +} + +extension StaticTest { + func testInstanceContextInExtension() { + _ = instanceProp // $ unqualified=StaticTest.instanceProp + _ = instanceMethod(1) // $ unqualified=StaticTest.instanceMethod + _ = staticProp // $ baseMetaType=StaticTest.Type staticMember=StaticTest.Type.staticProp SPURIOUS: unqualified=StaticTest.Type.staticProp // not accessible from an instance context + } + + static func testStaticContextInExtension() { + _ = staticProp // $ baseMetaType=StaticTest.Type unqualified=StaticTest.Type.staticProp staticMember=StaticTest.Type.staticProp + _ = staticMethod(1) // $ baseMetaType=StaticTest.Type unqualified=StaticTest.Type.staticMethod staticMember=StaticTest.Type.staticMethod + _ = instanceProp // $ SPURIOUS: unqualified=StaticTest.instanceProp // not accessible from a static context + } +} + +class DeclaredType { + static var staticField = 0 + var instanceField = 0 + + static func staticContext() { + _ = staticField // $ baseMetaType=DeclaredType.Type + } + + func instanceContext() { + _ = instanceField + } +} + +func testDeclaredType(obj: DeclaredType) { + _ = DeclaredType.staticField // $ baseMetaType=DeclaredType.Type + _ = obj.instanceField +} diff --git a/unified/ql/test/library-tests/mad/test.expected b/unified/ql/test/library-tests/mad/test.expected index a1f7d8989cdc..903142cde669 100644 --- a/unified/ql/test/library-tests/mad/test.expected +++ b/unified/ql/test/library-tests/mad/test.expected @@ -34,6 +34,10 @@ isSink | test.swift:218:9:218:14 | string | shorthand-sink | | test.swift:239:13:239:13 | 0 | subscript-getter-sink | | test.swift:240:5:240:10 | ... .subscript(...) | subscript-setter-sink | +| test.swift:245:22:245:27 | string | instance-sink | +| test.swift:246:27:246:32 | string | static-sink | +| test.swift:249:29:249:34 | string | instance-sink | +| test.swift:250:20:250:25 | string | static-sink | isSource | test.swift:4:5:4:27 | String(...) | remote | | test.swift:5:5:5:44 | String(...) | remote | @@ -51,3 +55,11 @@ isSource | test.swift:209:5:213:5 | [self param] func ShorthandTestSub.sourceParams | shorthand-source | | test.swift:210:11:210:11 | x | shorthand-source | | test.swift:232:13:232:13 | v | subscript-setter-source | +| test.swift:254:9:254:24 | ... .instanceProp | instance-prop-source | +| test.swift:255:9:255:29 | ... .staticProp | static-prop-source | +| test.swift:263:13:263:24 | instanceProp | instance-prop-source | +| test.swift:267:13:267:22 | staticProp | static-prop-source | +| test.swift:273:13:273:24 | instanceProp | instance-prop-source | +| test.swift:277:13:277:22 | staticProp | static-prop-source | +| test.swift:282:9:282:32 | ... .staticProp | static-prop-source | +| test.swift:283:9:283:24 | ... .instanceProp | instance-prop-source | diff --git a/unified/ql/test/library-tests/mad/test.ext.json b/unified/ql/test/library-tests/mad/test.ext.json index 8f540964d08c..af0142928d07 100644 --- a/unified/ql/test/library-tests/mad/test.ext.json +++ b/unified/ql/test/library-tests/mad/test.ext.json @@ -8,7 +8,9 @@ "data": [ // namespace, type, subtypes, name, signature, ext, output, kind, provenance ["", "ShorthandTest", true, "sourceParams(_:)", "", "", "Parameter[self,0]", "shorthand-source", "manual"], - ["", "SubscriptTest", true, "subscript(_:#newValue:)", "", "", "Parameter[#newValue:]", "subscript-setter-source", "manual"] + ["", "SubscriptTest", true, "subscript(_:#newValue:)", "", "", "Parameter[#newValue:]", "subscript-setter-source", "manual"], + ["", "StaticTest", true, "instanceProp", "", "", "", "instance-prop-source", "manual"], + ["", "StaticTest.Type", true, "staticProp", "", "", "", "static-prop-source", "manual"] ] }, { @@ -20,7 +22,9 @@ // namespace, type, subtypes, name, signature, ext, input, kind, provenance ["", "ShorthandTest", true, "sinkArgs(_:)", "", "", "Argument[self,0]", "shorthand-sink", "manual"], ["", "SubscriptTest", true, "subscript(_:)", "", "", "Argument[0]", "subscript-getter-sink", "manual"], - ["", "SubscriptTest", true, "subscript(_:#newValue:)", "", "", "Argument[#newValue:]", "subscript-setter-sink", "manual"] + ["", "SubscriptTest", true, "subscript(_:#newValue:)", "", "", "Argument[#newValue:]", "subscript-setter-sink", "manual"], + ["", "StaticTest", true, "instanceSink(_:)", "", "", "Argument[0]", "instance-sink", "manual"], + ["", "StaticTest.Type", true, "staticSink(_:)", "", "", "Argument[0]", "static-sink", "manual"] ] } ] diff --git a/unified/ql/test/library-tests/mad/test.swift b/unified/ql/test/library-tests/mad/test.swift index 5aa1d78ba1bd..1a28dbbd765c 100644 --- a/unified/ql/test/library-tests/mad/test.swift +++ b/unified/ql/test/library-tests/mad/test.swift @@ -239,3 +239,48 @@ func testSubscripts(obj: SubscriptTest, string: String) { _ = obj[0] // $ isSink=subscript-getter-sink obj[0] = string // $ isSink=subscript-setter-sink } + +// `StaticTest` is not declared in the test codebase; it is only known from the models. +func testStaticAndInstanceMethods(obj: StaticTest, string: String) { + obj.instanceSink(string) // $ isSink=instance-sink + StaticTest.staticSink(string) // $ isSink=static-sink + + // Models for the meta type (`StaticTest.Type`) are not yet distinguished from instance members for method calls + StaticTest.instanceSink(string) // $ SPURIOUS: isSink=instance-sink + obj.staticSink(string) // $ SPURIOUS: isSink=static-sink +} + +func testStaticAndInstanceProperties(obj: StaticTest) { + _ = obj.instanceProp // $ isSource=instance-prop-source + _ = StaticTest.staticProp // $ isSource=static-prop-source + + _ = StaticTest.instanceProp // not a source: instance property accessed on the type + _ = obj.staticProp // not a source: static property accessed on an instance +} + +class StaticTestSub: StaticTest { + func testInstanceContext() { + _ = instanceProp // $ isSource=instance-prop-source + } + + static func testStaticContext() { + _ = staticProp // $ isSource=static-prop-source + } +} + +extension StaticTest { + func testInstanceContextInExtension() { + _ = instanceProp // $ isSource=instance-prop-source + } + + static func testStaticContextInExtension() { + _ = staticProp // $ isSource=static-prop-source + } +} + +func testStaticPropertiesOnSubclass(obj: StaticTestSub) { + _ = StaticTestSub.staticProp // $ isSource=static-prop-source + _ = obj.instanceProp // $ isSource=instance-prop-source + _ = StaticTestSub.instanceProp // not a source: instance property accessed on the type + _ = obj.staticProp // not a source: static property accessed on an instance +} diff --git a/unified/ql/test/library-tests/static-name-binding/test.ql b/unified/ql/test/library-tests/static-name-binding/test.ql index bcbb86b6ead9..57659bc52c67 100644 --- a/unified/ql/test/library-tests/static-name-binding/test.ql +++ b/unified/ql/test/library-tests/static-name-binding/test.ql @@ -23,5 +23,5 @@ import MakeTest query predicate unqualifiedMemberAccess( UnqualifiedMemberAccess uma, NameBinding target, ClassLikeDeclaration accessingClass ) { - unqualifiedMemberAccess(uma, _, target, accessingClass) + unqualifiedMemberAccess(uma, _, any(MemberTargetNode n | n.isIdentifier(target)), accessingClass) } diff --git a/unified/ql/test/library-tests/type-inference/metatypes.swift b/unified/ql/test/library-tests/type-inference/metatypes.swift new file mode 100644 index 000000000000..b4dc86d73297 --- /dev/null +++ b/unified/ql/test/library-tests/type-inference/metatypes.swift @@ -0,0 +1,26 @@ +class Meta { + static func create() -> Meta { return Meta() } // $ target=Meta.init + class func name() -> String { return "Meta" } + func instanceMethod() -> Int { return 0 } +} + +class MetaChild: Meta { + override class func name() -> String { return "MetaChild" } +} + +func metaTypeParameter(t: Meta.Type, c: MetaChild.Type) { + let m = t.create() // $ type=m:Meta target=Meta.create + let n = t.name() // $ type=n:String target=Meta.name + let cn = c.name() // $ type=cn:String target=MetaChild.name + let cm = c.create() // $ type=cm:Meta target=Meta.create +} + +func metaTypeFromSelf() { + let t = Meta.self // $ type=t:Meta.Type + let m = t.create() // $ type=m:Meta target=Meta.create +} + +func metaTypeAnnotation() { + let t: Meta.Type = Meta.self // $ type=t:Meta.Type + let n = t.name() // $ type=n:String target=Meta.name +} diff --git a/unified/ql/test/library-tests/type-inference/type-inference.expected b/unified/ql/test/library-tests/type-inference/type-inference.expected index f6249e7ac62c..45902e83f6de 100644 --- a/unified/ql/test/library-tests/type-inference/type-inference.expected +++ b/unified/ql/test/library-tests/type-inference/type-inference.expected @@ -559,6 +559,14 @@ inferCertainType | key_paths.swift:204:7:204:9 | arr | | {EXTERNAL LOCATION} | Array | | key_paths.swift:204:13:204:24 | ArrayLiteral | | {EXTERNAL LOCATION} | Array | | key_paths.swift:205:15:205:17 | arr | | {EXTERNAL LOCATION} | Array | +| metatypes.swift:11:24:11:24 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:11:38:11:38 | c | | metatypes.swift:7:1:9:1 | MetaChild.Type | +| metatypes.swift:12:13:12:13 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:13:13:13:13 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:14:14:14:14 | c | | metatypes.swift:7:1:9:1 | MetaChild.Type | +| metatypes.swift:15:14:15:14 | c | | metatypes.swift:7:1:9:1 | MetaChild.Type | +| metatypes.swift:24:9:24:9 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:25:13:25:13 | t | | metatypes.swift:1:1:5:1 | Meta.Type | | nested_types.swift:2:9:2:17 | baseValue | | nested_types.swift:1:12:1:16 | TBase | | nested_types.swift:4:10:4:18 | baseValue | | nested_types.swift:1:12:1:16 | TBase | | nested_types.swift:5:9:5:12 | self | | nested_types.swift:1:1:11:1 | Base | @@ -3549,6 +3557,39 @@ inferType | lub.swift:14:15:14:15 | 3 | | {EXTERNAL LOCATION} | Int | | lub.swift:14:19:14:19 | b | | lub.swift:5:1:7:1 | B | | lub.swift:14:23:14:23 | c | | lub.swift:9:1:9:13 | C | +| metatypes.swift:2:34:2:50 | Block | | metatypes.swift:1:1:5:1 | Meta | +| metatypes.swift:2:43:2:46 | Meta | | metatypes.swift:1:1:5:1 | Meta | +| metatypes.swift:2:43:2:48 | Meta(...) | | metatypes.swift:1:1:5:1 | Meta | +| metatypes.swift:3:33:3:49 | Block | | {EXTERNAL LOCATION} | String | +| metatypes.swift:3:42:3:47 | "Meta" | | {EXTERNAL LOCATION} | String | +| metatypes.swift:4:34:4:45 | Block | | {EXTERNAL LOCATION} | Int | +| metatypes.swift:4:43:4:43 | 0 | | {EXTERNAL LOCATION} | Int | +| metatypes.swift:8:42:8:63 | Block | | {EXTERNAL LOCATION} | String | +| metatypes.swift:8:51:8:61 | "MetaChild" | | {EXTERNAL LOCATION} | String | +| metatypes.swift:11:24:11:24 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:11:38:11:38 | c | | metatypes.swift:7:1:9:1 | MetaChild.Type | +| metatypes.swift:12:9:12:9 | m | | metatypes.swift:1:1:5:1 | Meta | +| metatypes.swift:12:13:12:13 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:12:13:12:22 | ... .create(...) | | metatypes.swift:1:1:5:1 | Meta | +| metatypes.swift:13:9:13:9 | n | | {EXTERNAL LOCATION} | String | +| metatypes.swift:13:13:13:13 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:13:13:13:20 | ... .name(...) | | {EXTERNAL LOCATION} | String | +| metatypes.swift:14:9:14:10 | cn | | {EXTERNAL LOCATION} | String | +| metatypes.swift:14:14:14:14 | c | | metatypes.swift:7:1:9:1 | MetaChild.Type | +| metatypes.swift:14:14:14:21 | ... .name(...) | | {EXTERNAL LOCATION} | String | +| metatypes.swift:15:9:15:10 | cm | | metatypes.swift:1:1:5:1 | Meta | +| metatypes.swift:15:14:15:14 | c | | metatypes.swift:7:1:9:1 | MetaChild.Type | +| metatypes.swift:15:14:15:23 | ... .create(...) | | metatypes.swift:1:1:5:1 | Meta | +| metatypes.swift:19:9:19:9 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:19:13:19:21 | ... .self | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:20:9:20:9 | m | | metatypes.swift:1:1:5:1 | Meta | +| metatypes.swift:20:13:20:13 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:20:13:20:22 | ... .create(...) | | metatypes.swift:1:1:5:1 | Meta | +| metatypes.swift:24:9:24:9 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:24:24:24:32 | ... .self | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:25:9:25:9 | n | | {EXTERNAL LOCATION} | String | +| metatypes.swift:25:13:25:13 | t | | metatypes.swift:1:1:5:1 | Meta.Type | +| metatypes.swift:25:13:25:20 | ... .name(...) | | {EXTERNAL LOCATION} | String | | modified-expressions.swift:2:7:2:11 | value | | {EXTERNAL LOCATION} | Int | | modified-expressions.swift:2:15:2:16 | 42 | | {EXTERNAL LOCATION} | Int | | modified-expressions.swift:3:7:3:14 | borrowed | | {EXTERNAL LOCATION} | Int |