Skip to content

Commit a79f09f

Browse files
committed
Add basic query for Go
1 parent 8e8c43a commit a79f09f

File tree

2 files changed

+153
-1
lines changed

2 files changed

+153
-1
lines changed
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
Basic query for Go code
2+
=======================
3+
4+
Learn to write and run a simple CodeQL query using LGTM.
5+
6+
About the query
7+
---------------
8+
9+
The query we're going to run searches the code for methods defined on value types that modify their receiver by writing a field:
10+
11+
.. code-block:: go
12+
13+
func (s MyStruct) valueMethod() { s.f = 1 } // method on value
14+
15+
This is problematic because the receiver argument is passed by value, not by reference. Consequently, valueMethod is called with a copy of the receiver object, so any changes it makes to the receiver will be invisible to the caller. To prevent this, the method should be defined on a pointer instead:
16+
17+
.. code-block:: go
18+
19+
func (s *MyStruct) pointerMethod() { s.f = 1 } // method on pointer
20+
21+
For further information on using methods on values or pointers in Go, see the `Go FAQ <https://golang.org/doc/faq#methods_on_values_or_pointers>`__.
22+
23+
Running the query
24+
-----------------
25+
26+
#. In the main search box on LGTM.com, search for the project you want to query. For tips, see `Searching <https://lgtm.com/help/lgtm/searching>`__.
27+
28+
#. Click the project in the search results.
29+
30+
#. Click **Query this project**.
31+
32+
This opens the query console. (For information about using this, see `Using the query console <https://lgtm.com/help/lgtm/using-query-console>`__.)
33+
34+
.. pull-quote::
35+
36+
Note
37+
38+
Alternatively, you can go straight to the query console by clicking **Query console** (at the top of any page), selecting **Go** from the **Language** drop-down list, then choosing one or more projects to query from those displayed in the **Project** drop-down list.
39+
40+
#. Copy the following query into the text box in the query console:
41+
42+
.. code-block:: ql
43+
44+
import go
45+
46+
from Method m, Variable recv, Write w, Field f
47+
where
48+
recv = m.getReceiver() and
49+
w.writesField(recv.getARead(), f, _) and
50+
not recv.getType() instanceof PointerType
51+
select w, "This update to " + f + " has no effect, because " + recv + " is not a pointer."
52+
53+
LGTM checks whether your query compiles and, if all is well, the **Run** button changes to green to indicate that you can go ahead and run the query.
54+
55+
#. Click **Run**.
56+
57+
The name of the project you are querying, and the ID of the most recently analyzed commit to the project, are listed below the query box. To the right of this is an icon that indicates the progress of the query operation:
58+
59+
.. image:: ../../images/query-progress.png
60+
:align: center
61+
62+
.. pull-quote::
63+
64+
Note
65+
66+
Your query is always run against the most recently analyzed commit to the selected project.
67+
68+
The query will take a few moments to return results. When the query completes, the results are displayed below the project name. The query results are listed in two columns, corresponding to the two expressions in the ``select`` clause of the query. The first column corresponds to ``w``, which is the location in the source code where the receiver ``recv`` is modified. The second column is the alert message.
69+
70+
➤ `Example query results <https://lgtm.com/query/6221190009056970603/>`__
71+
72+
.. pull-quote::
73+
74+
Note
75+
76+
An ellipsis (…) at the bottom of the table indicates that the entire list is not displayed—click it to show more results.
77+
78+
#. If any matching code is found, click a link in the ``w`` column to view it in the code viewer.
79+
80+
The matching ``w`` is highlighted with a yellow background in the code viewer. If any code in the file also matches a query from the standard query library for that language, you will see a red alert message at the appropriate point within the code.
81+
82+
About the query structure
83+
~~~~~~~~~~~~~~~~~~~~~~~~~
84+
85+
After the initial ``import`` statement, this simple query comprises three parts that serve similar purposes to the FROM, WHERE, and SELECT parts of an SQL query.
86+
87+
+---------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+
88+
| Query part | Purpose | Details |
89+
+===============================================================+===================================================================================================================+======================================================================================================================================+
90+
| ``import go`` | Imports the standard CodeQL libraries for Go. | Every query begins with one or more ``import`` statements. |
91+
+---------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+
92+
| ``from Method m, Variable recv, Write w, Field f`` | Defines the variables for the query. | We declare: |
93+
| | Declarations are of the form: | |
94+
| | ``<type> <variable name>`` | - ``m`` as a variable for all methods |
95+
| | | - a ``recv`` variable, which is the receiver of ``m`` |
96+
| | | - ``w`` as the location in the code where the receiver is modified |
97+
| | | - ``f`` as the field that is written when ``m`` is called |
98+
+---------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+
99+
| ``where recv = m.getReceiver() and | Defines a condition on the variables. | ``recv = m.getReceiver()`` states that ``recv`` must be the receiver variable of ``m``. |
100+
| w.writesField(recv.getARead(), f, _) and | | |
101+
| not recv.getType() instanceof PointerType`` | | ``w.writesField(recv.getARead(), f, _)`` states that ``w`` must be a location in the code where field ``f`` of ``recv`` is modified. |
102+
| | | We use a `'don't-care' expression <https://help.semmle.com/QL/ql-handbook/expressions.html#don-t-care-expressions>`__ _ for the |
103+
| | | value that is written to ``f``—the actual value doesn't matter in this query. |
104+
| | | |
105+
| | | ``not recv.getType() instanceof PointerType`` states that ``m`` is not a pointer method. |
106+
+---------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+
107+
| ``select w, "This update to " + f + | Defines what to report for each match. | Reports ``w`` with a message that explains the potential problem. |
108+
| " has no effect, because " + recv + " is not a pointer."`` | | |
109+
| | ``select`` statements for queries that are used to find instances of poor coding practice are always in the form: | |
110+
| | ``select <program element>, "<alert message>"`` | |
111+
+---------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+
112+
113+
Extend the query
114+
----------------
115+
116+
Query writing is an inherently iterative process. You write a simple query and then, when you run it, you discover examples that you had not previously considered, or opportunities for improvement.
117+
118+
Remove false positive results
119+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
120+
121+
Among the results generated by the first iteration of this query, you can find cases where a value method is called but the receiver variable is returned. In such cases, the change to the receiver is not invisible to the caller, so a pointer method is not required. These are false positive results and you can improve the query by adding an extra condition to remove them.
122+
123+
To exclude these values:
124+
125+
#. Extend the where clause to include the following extra condition:
126+
127+
.. code-block:: ql
128+
129+
not exists(ReturnStmt ret | ret.getExpr() = recv.getARead().asExpr())
130+
131+
The ``where`` clause is now:
132+
133+
.. code-block:: ql
134+
135+
where e.isPure() and
136+
recv = m.getReceiver() and
137+
w.writesField(recv.getARead(), f, _) and
138+
not recv.getType() instanceof PointerType and
139+
not exists(ReturnStmt ret | ret.getExpr() = recv.getARead().asExpr())
140+
141+
#. Click **Run**.
142+
143+
There are now fewer results because value methods that return their receiver variable are no longer reported.
144+
145+
➤ `See this in the query console <https://lgtm.com/query/9110448975027954322/>`__
146+
147+
Further reading
148+
---------------
149+
150+
.. include:: ../../reusables/go-further-reading.rst
151+
.. include:: ../../reusables/codeql-ref-tools-further-reading.rst

docs/language/learn-ql/go/ql-for-go.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@ Experiment and learn how to write effective and efficient queries for CodeQL dat
66
.. toctree::
77
:hidden:
88

9+
basic-query-go
910
introduce-libraries-go
1011
ast-class-reference
1112
library-modeling-go
1213

13-
- `Basic Go query <https://lgtm.com/help/lgtm/console/ql-go-basic-example>`__: Learn to write and run a simple CodeQL query using LGTM.
14+
- :doc:`Basic query for Go code <basic-query-go>`: Learn to write and run a simple CodeQL query using LGTM.
1415

1516
- :doc:`CodeQL library for Go <introduce-libraries-go>`: When you're analyzing a Go program, you can make use of the large collection of classes in the CodeQL library for Go.
1617

0 commit comments

Comments
 (0)