Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
9830cc0
Implement MISRA-C++23 Preprocesser package rules 19-0-4, 19-1-1, and …
MichaelRFairhurst Apr 29, 2025
2095d1d
Fix Preprocessor.json, for defined in if directive
MichaelRFairhurst Apr 29, 2025
ef9d96b
Fix package errors
MichaelRFairhurst Apr 29, 2025
a49c0d1
s/maintanability/maintainability
MichaelRFairhurst Apr 29, 2025
ea173e5
Regenerate query metadata
MichaelRFairhurst Apr 29, 2025
a31e047
Format additional files
MichaelRFairhurst Apr 29, 2025
a653a58
Implement package preprocessor2
MichaelRFairhurst May 14, 2025
a020c0f
Update query metadata
MichaelRFairhurst May 14, 2025
b47ec45
Merge branch 'main' into michaelrfairhurst/implement-package-preproce…
lcartey Jun 9, 2025
36eee16
Update to use features from codeql-qtil
MichaelRFairhurst Aug 24, 2025
39ef003
Update to use features from codeql-qtil
MichaelRFairhurst Aug 24, 2025
5da3a00
Merge remote-tracking branch 'origin/main' into michaelrfairhurst/imp…
MichaelRFairhurst Aug 24, 2025
3b3b3be
Merge branch 'michaelrfairhurst/implement-package-preprocessor' into …
MichaelRFairhurst Aug 24, 2025
eb5453b
Update to 0.0.3 which has fixes for codeql/util breaking change.
MichaelRFairhurst Aug 24, 2025
687783b
Merge branch 'michaelrfairhurst/implement-package-preprocessor' into …
MichaelRFairhurst Aug 24, 2025
5d22374
Merge remote-tracking branch 'origin/main' into michaelrfairhurst/imp…
MichaelRFairhurst Feb 6, 2026
3d578f0
Address feedback
MichaelRFairhurst Feb 10, 2026
a83e513
Merge branch 'main' into michaelrfairhurst/implement-package-preproce…
MichaelRFairhurst Feb 11, 2026
c808c96
Merge branch 'main' into michaelrfairhurst/implement-package-preproce…
MichaelRFairhurst Feb 25, 2026
8d537d6
Merge remote-tracking branch 'origin/michaelrfairhurst/implement-pack…
MichaelRFairhurst Feb 25, 2026
d1940ab
Merge remote-tracking branch 'origin/michaelrfairhurst/implement-pack…
MichaelRFairhurst Feb 25, 2026
98e2c71
Merge remote-tracking branch 'origin/main' into michaelrfairhurst/imp…
MichaelRFairhurst Feb 26, 2026
466bb1f
Merge remote-tracking branch 'origin/michaelrfairhurst/implement-pack…
MichaelRFairhurst Feb 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions cpp/common/src/codingstandards/cpp/Macro.qll
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,49 @@ class FunctionLikeMacro extends Macro {
exists(this.getBody().regexpFind("\\#?\\b" + parameter + "\\b", _, result))
)
}

/**
* Holds if the parameter is used in a way that may make it vulnerable to precedence issues.
*
* Typically, parameters are wrapped in parentheses to protect them from precedence issues, but
* that is not always possible.
*/
predicate parameterPrecedenceUnprotected(int index) {
// Check if the parameter is used in a way that requires parentheses
exists(string parameter | parameter = getParameter(index) |
// Finds any occurence of the parameter that is not preceded by, or followed by, either a
// parenthesis or the '#' token operator.
//
// Note the following cases:
// - "(x + 1)" is preceded by a parenthesis, but not followed by one, so SHOULD be matched.
// - "x # 1" is followed by "#" (though not preceded by #) and SHOULD be matched.
// - "(1 + x)" is followed by a parenthesis, but not preceded by one, so SHOULD be matched.
// - "1 # x" is preceded by "#" (though not followed by #) and SHOULD NOT be matched.
//
// So the regex is structured as follows:
// - paramMatch: Matches the parameter at a word boundary, with optional whitespace
// - notHashed: Finds parameters not used with a leading # operator.
// - The final regex finds cases of `notHashed` that are not preceded by a parenthesis,
// and cases of `notHashed` that are not followed by a parenthesis.
//
// Therefore, a parameter with parenthesis on both sides is not matched, a parameter with
// parenthesis missing on one or both sides is only matched if there is no leading or trailing
// ## operator.
exists(string noBeforeParen, string noAfterParen, string paramMatch, string notHashed |
// Not preceded by a parenthesis
noBeforeParen = "(?<!\\(\\s*)" and
// Not followed by a parenthesis
noAfterParen = "(?!\\s*\\))" and
// Parameter at word boundary in optional whitespace
paramMatch = "\\s*\\b" + parameter + "\\b\\s*" and
// A parameter is ##'d if it is preceded or followed by the # operator.
notHashed = "(?<!#)" + paramMatch and
// Parameter is used without a leading or trailing parenthesis, and without #.
getBody()
.regexpMatch(".*(" + noBeforeParen + notHashed + "|" + notHashed + noAfterParen + ").*")
)
)
}
}

newtype TMacroOperator =
Expand Down
2 changes: 1 addition & 1 deletion cpp/common/src/codingstandards/cpp/MatchingParenthesis.qll
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ module MatchingParenthesis<InputString Input> {
occurrence = prevOccurrence + 1
) else (
token = TNotParen() and
exists(inputStr.regexpFind("\\(|\\)", prevOccurrence + 1, endPos)) and
exists(inputStr.regexpFind("\\(|\\)|$", prevOccurrence + 1, endPos)) and
Copy link

Copilot AI May 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Including '$' in the regex "\\(|\\)|$" allows matching an empty string at end‐of‐input, which can lead to zero‐length matches and infinite loops. Consider matching only parentheses here and handling end‐of‐input separately.

Suggested change
exists(inputStr.regexpFind("\\(|\\)|$", prevOccurrence + 1, endPos)) and
exists(inputStr.regexpFind("\\(|\\)", prevOccurrence + 1, endPos)) and
(endPos < inputStr.length() or endPos = inputStr.length()) and

Copilot uses AI. Check for mistakes.
occurrence = prevOccurrence
)
)
Expand Down
95 changes: 95 additions & 0 deletions cpp/common/src/codingstandards/cpp/exclusions/cpp/Preprocessor.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//** THIS FILE IS AUTOGENERATED, DO NOT MODIFY DIRECTLY. **/
import cpp
import RuleMetadata
import codingstandards.cpp.exclusions.RuleMetadata

newtype PreprocessorQuery =
TUndefOfMacroNotDefinedInFileQuery() or
TInvalidTokenInDefinedOperatorQuery() or
TDefinedOperatorExpandedInIfDirectiveQuery() or
TNoValidIfdefGuardInHeaderQuery() or
TIncludeOutsideGuardQuery()

predicate isPreprocessorQueryMetadata(Query query, string queryId, string ruleId, string category) {
query =
// `Query` instance for the `undefOfMacroNotDefinedInFile` query
PreprocessorPackage::undefOfMacroNotDefinedInFileQuery() and
queryId =
// `@id` for the `undefOfMacroNotDefinedInFile` query
"cpp/misra/undef-of-macro-not-defined-in-file" and
ruleId = "RULE-19-0-4" and
category = "advisory"
or
query =
// `Query` instance for the `invalidTokenInDefinedOperator` query
PreprocessorPackage::invalidTokenInDefinedOperatorQuery() and
queryId =
// `@id` for the `invalidTokenInDefinedOperator` query
"cpp/misra/invalid-token-in-defined-operator" and
ruleId = "RULE-19-1-1" and
category = "required"
or
query =
// `Query` instance for the `definedOperatorExpandedInIfDirective` query
PreprocessorPackage::definedOperatorExpandedInIfDirectiveQuery() and
queryId =
// `@id` for the `definedOperatorExpandedInIfDirective` query
"cpp/misra/defined-operator-expanded-in-if-directive" and
ruleId = "RULE-19-1-1" and
category = "required"
or
query =
// `Query` instance for the `noValidIfdefGuardInHeader` query
PreprocessorPackage::noValidIfdefGuardInHeaderQuery() and
queryId =
// `@id` for the `noValidIfdefGuardInHeader` query
"cpp/misra/no-valid-ifdef-guard-in-header" and
ruleId = "RULE-19-2-1" and
category = "required"
or
query =
// `Query` instance for the `includeOutsideGuard` query
PreprocessorPackage::includeOutsideGuardQuery() and
queryId =
// `@id` for the `includeOutsideGuard` query
"cpp/misra/include-outside-guard" and
ruleId = "RULE-19-2-1" and
category = "required"
}

module PreprocessorPackage {
Query undefOfMacroNotDefinedInFileQuery() {
//autogenerate `Query` type
result =
// `Query` type for `undefOfMacroNotDefinedInFile` query
TQueryCPP(TPreprocessorPackageQuery(TUndefOfMacroNotDefinedInFileQuery()))
}

Query invalidTokenInDefinedOperatorQuery() {
//autogenerate `Query` type
result =
// `Query` type for `invalidTokenInDefinedOperator` query
TQueryCPP(TPreprocessorPackageQuery(TInvalidTokenInDefinedOperatorQuery()))
}

Query definedOperatorExpandedInIfDirectiveQuery() {
//autogenerate `Query` type
result =
// `Query` type for `definedOperatorExpandedInIfDirective` query
TQueryCPP(TPreprocessorPackageQuery(TDefinedOperatorExpandedInIfDirectiveQuery()))
}

Query noValidIfdefGuardInHeaderQuery() {
//autogenerate `Query` type
result =
// `Query` type for `noValidIfdefGuardInHeader` query
TQueryCPP(TPreprocessorPackageQuery(TNoValidIfdefGuardInHeaderQuery()))
}

Query includeOutsideGuardQuery() {
//autogenerate `Query` type
result =
// `Query` type for `includeOutsideGuard` query
TQueryCPP(TPreprocessorPackageQuery(TIncludeOutsideGuardQuery()))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//** THIS FILE IS AUTOGENERATED, DO NOT MODIFY DIRECTLY. **/
import cpp
import RuleMetadata
import codingstandards.cpp.exclusions.RuleMetadata

newtype Preprocessor2Query =
TInvalidIncludeDirectiveQuery() or
TUnparenthesizedMacroArgumentQuery() or
TDisallowedUseOfPragmaQuery()

predicate isPreprocessor2QueryMetadata(Query query, string queryId, string ruleId, string category) {
query =
// `Query` instance for the `invalidIncludeDirective` query
Preprocessor2Package::invalidIncludeDirectiveQuery() and
queryId =
// `@id` for the `invalidIncludeDirective` query
"cpp/misra/invalid-include-directive" and
ruleId = "RULE-19-2-2" and
category = "required"
or
query =
// `Query` instance for the `unparenthesizedMacroArgument` query
Preprocessor2Package::unparenthesizedMacroArgumentQuery() and
queryId =
// `@id` for the `unparenthesizedMacroArgument` query
"cpp/misra/unparenthesized-macro-argument" and
ruleId = "RULE-19-3-4" and
category = "required"
or
query =
// `Query` instance for the `disallowedUseOfPragma` query
Preprocessor2Package::disallowedUseOfPragmaQuery() and
queryId =
// `@id` for the `disallowedUseOfPragma` query
"cpp/misra/disallowed-use-of-pragma" and
ruleId = "RULE-19-6-1" and
category = "advisory"
}

module Preprocessor2Package {
Query invalidIncludeDirectiveQuery() {
//autogenerate `Query` type
result =
// `Query` type for `invalidIncludeDirective` query
TQueryCPP(TPreprocessor2PackageQuery(TInvalidIncludeDirectiveQuery()))
}

Query unparenthesizedMacroArgumentQuery() {
//autogenerate `Query` type
result =
// `Query` type for `unparenthesizedMacroArgument` query
TQueryCPP(TPreprocessor2PackageQuery(TUnparenthesizedMacroArgumentQuery()))
}

Query disallowedUseOfPragmaQuery() {
//autogenerate `Query` type
result =
// `Query` type for `disallowedUseOfPragma` query
TQueryCPP(TPreprocessor2PackageQuery(TDisallowedUseOfPragmaQuery()))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ import OutOfBounds
import Pointers
import Preconditions1
import Preconditions4
import Preprocessor
import Preprocessor2
import Representation
import Scope
import SideEffects1
Expand Down Expand Up @@ -139,6 +141,8 @@ newtype TCPPQuery =
TPointersPackageQuery(PointersQuery q) or
TPreconditions1PackageQuery(Preconditions1Query q) or
TPreconditions4PackageQuery(Preconditions4Query q) or
TPreprocessorPackageQuery(PreprocessorQuery q) or
TPreprocessor2PackageQuery(Preprocessor2Query q) or
TRepresentationPackageQuery(RepresentationQuery q) or
TScopePackageQuery(ScopeQuery q) or
TSideEffects1PackageQuery(SideEffects1Query q) or
Expand Down Expand Up @@ -217,6 +221,8 @@ predicate isQueryMetadata(Query query, string queryId, string ruleId, string cat
isPointersQueryMetadata(query, queryId, ruleId, category) or
isPreconditions1QueryMetadata(query, queryId, ruleId, category) or
isPreconditions4QueryMetadata(query, queryId, ruleId, category) or
isPreprocessorQueryMetadata(query, queryId, ruleId, category) or
isPreprocessor2QueryMetadata(query, queryId, ruleId, category) or
isRepresentationQueryMetadata(query, queryId, ruleId, category) or
isScopeQueryMetadata(query, queryId, ruleId, category) or
isSideEffects1QueryMetadata(query, queryId, ruleId, category) or
Expand Down
2 changes: 2 additions & 0 deletions cpp/misra/src/codeql-pack.lock.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
---
lockVersion: 1.0.0
dependencies:
advanced-security/qtil:
version: 0.0.3
codeql/cpp-all:
version: 5.0.0
codeql/dataflow:
Expand Down
1 change: 1 addition & 0 deletions cpp/misra/src/qlpack.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ license: MIT
dependencies:
codeql/common-cpp-coding-standards: '*'
codeql/cpp-all: 5.0.0
advanced-security/qtil: 0.0.3
57 changes: 57 additions & 0 deletions cpp/misra/src/rules/RULE-19-0-4/UndefOfMacroNotDefinedInFile.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* @id cpp/misra/undef-of-macro-not-defined-in-file
* @name RULE-19-0-4: #undef should only be used for macros defined previously in the same file
* @description Using #undef to undefine a macro that is not defined in the same file can lead to
* confusion.
* @kind problem
* @precision very-high
* @problem.severity warning
* @tags external/misra/id/rule-19-0-4
* scope/single-translation-unit
* readability
* maintainability
* external/misra/enforcement/decidable
* external/misra/obligation/advisory
*/

import cpp
import codingstandards.cpp.misra
import qtil.Qtil

class DefOrUndef extends PreprocessorDirective {
DefOrUndef() { this instanceof PreprocessorUndef or this instanceof Macro }

string getName() {
result = this.(PreprocessorUndef).getName() or
result = this.(Macro).getName()
}
}

predicate relevantNameAndFile(string name, File file) {
exists(DefOrUndef m |
m.getName() = name and
m.getFile() = file
)
}

class StringFilePair = Qtil::Pair<string, File, relevantNameAndFile/2>::Pair;

/**
* Defs and undefs ordered by location, grouped by name and file.
*/
class OrderedDefOrUndef extends Qtil::Ordered<DefOrUndef>::GroupBy<StringFilePair>::Type {
override int getOrder() { result = getLocation().getStartLine() }

override StringFilePair getGroup() {
result.getFirst() = getName() and result.getSecond() = getFile()
}
}

from OrderedDefOrUndef defOrUndef
where
not isExcluded(defOrUndef, PreprocessorPackage::undefOfMacroNotDefinedInFileQuery()) and
// There exists an #undef for a given name and file
defOrUndef instanceof PreprocessorUndef and
// A previous def or undef of this name must exist in this file, and it must be a #define
not defOrUndef.getPrevious() instanceof Macro
select defOrUndef, "Undef of name '" + defOrUndef.getName() + "' not defined in the same file."
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @id cpp/misra/defined-operator-expanded-in-if-directive
* @name RULE-19-1-1: The defined preprocessor operator shall be used appropriately
* @description Macro expansions that produce the token 'defined' inside of an if directive result
* in undefined behavior.
* @kind problem
* @precision very-high
* @problem.severity error
* @tags external/misra/id/rule-19-1-1
* scope/single-translation-unit
* correctness
* maintainability
* external/misra/enforcement/decidable
* external/misra/obligation/required
*/

import cpp
import codingstandards.cpp.misra

from PreprocessorIf ifDirective, MacroInvocation mi
where
not isExcluded(ifDirective, PreprocessorPackage::definedOperatorExpandedInIfDirectiveQuery()) and
ifDirective.getLocation().subsumes(mi.getLocation()) and
mi.getMacro().getBody().regexpMatch(".*defined.*")
select ifDirective,
"If directive contains macro expansion including the token 'defined' from macro $@, which results in undefined behavior.",
mi.getMacro(), mi.getMacroName()
42 changes: 42 additions & 0 deletions cpp/misra/src/rules/RULE-19-1-1/InvalidTokenInDefinedOperator.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* @id cpp/misra/invalid-token-in-defined-operator
* @name RULE-19-1-1: The defined preprocessor operator shall be used appropriately
* @description Using the defined operator without an immediately following optionally parenthesized
* identifier results in undefined behavior.
* @kind problem
* @precision very-high
* @problem.severity error
* @tags external/misra/id/rule-19-1-1
* scope/single-translation-unit
* correctness
* maintainability
* external/misra/enforcement/decidable
* external/misra/obligation/required
*/

import cpp
import codingstandards.cpp.misra

string idRegex() { result = "[a-zA-Z_]([a-zA-Z_0-9]*)" }

bindingset[body]
predicate hasInvalidDefinedOperator(string body) {
body.regexpMatch(".*\\bdefined" +
// Contains text "defined" at a word break
// Negative zero width lookahead:
"(?!(" +
// (group) optional whitespace followed by a valid identifier
"(\\s*" + idRegex() + ")" +
// or
"|" +
// (group) optional whitespace followed by parenthesis and valid identifier
"(\\s*\\(\\s*" + idRegex() + "\\s*\\))" +
// End negative zero width lookahead, match remaining text
")).*")
}

from PreprocessorIf ifDirective
where
not isExcluded(ifDirective, PreprocessorPackage::invalidTokenInDefinedOperatorQuery()) and
hasInvalidDefinedOperator(ifDirective.getHead())
select ifDirective, "Invalid use of defined operator in if directive."
Loading
Loading