Create rule S7443 Calls to std::mem::transmute
should not be evaluated eagerly (#4786)
* Create rule S7443 * Update metadata.json * Update rule.adoc * Update metadata.json --------- Co-authored-by: sallaigy <sallaigy@users.noreply.github.com> Co-authored-by: Gyula Sallai <gyula.sallai@sonarsource.com>
This commit is contained in:
parent
d4cbb1c40b
commit
1de188a9e5
2
rules/S7443/metadata.json
Normal file
2
rules/S7443/metadata.json
Normal file
@ -0,0 +1,2 @@
|
||||
{
|
||||
}
|
24
rules/S7443/rust/metadata.json
Normal file
24
rules/S7443/rust/metadata.json
Normal file
@ -0,0 +1,24 @@
|
||||
{
|
||||
"title": "Calls to `std::mem::transmute` should not be evaluated eagerly",
|
||||
"type": "BUG",
|
||||
"status": "ready",
|
||||
"remediation": {
|
||||
"func": "Constant\/Issue",
|
||||
"constantCost": "5min"
|
||||
},
|
||||
"tags": [
|
||||
"clippy"
|
||||
],
|
||||
"defaultSeverity": "Critical",
|
||||
"ruleSpecification": "RSPEC-7443",
|
||||
"sqKey": "S7443",
|
||||
"scope": "All",
|
||||
"defaultQualityProfiles": ["Sonar way"],
|
||||
"quickfix": "unknown",
|
||||
"code": {
|
||||
"impacts": {
|
||||
"RELIABILITY": "HIGH"
|
||||
},
|
||||
"attribute": "LOGICAL"
|
||||
}
|
||||
}
|
52
rules/S7443/rust/rule.adoc
Normal file
52
rules/S7443/rust/rule.adoc
Normal file
@ -0,0 +1,52 @@
|
||||
|
||||
== Why is this an issue?
|
||||
|
||||
When a transmute is placed within an expression that uses eager evaluation (like `bool::then_some`), it will execute even if a preceding validity check fails. This can result in creating invalid values, potentially leading to undefined behavior.
|
||||
|
||||
|
||||
== How to fix it
|
||||
|
||||
Use lazy evaluation (for example by replacing `then_some` with `then`) and providing a closure that contains the transmute. This ensures the transmute only occurs if the validity check passes.
|
||||
|
||||
|
||||
=== Code examples
|
||||
|
||||
==== Noncompliant code example
|
||||
|
||||
[source,rust,diff-id=1,diff-type=noncompliant]
|
||||
----
|
||||
#[repr(u8)]
|
||||
enum Opcode {
|
||||
Add = 0,
|
||||
Sub = 1,
|
||||
Mul = 2,
|
||||
Div = 3
|
||||
}
|
||||
|
||||
fn int_to_opcode(op: u8) -> Option<Opcode> {
|
||||
(op < 4).then_some(unsafe { std::mem::transmute(op) })
|
||||
}
|
||||
----
|
||||
|
||||
==== Compliant solution
|
||||
|
||||
[source,rust,diff-id=1,diff-type=compliant]
|
||||
----
|
||||
#[repr(u8)]
|
||||
enum Opcode {
|
||||
Add = 0,
|
||||
Sub = 1,
|
||||
Mul = 2,
|
||||
Div = 3
|
||||
}
|
||||
|
||||
fn int_to_opcode(op: u8) -> Option<Opcode> {
|
||||
(op < 4).then(|| unsafe { std::mem::transmute(op) })
|
||||
}
|
||||
----
|
||||
|
||||
== Resources
|
||||
=== Documentation
|
||||
|
||||
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#eager_transmute
|
||||
|
Loading…
x
Reference in New Issue
Block a user