Skip to content

Commit abdf993

Browse files
authored
Merge pull request github#6537 from andersfugmann/implicit_downcast_involving_references
Implicit downcast involving references
2 parents 8f73c69 + 67a267d commit abdf993

File tree

4 files changed

+37
-9
lines changed

4 files changed

+37
-9
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
lgtm,codescanning
2+
* The query `cpp/implicit-bitfield-downcast` now accounts for C++ reference types, which leads to more true positive results.

cpp/ql/src/Likely Bugs/Conversion/ImplicitDowncastFromBitfield.ql

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,15 @@
1313

1414
import cpp
1515

16-
from BitField fi, VariableAccess va
16+
from BitField fi, VariableAccess va, Type fct
1717
where
18-
fi.getNumBits() > va.getFullyConverted().getType().getSize() * 8 and
19-
va.getExplicitlyConverted().getType().getSize() > va.getFullyConverted().getType().getSize() and
18+
(
19+
if va.getFullyConverted().getType() instanceof ReferenceType
20+
then fct = va.getFullyConverted().getType().(ReferenceType).getBaseType()
21+
else fct = va.getFullyConverted().getType()
22+
) and
23+
fi.getNumBits() > fct.getSize() * 8 and
24+
va.getExplicitlyConverted().getType().getSize() > fct.getSize() and
2025
va.getTarget() = fi and
21-
not va.getActualType() instanceof BoolType
26+
not fct.getUnspecifiedType() instanceof BoolType
2227
select va, "Implicit downcast of bitfield $@", fi, fi.toString()
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
| test.cpp:10:11:10:11 | x | Implicit downcast of bitfield $@ | test.cpp:2:6:2:6 | x | x |
2+
| test.cpp:26:25:26:25 | x | Implicit downcast of bitfield $@ | test.cpp:2:6:2:6 | x | x |

cpp/ql/test/query-tests/Likely Bugs/Conversion/ImplicitDowncastFromBitfield/test.cpp

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,41 @@ typedef struct {
33
} my_struct;
44

55
int getX1(my_struct m) {
6-
return m.x;
6+
return m.x; // GOOD
77
}
88

99
short getX2(my_struct m) {
10-
return m.x;
10+
return m.x; // BAD
1111
}
1212

1313
short getX3(my_struct m) {
14-
return (short) m.x;
14+
return (short) m.x; // GOOD
1515
}
1616

1717
bool getX4(my_struct m) {
18-
return m.x;
18+
return m.x; // GOOD
1919
}
2020

2121
short getX5(my_struct m) {
22-
return (char) m.x;
22+
return (char) m.x; // GOOD
23+
}
24+
25+
const char& getx6(my_struct& m) {
26+
const char& result = m.x; // BAD
27+
return result;
28+
}
29+
30+
const short& getx7(my_struct& m) {
31+
const short& result = (short) m.x; // GOOD
32+
return result;
33+
}
34+
35+
const int& getx8(my_struct& m) {
36+
const int& result = m.x; // GOOD
37+
return result;
38+
}
39+
40+
const bool& getx9(my_struct& m) {
41+
const bool& result = m.x; // GOOD
42+
return result;
2343
}

0 commit comments

Comments
 (0)