Skip to content

Commit 6925d4e

Browse files
authored
Merge pull request #20129 from codeqlhelper/main
C++: Static variables are initialized to zero or null by compiler
2 parents 9aebc58 + 4323e68 commit 6925d4e

File tree

5 files changed

+52
-0
lines changed

5 files changed

+52
-0
lines changed

cpp/ql/src/Critical/InitialisationNotRun.ql

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,18 @@ predicate called(Function f) {
3232
exists(FunctionAccess fa | fa.getTarget() = f)
3333
}
3434

35+
predicate staticWithoutDereference(GlobalVariable v) {
36+
v.isStatic() and
37+
not exists(VariableAccess va |
38+
va = v.getAnAccess() and
39+
dereferenced(va)
40+
)
41+
}
42+
3543
from GlobalVariable v
3644
where
3745
global(v) and
46+
not staticWithoutDereference(v) and
3847
not exists(VariableAccess lval |
3948
v.getAnAccess() = lval and
4049
lval.isUsedAsLValue() and
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
category: minorAnalysis
3+
---
4+
* The "Initialization code not run" query (`cpp/initialization-not-run`) no longer reports an alert on static global variables that has no dereference.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
| test.cpp:12:16:12:17 | g1 | Initialization code for 'g1' is never run. |
2+
| test.cpp:14:23:14:24 | g3 | Initialization code for 'g3' is never run. |
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Critical/InitialisationNotRun.ql
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// --- stubs ---
2+
3+
char *strcpy(char *dest, const char *src);
4+
5+
// --- tests ---
6+
7+
class GlobalStorage {
8+
public:
9+
char name[1000];
10+
};
11+
12+
GlobalStorage *g1; // BAD
13+
static GlobalStorage g2; // GOOD
14+
static GlobalStorage *g3; // BAD
15+
// static variables are initialized by compilers
16+
static int a; // GOOD
17+
static int b = 0; // GOOD
18+
19+
void init() { //initializes g_storage, but is never run from main
20+
g1 = new GlobalStorage();
21+
g3 = new GlobalStorage();
22+
}
23+
24+
void init2(int b) {
25+
for (int i = 0; i < b; ++i)
26+
a *= -1;
27+
}
28+
29+
int main(int argc, char *argv[]) {
30+
//init not called
31+
strcpy(g1->name, argv[1]); // g1 is used before init() is called
32+
strcpy(g2.name, argv[1]); // g2 is initialised by compiler
33+
strcpy(g3->name, argv[1]);
34+
b++;
35+
return 0;
36+
}

0 commit comments

Comments
 (0)