### CodeQL Select Clause Example Source: https://codeql.github.com/docs/ql-language-reference/queries An example demonstrating the usage of a select clause in CodeQL, including variable declarations, a logical formula, and selecting computed expressions with aliasing and string concatenation. ```ql from int x, int y where x = 3 and y in [0 .. 2] select x, y, x * y as product, "product: " + product ``` -------------------------------- ### CodeQL Variable Declaration Syntax Example Source: https://codeql.github.com/docs/ql-language-reference/variables Illustrates the syntax for declaring variables with specific types in CodeQL. It shows examples of declaring integer, SsaDefinitionNode, and LocalScopeVariable types. ```codeql int i SsaDefinitionNode node LocalScopeVariable lsv ``` -------------------------------- ### CodeQL 'forall' Quantifier Example Source: https://codeql.github.com/docs/ql-language-reference/formulas Shows an example of the 'forall' quantifier in CodeQL. It checks if all integers 'i' that are instances of 'OneTwoThree' are also less than 5, demonstrating universal quantification over a subset of values. ```codeql forall(int i | i instanceof OneTwoThree | i < 5) ``` -------------------------------- ### CodeQL Type Signature Examples Source: https://codeql.github.com/docs/ql-language-reference/signatures Demonstrates type signatures for module parameters. The first example declares a type signature 'ExtendsInt' that must extend the 'int' type. The second example declares 'CanBePrinted' requiring a 'toString()' member predicate. ```codeql signature class ExtendsInt extends int; ``` ```codeql signature class CanBePrinted { string toString(); } ``` -------------------------------- ### Define an Explicit CodeQL Module Source: https://codeql.github.com/docs/ql-language-reference/modules Demonstrates the simplest way to define an explicit module in CodeQL, named 'Example', which contains a class 'OneTwoThree'. Module names can be any valid identifier. ```CodeQL module Example { class OneTwoThree extends int { OneTwoThree() { this = 1 or this = 2 or this = 3 } } } ``` -------------------------------- ### CodeQL Rank Aggregate Example Source: https://codeql.github.com/docs/ql-language-reference/expressions Demonstrates the usage of the 'rank' aggregate function in CodeQL to find a specific ranked value within a range. Rank indices start at 1. ```CodeQL rank[4](int i | i = [5 .. 15] | i) ``` -------------------------------- ### CodeQL 'exists' Quantifier Example Source: https://codeql.github.com/docs/ql-language-reference/formulas Provides an example of the 'exists' quantifier in CodeQL. It declares an integer variable 'i' and checks if any value of 'i' is of type 'OneTwoThree', demonstrating existential quantification over a type check. ```codeql exists(int i | i instanceof OneTwoThree) ``` -------------------------------- ### QL: Select JS files under 200 lines using and Source: https://codeql.github.com/docs/ql-language-reference/formulas The `and` keyword combines two formulas, requiring both to be true. This example selects JavaScript files (`.js` extension) that also contain fewer than 200 lines of code. ```ql from File f where f.getExtension() = "js" and f.getNumberOfLinesOfCode() < 200 select f ``` -------------------------------- ### QL pragma[inline_late] and bindingset Example Source: https://codeql.github.com/docs/ql-language-reference/annotations Demonstrates the use of `pragma[inline_late]` with `bindingset` to influence join ordering for performance. This forces the optimizer to consider specific binding sets when evaluating predicates, potentially leading to more efficient query execution. ```ql bindingset[x] pragma[inline_late] predicate p(int x) { x in [0..100000000] } predicate q(int x) { x in [0..10000] } from int x where p(x) and q(x) select x ``` -------------------------------- ### QL Bindingset Annotation Example Source: https://codeql.github.com/docs/ql-language-reference/predicates Shows how to use the `bindingset` annotation in QL to explicitly define a binding set for a predicate, allowing infinite predicates to be used in contexts where their arguments are restricted to a finite set. ```ql bindingset[i] int multiplyBy4(int i) { result = i * 4 } from int i where i in [1 .. 10] select multiplyBy4(i) ``` -------------------------------- ### QL pragma[noopt] Rewriting Example Source: https://codeql.github.com/docs/ql-language-reference/annotations Illustrates how to rewrite predicates when using `pragma[noopt]`. This pragma prevents the QL optimizer from reordering conjuncts or creating intermediary conjuncts, requiring explicit and ordered definitions for complex logic. ```ql class Small extends int { Small() { this in [1 .. 10] } Small getSucc() { result = this + 1} } predicate p(int i) { i.(Small).getSucc() = 2 } predicate q(Small s) { s.getSucc().getSucc() = 3 } ``` ```ql pragma[noopt] predicate p(int i) { exists(Small s | s = i and s.getSucc() = 2) } pragma[noopt] predicate q(Small s) { exists(Small succ | succ = s.getSucc() and succ.getSucc() = 3 ) } ``` -------------------------------- ### CodeQL Prefix Cast Example Source: https://codeql.github.com/docs/ql-language-reference/expressions This example shows the equivalent of the postfix cast using a prefix cast `(Type)expression` in CodeQL. It achieves the same goal of restricting an expression's type to access specific member predicates, demonstrated here by selecting Java classes with a 'List' supertype. ```CodeQL import java from Type t where ((Class)t).getASupertype().hasName("List") select t ``` -------------------------------- ### Reflexive Transitive Closure Operator '*' in QL Source: https://codeql.github.com/docs/ql-language-reference/recursion Illustrates the reflexive transitive closure operator '*' in QL, which applies a predicate zero or more times. This is useful for including the starting element itself in the closure, such as finding all ancestors including the person. ```ql // Explicit definition: Person getAnAncestor2() { result = this or result = this.getAParent().getAnAncestor2() } // Equivalent using '*': // p.getAParent*() ``` -------------------------------- ### QL Multiple Bindingset Annotations Example Source: https://codeql.github.com/docs/ql-language-reference/predicates Demonstrates specifying multiple independent binding sets for a QL predicate using multiple `bindingset` annotations. This allows for more flexible control over predicate finiteness based on different argument bindings. ```ql bindingset[x] bindingset[y] predicate plusOne(int x, int y) { x + 1 = y } from int x, int y where y = 42 and plusOne(x, y) select x, y ``` -------------------------------- ### Calling Member Predicates on Class Instances in QL Source: https://codeql.github.com/docs/ql-language-reference/types Demonstrates how to call member predicates on instances of a QL class. The example shows casting an integer to a specific class to access its member predicates and chaining them with built-in functions. ```ql 1.(OneTwoThree).getAString() 1.(OneTwoThree).getAString().toUpperCase() ``` -------------------------------- ### QL: Define all expressions using any() Source: https://codeql.github.com/docs/ql-language-reference/formulas The built-in predicate `any()` always holds true and can be used to define a set containing all possible values. This example defines a predicate `allExpressions()` that returns all expressions. ```ql Expr allExpressions() { any() } ``` -------------------------------- ### QL Bindingset for Multiple Arguments Example Source: https://codeql.github.com/docs/ql-language-reference/predicates Illustrates using `bindingset` with multiple arguments in QL to define a predicate that takes several inputs and ensures finiteness when all specified arguments are bound. This is useful for predicates with multiple input parameters. ```ql bindingset[str, len] string truncate(string str, int len) { if str.length() > len then result = str.prefix(len) else result = str } ``` -------------------------------- ### CodeQL Sum Aggregate with Multiple Variables Source: https://codeql.github.com/docs/ql-language-reference/expressions Shows an example of the 'sum' aggregate function with multiple input variables. It calculates the sum of 'i' based on conditions involving string character indices. ```CodeQL select sum(int i, int j | exists(string s | s = "hello".charAt(i)) and exists(string s | s = "world!".charAt(j)) | i) ``` -------------------------------- ### CodeQL Postfix Cast Example Source: https://codeql.github.com/docs/ql-language-reference/expressions This example demonstrates how to use a postfix cast `.(Type)` in CodeQL to restrict an expression's type, enabling access to member predicates defined for the more specific type. It selects Java classes with a direct supertype named 'List'. ```CodeQL import java from Type t where t.(Class).getASupertype().hasName("List") select t ``` -------------------------------- ### QL: Select files that are not HTML using not Source: https://codeql.github.com/docs/ql-language-reference/formulas The `not` keyword negates a formula. This example demonstrates selecting files that do not have an HTML file type by applying `not` to the `isHtml()` predicate. ```ql from File f where not f.getFileType().isHtml() select f ``` -------------------------------- ### QL 'any' Expression Syntax and Examples Source: https://codeql.github.com/docs/ql-language-reference/expressions Explains the syntax and purpose of the 'any' expression in QL, which denotes values of a specific form satisfying a condition. It can introduce temporary variables, restrict values via a formula, and return an expression or the variables themselves. ```ql any( | | ) ``` ```ql any(File f) ``` ```ql any(Element e | e.getName()) ``` ```ql any(int i | i = [0 .. 3]) ``` ```ql any(int i | i = [0 .. 3] | i * i) ``` -------------------------------- ### QL Aggregation: Simplified Count Example Source: https://codeql.github.com/docs/ql-language-reference/expressions Demonstrates how to simplify the count aggregation by omitting variable declarations and formula parts. This is useful for counting occurrences of a substring. ```QL count("hello".indexOf("l")) ``` -------------------------------- ### CodeQL Predicate Signature Example Source: https://codeql.github.com/docs/ql-language-reference/signatures Defines a predicate signature for a module parameter that expects a predicate with an integer result and two integer arguments. It uses structural typing for substitution. ```codeql signature int operator(int lhs, int rhs); ``` -------------------------------- ### QL Recursive Descendant Calculation Example Source: https://codeql.github.com/docs/ql-language-reference/about-the-ql-language Demonstrates how to define recursive predicates in QL to find all descendants of a person and count them using aggregates. This showcases QL's declarative nature and ability to handle complex queries concisely. ```ql Person getADescendant(Person p) { result = p.getAChild() or result = getADescendant(p.getAChild()) } int getNumberOfDescendants(Person p) { result = count(getADescendant(p)) } ``` -------------------------------- ### QL Super Expression Example Source: https://codeql.github.com/docs/ql-language-reference/expressions Demonstrates how to use super expressions in QL to resolve ambiguity when a class inherits multiple definitions of the same predicate from different supertypes. It shows class C inheriting from A and B, and using `B.super.getANumber()` to specify which definition to use. ```QL class A extends int { A() { this = 1 } int getANumber() { result = 2 } } class B extends int { B() { this = 1 } int getANumber() { result = 3 } } class C extends A, B { // Need to define `int getANumber()`; otherwise it would be ambiguous override int getANumber() { result = B.super.getANumber() } } from C c select c, c.getANumber() ``` -------------------------------- ### QL Example: Monotonic vs. Default Aggregates Source: https://codeql.github.com/docs/ql-language-reference/expressions This QL code defines helper predicates for people, fruits, and prices, and then compares a non-monotonic sum aggregate with a monotonic sum aggregate. The comparison shows how different handling of multiple or missing results affects the output. ```ql string getPerson() { result = "Alice" or result = "Bob" or result = "Charles" or result = "Diane" } string getFruit(string p) { p = "Alice" and result = "Orange" or p = "Alice" and result = "Apple" or p = "Bob" and result = "Apple" or p = "Charles" and result = "Apple" or p = "Charles" and result = "Banana" } int getPrice(string f) { f = "Apple" and result = 100 or f = "Orange" and result = 100 or f = "Orange" and result = 1 } predicate nonmono(string p, int cost) { p = getPerson() and cost = sum(string f | f = getFruit(p) | getPrice(f)) } language[monotonicAggregates] predicate mono(string p, int cost) { p = getPerson() and cost = sum(string f | f = getFruit(p) | getPrice(f)) } from string variant, string person, int cost where variant = "default" and nonmono(person, cost) or variant = "monotonic" and mono(person, cost) select variant, person, cost order by variant, person ``` -------------------------------- ### Transitive Closure (One or More) Operator '+' in QL Source: https://codeql.github.com/docs/ql-language-reference/recursion Demonstrates the transitive closure operator '+' in QL for expressing a predicate that applies one or more times. This is an alternative to explicitly defining recursive predicates for relationships like ancestry. ```ql // Explicit definition: Person getAnAncestor() { result = this.getAParent() or result = this.getAParent().getAnAncestor() } // Equivalent using '+': // p.getAParent+() ``` -------------------------------- ### Defining an Abstract Class in QL Source: https://codeql.github.com/docs/ql-language-reference/types Shows the definition of an abstract class in QL. Abstract classes are used to group multiple existing classes under a common name and can have member predicates defined on them. This example defines a base `SqlExpr` class. ```ql abstract class SqlExpr extends Expr { ... } ``` -------------------------------- ### QL: Define an empty set of integers using none() Source: https://codeql.github.com/docs/ql-language-reference/formulas The built-in predicate `none()` always holds false and can be used to define an empty set. This example defines a predicate `emptySet()` that returns an empty set of integers. ```ql int emptySet() { none() } ``` -------------------------------- ### Alternative Valid Monotonic Recursion in CodeQL Source: https://codeql.github.com/docs/ql-language-reference/recursion This CodeQL snippet offers an alternative, equivalent definition for the 'isExtinct' predicate using a 'forall' quantifier. This demonstrates another way to structure valid monotonic recursion where the recursive call is effectively under an even number of negations, ensuring a solvable fixed-point. ```CodeQL forall(Person descendant | descendant.getAParent+() = this | descendant.isExtinct() ) ``` -------------------------------- ### Define an Explicit Module within a Library Source: https://codeql.github.com/docs/ql-language-reference/modules Provides an example of defining an explicit module named 'M' nested within an existing library file (e.g., 'OneTwoThreeLib.qll'). This inner module defines a class 'OneTwo' that extends 'OneTwoThree'. Explicit modules can contain various QL elements but not select clauses. ```CodeQL module M { class OneTwo extends OneTwoThree { OneTwo() { this = 1 or this = 2 } } } ``` -------------------------------- ### Count Integers from 0 to 100 using Recursion in QL Source: https://codeql.github.com/docs/ql-language-reference/recursion This QL query demonstrates direct recursion to list all integers from 0 to 100. It defines a predicate that starts with 0 and recursively adds 1 until it reaches 100. ```ql int getANumber() { result = 0 or result <= 100 and result = getANumber() + 1 } select getANumber() ``` -------------------------------- ### Invalid Direct Recursion (Empty Base Case) in QL Source: https://codeql.github.com/docs/ql-language-reference/recursion Shows an example of an invalid recursive definition in QL that lacks a base case, leading to an empty recursive call. The QL compiler typically flags this as an error because no new values can be generated. ```ql // Invalid definition: Person getAnAncestor() { result = this.getAParent().getAnAncestor() } // Correct definition requires a base case: // Person getAnAncestor() { // result = this.getAParent() // or // result = this.getAParent().getAnAncestor() // } ``` -------------------------------- ### Parameterized Module Instantiation with Type Dependencies in QL Source: https://codeql.github.com/docs/ql-language-reference/modules Demonstrates instantiation of a parameterized module 'M' with a type parameter 'T'. It defines a new type 'A' within 'M' and shows how instantiating 'M' with different types (int vs. float) can lead to type incompatibility errors if not handled carefully, illustrating the strictness of QL's type system. ```ql bindingset[this] signature class TSig; module M { newtype A = B() or C() } string foo(M::A a) { ... } select foo(M::B()), // valid: repeated identical instantiation of M does not duplicate A, B, C foo(M::B()) // ERROR: M::B is not compatible with M::A ``` -------------------------------- ### Deprecated Annotation Example in QL Source: https://codeql.github.com/docs/ql-language-reference/annotations The `deprecated` annotation marks outdated names scheduled for removal. It typically includes a QLDoc comment with the recommended alternative. This example shows a deprecated class `DataFlowNode`. ```ql /** * DEPRECATED: Use `DataFlow::Node` instead. * * An expression or function/class declaration, * viewed as a node in a data flow graph. */ deprecated class DataFlowNode extends @dataflownode { ... } ``` -------------------------------- ### Final Annotation Example in QL Source: https://codeql.github.com/docs/ql-language-reference/annotations The `final` annotation prevents overriding or extension of classes, type aliases, member predicates, or fields. This example demonstrates a `final` predicate `hasName` within a `class Element`. ```ql class Element { string getName() { result = ... } final predicate hasName(string name) { name = this.getName() } } ``` -------------------------------- ### Importing a Qualified Module Reference in CodeQL Source: https://codeql.github.com/docs/ql-language-reference/name-resolution Illustrates importing a library module using a qualified reference in CodeQL. The compiler resolves 'examples.security.MyLibrary' by looking for 'examples/security/MyLibrary.qll' relative to the query file, the query directory, or library path entries. ```codeql import examples.security.MyLibrary ``` -------------------------------- ### CodeQL Don't-care Expression Example Source: https://codeql.github.com/docs/ql-language-reference/expressions This example illustrates the use of the don't-care expression `_` in CodeQL, which represents any value and is useful when a predicate argument is not relevant. It selects all characters from the string 'hello' by using `_` with the `charAt` predicate. ```CodeQL from string s where s = "hello".charAt(_) select s ``` -------------------------------- ### CodeQL Unique Aggregate Example Source: https://codeql.github.com/docs/ql-language-reference/expressions Illustrates the 'unique' aggregate function, which returns a value only if it's unique across all possible assignments to aggregation variables. This example selects positive integers or their absolute values. ```CodeQL from int x where x in [-5 .. 5] and x != 0 select unique(int y | y = x or y = x.abs() | y) ``` -------------------------------- ### Instantiate Parameterized Module in QL Source: https://codeql.github.com/docs/ql-language-reference/modules Instantiates the parameterized module 'M' with the 'increment/1' predicate for both parameters, creating a module 'IncrementTwice'. This module contains a predicate that effectively adds 2 to its input. It then selects the result of applying this predicate to 40. ```ql bindingset[result] bindingset[x] int increment(int x) { result = x + 1 } module IncrementTwice = M; select IncrementTwice::applyBoth(40) // 42 ``` -------------------------------- ### Import Statement Syntax in QL Source: https://codeql.github.com/docs/ql-language-reference/modules Shows the syntax for importing modules in QL. It includes basic import, aliased import using 'as', and mentions optional annotations like 'private' and 'deprecated' for controlling re-exporting and deprecation warnings. ```ql import as import ``` -------------------------------- ### CodeQL Query Predicate Usage Source: https://codeql.github.com/docs/ql-language-reference/queries Demonstrates how a defined query predicate, 'getProduct', can be called within a class definition in CodeQL to constrain the 'this' instance. ```ql class MultipleOfThree extends int { MultipleOfThree() { this = getProduct(_, _) } } ``` -------------------------------- ### QL Class with Overlapping Subtypes Source: https://codeql.github.com/docs/ql-language-reference/types Illustrates defining another subclass of `OneTwoThree` that overlaps with `OneTwo`. This example shows how multiple, potentially overlapping, overridden definitions of a predicate are handled by QL queries. ```ql class TwoThree extends OneTwoThree { TwoThree() { this = 2 or this = 3 } override string getAString() { result = "Two or three: " + this.toString() } } ``` -------------------------------- ### Group Values into Sets with InternSets Module Source: https://codeql.github.com/docs/ql-language-reference/modules This example shows how to use the `InternSets` module to group values based on keys. The module is parameterized by key and value types, and a relation `getAValue`. It exports a `getSet` relation that maps keys to sets of associated values. The `Set` type has a `contains` predicate to check for membership. If multiple keys map to the same set of values, they will be related to the same set object. ```ql int getAValue(int key) { key = 1 and result = 1 or key = 2 and (result = 1 or result = 2) or key = 3 and result = 1 or key = 4 and result = 2 } module Sets = QlBuiltins::InternSets; from int k, int v where Sets::getSet(k).contains(v) select k, v ``` -------------------------------- ### Recursive Monotonic Aggregates in QL Source: https://codeql.github.com/docs/ql-language-reference/expressions Demonstrates how monotonic aggregates can be used recursively in QL. The recursive call must be within the expression part, not the range. This example calculates the depth of a node in a graph from the leaves. ```ql language[monotonicAggregates] int depth(Node n) { if not exists(n.getAChild()) then result = 0 else result = 1 + max(Node child | child = n.getAChild() | depth(child)) } ``` -------------------------------- ### Identify Keys Mapping to Identical Sets using InternSets Source: https://codeql.github.com/docs/ql-language-reference/modules This QL snippet leverages the `InternSets` module to find pairs of keys that are associated with identical sets of values. By comparing the results of `Sets::getSet(k1)` and `Sets::getSet(k2)`, the query identifies keys that point to the same set object, indicating they share the same associated values. ```ql from int k1, int k2 where Sets::getSet(k1) = Sets::getSet(k2) select k1, k2 ``` -------------------------------- ### CodeQL QL: Type Check Formula Source: https://codeql.github.com/docs/ql-language-reference/formulas A formula to check if an expression belongs to a specific type in QL. It uses the 'instanceof' operator, for example, 'x instanceof Person' checks if variable 'x' is of type 'Person'. ```CodeQL x instanceof Person ``` -------------------------------- ### QL Expressions with Variables Source: https://codeql.github.com/docs/ql-language-reference/variables Demonstrates QL expressions, illustrating scenarios with no variables, bound variables, and free variables. Bound variables are placeholders, while free variables' values impact the expression's result. ```ql "hello".indexOf("l") min(float f | f in [-3 .. 3]) (i + 7) * 3 x.sqrt() ``` -------------------------------- ### QL: Declare Bar as instanceof Foo Source: https://codeql.github.com/docs/ql-language-reference/types Demonstrates declaring a class 'Bar' as an 'instanceof' 'Foo'. This means 'Bar' inherits properties and methods from 'Foo' without directly extending it. It shows how to access superclass methods using 'super' within the specialized class. ```ql class Foo extends int { Foo() { this in [1 .. 10] } string fooMethod() { result = "foo" } } class Bar instanceof Foo { string toString() { result = super.fooMethod() } } ``` -------------------------------- ### Define Parameterized Module in QL Source: https://codeql.github.com/docs/ql-language-reference/modules Defines a parameterized module 'M' in QL that accepts two predicate parameters, 'first' and 'second'. It then defines a new predicate 'applyBoth' that applies these predicates sequentially. This demonstrates QL's approach to generic programming. ```ql module M { bindingset[x] int applyBoth(int x) { result = second(first(x)) } } ``` -------------------------------- ### QL: Select SmallInt that are odd or multiples of 4 using implies Source: https://codeql.github.com/docs/ql-language-reference/formulas The `implies` keyword creates an implication formula, equivalent to `(not A) or B`. This example selects integers from 1 to 10 (`SmallInt`) that are either odd or a multiple of 4. ```ql class SmallInt extends int { SmallInt() { this = [1 .. 10] } } from SmallInt x where x % 2 = 0 implies x % 4 = 0 select x ``` -------------------------------- ### CodeQL Select Clause Syntax Source: https://codeql.github.com/docs/ql-language-reference/queries Defines the basic structure of a select clause in a CodeQL query module. The 'from' and 'where' clauses are optional. The 'select' clause defines the output columns. ```ql from /* ... variable declarations ... */ where /* ... logical formula ... */ select /* ... expressions ... */ ``` -------------------------------- ### QL: Determine class visibility using if...then...else Source: https://codeql.github.com/docs/ql-language-reference/formulas The `if...then...else` construct creates a conditional formula. This example defines a `visibility` predicate that returns 'public' if a class is public, and 'private' otherwise. ```ql string visibility(Class c){ if c.isPublic() then result = "public" else result = "private" } ``` -------------------------------- ### Define a CodeQL Library Module Source: https://codeql.github.com/docs/ql-language-reference/modules Illustrates a CodeQL library module defined in a '.qll' file. This module, named 'OneTwoThreeLib', contains a class 'OneTwoThree' for integer values 1, 2, or 3. Library modules can be imported into other files. ```CodeQL class OneTwoThree extends int { OneTwoThree() { this = 1 or this = 2 or this = 3 } } ```