Skip to content

Commit 5bbe64c

Browse files
authored
Merge branch 'main' into rvermeulen/fix-371
2 parents 9109b3c + 17d73e4 commit 5bbe64c

File tree

73 files changed

+974
-340
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+974
-340
lines changed

.vscode/tasks.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,28 @@
140140
},
141141
"problemMatcher": []
142142
},
143+
{
144+
"label": "🧪 Standards Automation: Build Case Test DB from test file",
145+
"type": "shell",
146+
"windows": {
147+
"command": ".${pathSeparator}scripts${pathSeparator}.venv${pathSeparator}Scripts${pathSeparator}python.exe scripts${pathSeparator}build_test_database.py ${file}"
148+
},
149+
"linux": {
150+
"command": ".${pathSeparator}scripts${pathSeparator}.venv${pathSeparator}bin${pathSeparator}python3 scripts${pathSeparator}build_test_database.py ${file}"
151+
},
152+
"osx": {
153+
"command": ".${pathSeparator}scripts${pathSeparator}.venv${pathSeparator}bin${pathSeparator}python3 scripts${pathSeparator}build_test_database.py ${file}"
154+
},
155+
"presentation": {
156+
"reveal": "always",
157+
"panel": "new",
158+
"focus": true
159+
},
160+
"runOptions": {
161+
"reevaluateOnRerun": false
162+
},
163+
"problemMatcher": []
164+
},
143165
{
144166
"label": "📝 Standards Automation: Format CodeQL",
145167
"type": "shell",

README.md

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,12 @@ This repository contains CodeQL queries and libraries which support various Codi
66

77
_Carnegie Mellon and CERT are registered trademarks of Carnegie Mellon University._
88

9-
This repository contains CodeQL queries and libraries which support various Coding Standards for the [C++14](https://www.iso.org/standard/64029.html) programming language.
9+
This repository contains CodeQL queries and libraries which support various Coding Standards for the [C++14](https://www.iso.org/standard/64029.html), [C99](https://www.iso.org/standard/29237.html) and [C11](https://www.iso.org/standard/57853.html) programming languages.
1010

1111
The following coding standards are supported:
1212
- [AUTOSAR - Guidelines for the use of C++14 language in critical and safety-related systems (Releases R22-11, R20-11, R19-11 and R19-03)](https://www.autosar.org/fileadmin/standards/R22-11/AP/AUTOSAR_RS_CPP14Guidelines.pdf).
1313
- [MISRA C++:2008](https://www.misra.org.uk) (support limited to the rules specified in AUTOSAR).
1414
- [SEI CERT C++ Coding Standard: Rules for Developing Safe, Reliable, and Secure Systems (2016 Edition)](https://resources.sei.cmu.edu/library/asset-view.cfm?assetID=494932)
15-
16-
In addition, the following Coding Standards for the C programming language are under development:
17-
1815
- [SEI CERT C Coding Standard: Rules for Developing Safe, Reliable, and Secure Systems (2016 Edition)](https://resources.sei.cmu.edu/downloads/secure-coding/assets/sei-cert-c-coding-standard-2016-v01.pdf)
1916
- [MISRA C 2012](https://www.misra.org.uk/product/misra-c2012-third-edition-first-revision/).
2017

c/misra/src/rules/RULE-20-8/ControllingExpressionIfDirective.ql

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,40 +14,35 @@
1414

1515
import cpp
1616
import codingstandards.c.misra
17+
import codingstandards.cpp.PreprocessorDirective
1718

1819
/* A controlling expression is evaluated if it is not excluded (guarded by another controlling expression that is not taken). This translates to it either being taken or not taken. */
1920
predicate isEvaluated(PreprocessorBranch b) { b.wasTaken() or b.wasNotTaken() }
2021

21-
class IfOrElifPreprocessorBranch extends PreprocessorBranch {
22-
IfOrElifPreprocessorBranch() {
23-
this instanceof PreprocessorIf or this instanceof PreprocessorElif
24-
}
25-
}
26-
2722
/**
2823
* Looks like it contains a single macro, which may be undefined
2924
*/
30-
class SimpleMacroPreprocessorBranch extends IfOrElifPreprocessorBranch {
25+
class SimpleMacroPreprocessorBranch extends PreprocessorIfOrElif {
3126
SimpleMacroPreprocessorBranch() { this.getHead().regexpMatch("[a-zA-Z_][a-zA-Z0-9_]+") }
3227
}
3328

34-
class SimpleNumericPreprocessorBranch extends IfOrElifPreprocessorBranch {
29+
class SimpleNumericPreprocessorBranch extends PreprocessorIfOrElif {
3530
SimpleNumericPreprocessorBranch() { this.getHead().regexpMatch("[0-9]+") }
3631
}
3732

3833
class ZeroOrOnePreprocessorBranch extends SimpleNumericPreprocessorBranch {
3934
ZeroOrOnePreprocessorBranch() { this.getHead().regexpMatch("[0|1]") }
4035
}
4136

42-
predicate containsOnlySafeOperators(IfOrElifPreprocessorBranch b) {
37+
predicate containsOnlySafeOperators(PreprocessorIfOrElif b) {
4338
containsOnlyDefinedOperator(b)
4439
or
4540
//logic: comparison operators eval last, so they make it safe?
4641
b.getHead().regexpMatch(".*[\\&\\&|\\|\\||>|<|==].*")
4742
}
4843

4944
//all defined operators is definitely safe
50-
predicate containsOnlyDefinedOperator(IfOrElifPreprocessorBranch b) {
45+
predicate containsOnlyDefinedOperator(PreprocessorIfOrElif b) {
5146
forall(string portion |
5247
portion =
5348
b.getHead()
@@ -65,7 +60,7 @@ class BinaryValuedMacro extends Macro {
6560
BinaryValuedMacro() { this.getBody().regexpMatch("\\(?(0|1)\\)?") }
6661
}
6762

68-
from IfOrElifPreprocessorBranch b, string msg
63+
from PreprocessorIfOrElif b, string msg
6964
where
7065
not isExcluded(b, Preprocessor3Package::controllingExpressionIfDirectiveQuery()) and
7166
isEvaluated(b) and
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
`M8-5-2` - `AggregateLiteralEnhancements.qll`:
2+
- recognise aggregate literals initialized with parameters from variadic templates.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
- `A2-10-1`, `RULE-5-3`:
2+
- Reduce false positives by considering point of declaration for local variables.
3+
- Reduce false negatives by considering catch block parameters to be in scope in the catch block.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
- `M6-5-5`:
2+
- Reduce false positives by no longer considering the taking of a const reference as a modification.
3+
- Improve detection of non-local modification of loop iteration variables to reduce false positives.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
- `M16-1-1` - `DefinedPreProcessorOperatorGeneratedFromExpansionFound.ql`:
2+
- Optimize query to improve performance
3+
- Improve detection of macros whose body contains the `defined` operator after the start of the macro (e.g. `#define X Y || defined(Z)`).
4+
- Enable exclusions to be applied for this rule.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
`M5-2-10` - `IncrementAndDecrementOperatorsMixedWithOtherOperatorsInExpression.ql`:
2+
- only report use of the increment and decrement operations in conjunction with arithmetic operators, as specified by the rule. Notably we no longer report the expressions of the form `*p++`, which combine increment and dereferencing operations.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
- `A8-4-8` - `OutParametersUsed.ql`
2+
- Fixes #370 - Non-member user-defined assignment operator and stream insertion/extraction parameters that are required to be out parameters are excluded.
3+
- Broadens the definition of out parameter by considering assignment and crement operators as modifications to an out parameter candidate.
4+
- `FIO51-CPP` - `CloseFilesWhenTheyAreNoLongerNeeded.ql`:
5+
- Broadened definition of `IStream` and `OStream` types may result in reduced false negatives.
6+
- `A5-1-1` - `LiteralValueUsedOutsideTypeInit.ql`:
7+
- Broadened definition of `IStream` types may result in reduced false positives because more file stream function calls may be detected as logging operations that will be excluded from the results.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
- `A2-10-4` - `IdentifierNameOfStaticNonMemberObjectReusedInNamespace.ql`:
2+
- Fix FP reported in #385. Addresses incorrect detection of partially specialized template variables as conflicting reuses.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
- `A18-0-1` - `CLibraryFacilitiesNotAccessedThroughCPPLibraryHeaders.ql`:
2+
- Fix issue #7 - improve query logic to only match on exact standard library names (e.g., now excludes sys/header.h type headers from the results as those are not C standard libraries).
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-`A15-4-4` - `MissingNoExcept.ql`:
2+
- Fix FP reported in #424. Exclude functions calling `std::string::reserve` or `std::string::append` that may throw even if their signatures don't specify it.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
- `M0-1-4` - `SingleUseMemberPODVariable.ql`:
2+
- Address FP reported in #388. Include aggregrate initialization as a use of a member.
3+
- Include indirect initialization of members. For example, casting a pointer to a buffer to a struct pointer.
4+
- Reformat the alert message to adhere to the style-guide.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
- `M0-1-3` - `UnusedMemberVariable.ql`, `UnusedGlobalOrNamespaceVariable.ql`:
2+
- Address FP reported in #384. Exclude variables with compile time values that may have been used as a template argument.
3+
- Exclude uninstantiated template members.
4+
- Reformat the alert message to adhere to the style-guide.

cpp/autosar/src/rules/A18-0-1/CLibraryFacilitiesNotAccessedThroughCPPLibraryHeaders.ql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ where
2828
* not use any of 'signal.h's facilities, for example.
2929
*/
3030

31-
filename = i.getIncludedFile().getBaseName() and
31+
filename = i.getIncludeText().substring(1, i.getIncludeText().length() - 1) and
3232
filename in [
3333
"assert.h", "ctype.h", "errno.h", "fenv.h", "float.h", "inttypes.h", "limits.h", "locale.h",
3434
"math.h", "setjmp.h", "signal.h", "stdarg.h", "stddef.h", "stdint.h", "stdio.h", "stdlib.h",

cpp/autosar/src/rules/A2-10-4/IdentifierNameOfStaticNonMemberObjectReusedInNamespace.ql

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ class CandidateVariable extends Variable {
2020
CandidateVariable() {
2121
hasDefinition() and
2222
isStatic() and
23-
not this instanceof MemberVariable
23+
not this instanceof MemberVariable and
24+
//exclude partially specialized template variables
25+
not exists(TemplateVariable v | this = v.getAnInstantiation())
2426
}
2527
}
2628

cpp/autosar/src/rules/A8-4-8/OutputParametersUsed.ql

Lines changed: 49 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -23,31 +23,60 @@ import codingstandards.cpp.ConstHelpers
2323
import codingstandards.cpp.Operator
2424

2525
/**
26-
* Non-const T& and T* `Parameter`s to `Function`s
26+
* Holds if p is passed as a non-const reference or pointer and is modified.
27+
* This holds for in-out or out-only parameters.
2728
*/
28-
class NonConstReferenceOrPointerParameterCandidate extends FunctionParameter {
29-
NonConstReferenceOrPointerParameterCandidate() {
30-
this instanceof NonConstReferenceParameter
31-
or
32-
this instanceof NonConstPointerParameter
33-
}
29+
predicate isOutParameter(NonConstPointerorReferenceParameter p) {
30+
any(VariableEffect ve).getTarget() = p
31+
}
32+
33+
/**
34+
* Holds if parameter `p` is a parameter to a user defined assignment operator that
35+
* is defined outside of a class body.
36+
* These require an in-out parameter as the first argument.
37+
*/
38+
predicate isNonMemberUserAssignmentParameter(NonConstPointerorReferenceParameter p) {
39+
p.getFunction() instanceof UserAssignmentOperator and
40+
not p.isMember()
41+
}
42+
43+
/**
44+
* Holds if parameter `p` is a parameter to a stream insertion operator that
45+
* is defined outside of a class body.
46+
* These require an in-out parameter as the first argument.
47+
*
48+
* e.g., `std::ostream& operator<<(std::ostream& os, const T& obj)`
49+
*/
50+
predicate isStreamInsertionStreamParameter(NonConstPointerorReferenceParameter p) {
51+
exists(StreamInsertionOperator op | not op.isMember() | op.getParameter(0) = p)
3452
}
3553

36-
pragma[inline]
37-
predicate isFirstAccess(VariableAccess va) {
38-
not exists(VariableAccess otherVa |
39-
otherVa.getTarget() = va.getTarget() or
40-
otherVa.getQualifier().(VariableAccess).getTarget() = va.getTarget()
41-
|
42-
otherVa.getASuccessor() = va
54+
/**
55+
* Holds if parameter `p` is a parameter to a stream insertion operator that
56+
* is defined outside of a class body.
57+
* These require an in-out parameter as the first argument and an out parameter for the second.
58+
*
59+
* e.g., `std::istream& operator>>(std::istream& is, T& obj)`
60+
*/
61+
predicate isStreamExtractionParameter(NonConstPointerorReferenceParameter p) {
62+
exists(StreamExtractionOperator op | not op.isMember() |
63+
op.getParameter(0) = p
64+
or
65+
op.getParameter(1) = p
4366
)
4467
}
4568

46-
from NonConstReferenceOrPointerParameterCandidate p, VariableEffect ve
69+
predicate isException(NonConstPointerorReferenceParameter p) {
70+
isNonMemberUserAssignmentParameter(p) and p.getIndex() = 0
71+
or
72+
isStreamInsertionStreamParameter(p)
73+
or
74+
isStreamExtractionParameter(p)
75+
}
76+
77+
from NonConstPointerorReferenceParameter p
4778
where
4879
not isExcluded(p, ConstPackage::outputParametersUsedQuery()) and
49-
ve.getTarget() = p and
50-
isFirstAccess(ve.getAnAccess()) and
51-
not ve instanceof AnyAssignOperation and
52-
not ve instanceof CrementOperation
53-
select p, "Out parameter " + p.getName() + " that is modified before being read."
80+
isOutParameter(p) and
81+
not isException(p)
82+
select p, "Out parameter '" + p.getName() + "' used."

cpp/autosar/src/rules/M0-1-3/UnusedGlobalOrNamespaceVariable.ql

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,7 @@ from PotentiallyUnusedGlobalOrNamespaceVariable v
2222
where
2323
not isExcluded(v, DeadCodePackage::unusedGlobalOrNamespaceVariableQuery()) and
2424
// No variable access
25-
not exists(v.getAnAccess())
26-
select v, "Variable " + v.getQualifiedName() + " is unused."
25+
not exists(v.getAnAccess()) and
26+
// Exclude members whose value is compile time and is potentially used to inintialize a template
27+
not maybeACompileTimeTemplateArgument(v)
28+
select v, "Variable '" + v.getQualifiedName() + "' is unused."

cpp/autosar/src/rules/M0-1-3/UnusedLocalVariable.ql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,4 @@ where
5050
// Local variable is never accessed
5151
not exists(v.getAnAccess()) and
5252
getUseCountConservatively(v) = 0
53-
select v, "Local variable " + v.getName() + " in " + v.getFunction().getName() + " is not used."
53+
select v, "Local variable '" + v.getName() + "' in '" + v.getFunction().getName() + "' is not used."

cpp/autosar/src/rules/M0-1-3/UnusedMemberVariable.ql

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,5 +25,7 @@ where
2525
// No variable access
2626
not exists(v.getAnAccess()) and
2727
// No explicit initialization in a constructor
28-
not exists(UserProvidedConstructorFieldInit cfi | cfi.getTarget() = v)
29-
select v, "Member variable " + v.getName() + " is unused."
28+
not exists(UserProvidedConstructorFieldInit cfi | cfi.getTarget() = v) and
29+
// Exclude members whose value is compile time and is potentially used to inintialize a template
30+
not maybeACompileTimeTemplateArgument(v)
31+
select v, "Member variable '" + v.getName() + "' is unused."

cpp/autosar/src/rules/M0-1-4/SingleUseMemberPODVariable.ql

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,5 @@ where
2424
not isExcluded(v, DeadCodePackage::singleUseMemberPODVariableQuery()) and
2525
isSingleUseNonVolatilePODVariable(v)
2626
select v,
27-
"Member POD variable " + v.getName() + " in " + v.getDeclaringType().getName() + " is only $@.",
28-
getSingleUse(v), "used once"
27+
"Member POD variable '" + v.getName() + "' in '" + v.getDeclaringType().getName() +
28+
"' is only $@.", getSingleUse(v), "used once"

cpp/autosar/src/rules/M0-1-4/SingleUsePODVariable.qll

Lines changed: 60 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,68 @@ private string getConstExprValue(Variable v) {
1010
v.isConstexpr()
1111
}
1212

13+
/**
14+
* Gets the number of uses of variable `v` in an opaque assignment, where an opaqua assignment for example a cast from one type to the other and `v` is assumed to be a member of the resulting type.
15+
* e.g.,
16+
* struct foo {
17+
* int bar;
18+
* }
19+
*
20+
* struct foo * v = (struct foo*)buffer;
21+
*/
22+
Expr getIndirectSubObjectAssignedValue(MemberVariable subobject) {
23+
// struct foo * ptr = (struct foo*)buffer;
24+
exists(Struct someStruct, Variable instanceOfSomeStruct | someStruct.getAMember() = subobject |
25+
instanceOfSomeStruct.getType().(PointerType).getBaseType() = someStruct and
26+
exists(Cast assignedValue |
27+
// Exclude cases like struct foo * v = nullptr;
28+
not assignedValue.isImplicit() and
29+
// `v` is a subobject of another type that reinterprets another object. We count that as a use of `v`.
30+
assignedValue.getExpr() = instanceOfSomeStruct.getAnAssignedValue() and
31+
result = assignedValue
32+
)
33+
or
34+
// struct foo; read(..., (char *)&foo);
35+
instanceOfSomeStruct.getType() = someStruct and
36+
exists(Call externalInitializerCall, Cast castToCharPointer, int n |
37+
externalInitializerCall.getArgument(n).(AddressOfExpr).getOperand() =
38+
instanceOfSomeStruct.getAnAccess() and
39+
externalInitializerCall.getArgument(n) = castToCharPointer.getExpr() and
40+
castToCharPointer.getType().(PointerType).getBaseType().getUnspecifiedType() instanceof
41+
CharType and
42+
result = externalInitializerCall
43+
)
44+
or
45+
// the object this subject is part of is initialized and we assumes this initializes the subobject.
46+
instanceOfSomeStruct.getType() = someStruct and
47+
result = instanceOfSomeStruct.getInitializer().getExpr()
48+
)
49+
}
50+
1351
/** Gets a "use" count according to rule M0-1-4. */
1452
int getUseCount(Variable v) {
15-
exists(int initializers |
16-
// We enforce that it's a POD type variable, so if it has an initializer it is explicit
17-
(if v.hasInitializer() then initializers = 1 else initializers = 0) and
18-
result =
19-
initializers +
20-
count(VariableAccess access | access = v.getAnAccess() and not access.isCompilerGenerated())
21-
+ count(UserProvidedConstructorFieldInit cfi | cfi.getTarget() = v) +
22-
// For constexpr variables used as template arguments, we don't see accesses (just the
23-
// appropriate literals). We therefore take a conservative approach and count the number of
24-
// template instantiations that use the given constant, and consider each one to be a use
25-
// of the variable
26-
count(ClassTemplateInstantiation cti |
27-
cti.getTemplateArgument(_).(Expr).getValue() = getConstExprValue(v)
28-
)
29-
)
53+
// We enforce that it's a POD type variable, so if it has an initializer it is explicit
54+
result =
55+
count(getAUserInitializedValue(v)) +
56+
count(VariableAccess access | access = v.getAnAccess() and not access.isCompilerGenerated()) +
57+
// For constexpr variables used as template arguments, we don't see accesses (just the
58+
// appropriate literals). We therefore take a conservative approach and count the number of
59+
// template instantiations that use the given constant, and consider each one to be a use
60+
// of the variable
61+
count(ClassTemplateInstantiation cti |
62+
cti.getTemplateArgument(_).(Expr).getValue() = getConstExprValue(v)
63+
) + count(getIndirectSubObjectAssignedValue(v))
64+
}
65+
66+
Expr getAUserInitializedValue(Variable v) {
67+
(
68+
result = v.getInitializer().getExpr()
69+
or
70+
exists(UserProvidedConstructorFieldInit cfi | cfi.getTarget() = v and result = cfi.getExpr())
71+
or
72+
exists(ClassAggregateLiteral l | not l.isCompilerGenerated() | result = l.getAFieldExpr(v))
73+
) and
74+
not result.isCompilerGenerated()
3075
}
3176

3277
/** Gets a single use of `v`, if `isSingleUseNonVolatilePODVariable` holds. */

0 commit comments

Comments
 (0)