Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Basic query for C and C++ code

Learn to write and run a simple CodeQL query using Visual Studio Code with the CodeQL extension.

For information about installing the CodeQL extension for Visual Studio code, see “Installing CodeQL for Visual Studio Code.”

About the query

The query we’re going to run performs a basic search of the code forif statements that are redundant, in the sense that they have an empty then branch. For example, code such as:

if(error){}

Finding a CodeQL database to experiment with

Before you start writing queries for C/C++ code, you need a CodeQL database to run them against. The simplest way to do this is to download a database for a repository that uses C/C++ directly from GitHub.com.

  1. In Visual Studio Code, click theQL iconIcon for the CodeQL extension. in the left sidebar to display the CodeQL extension.

  2. ClickFrom GitHub or the GitHub logoIcon for the CodeQL extension option to download a CodeQL database from GitHub. at the top of the CodeQL extension to open an entry field.

  3. Copy the URL for the repository into the field and press the keyboardEnter key. For example,https://github.com/protocolbuffers/protobuf.

  4. Optionally, if the repository has more than one CodeQL database available, selectcpp to download the database created from the C/C++ code.

Information about the download progress for the database is shown in the bottom right corner of Visual Studio Code. When the download is complete, the database is shown with a check mark in theDatabases section of the CodeQL extension (see screenshot below).

Running a quick query

The CodeQL extension for Visual Studio Code adds severalCodeQL: commands to the command palette includingQuick Query, which you can use to run a query without any set up.

  1. From the command palette in Visual Studio Code, selectCodeQL: Quick Query.

  2. After a moment, a new tabquick-query.ql is opened, ready for you to write a query for your currently selected CodeQL database (here acpp database). If you are prompted to reload your workspace as a multi-folder workspace to allow Quick queries, accept or create a new workspace using the starter workflow.

    image-quick-query

  1. In the quick query tab, deleteselect"" and paste the following query beneath the import statementimportcpp.

    fromIfStmtifstmt,BlockStmtblockwhereifstmt.getThen()=blockandblock.getNumStmt()=0selectifstmt,"This 'if' statement is redundant."
  1. Save the query in its default location (a temporary “Quick Queries” directory under the workspace forGitHub.vscode-codeql/quick-queries).

  2. Right-click in the query tab and selectCodeQL: Run Query on Selected Database. (Alternatively, run the command from the Command Palette.)

    The query will take a few moments to return results. When the query completes, the results are displayed in a CodeQL Query Results view, next to the main editor view.

    The query results are listed in two columns, corresponding to the expressions in theselect clause of the query. The first column corresponds to the expressionifstmt and is linked to the location in the source code of the project whereifstmt occurs. The second column is the alert message.

../../_images/basic-cpp-query-results-1.png

If any matching code is found, click a link in theifstmt column to open the file and highlight the matchingif statement.

../../_images/basic-cpp-query-results-2.png

Note

If you want to move your experimental query somewhere more permanent, you need to move the wholeQuickQueries directory. The directory is a CodeQL pack with aqlpack.yml file that defines the content as queries for C/C++ CodeQL databases. For more information about CodeQL packs, see “Managing CodeQL query packs and library packs.”

About the query structure

After the initialimport statement, this simple query comprises three parts that serve similar purposes to the FROM, WHERE, and SELECT parts of an SQL query.

Query part

Purpose

Details

importcpp

Imports the standard CodeQL libraries for C/C++.

Every query begins with one or moreimport statements.

fromIfStmtifstmt,BlockStmtblock

Defines the variables for the query.Declarations are of the form:<type><variablename>

We use:

  • anIfStmt variable forif statements

  • aBlockStmt variable for the statement block

whereifstmt.getThen()=blockandblock.getNumStmt()=0

Defines a condition on the variables.

ifstmt.getThen()=block relates the two variables. The block must be thethen branch of theif statement.

block.getNumStmt()=0 states that the block must be empty (that is, it contains no statements).

selectifstmt,"This'if'statementisredundant."

Defines what to report for each match.

select statements for queries that are used to find instances of poor coding practice are always in the form:select<programelement>,"<alertmessage>"

Reports the resultingif statement with a string that explains the problem.

Extend the query

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.

Remove false positive results

Browsing the results of our basic query shows that it could be improved. Among the results you are likely to find examples ofif statements with anelse branch, where an emptythen branch does serve a purpose. For example:

if(...){...}elseif(!strcmp(option,"-verbose")){// nothing to do - handled earlier}else{error("unrecognized option");}

In this case, identifying theif statement with the emptythen branch as redundant is a false positive. One solution to this is to modify the query to ignore emptythen branches if theif statement has anelse branch.

To excludeif statements that have anelse branch:

  1. Edit your query and extend thewhere clause to include the following extra condition:

    andnotifstmt.hasElse()

    Thewhere clause is now:

    whereifstmt.getThen()=blockandblock.getNumStmt()=0andnotifstmt.hasElse()
  2. Re-run the query.

    There are now fewer results becauseif statements with anelse branch are no longer reported.

Further reading


[8]ページ先頭

©2009-2025 Movatter.jp