-
Notifications
You must be signed in to change notification settings - Fork 2.1k
feat(lint): add UnsafeTypecast lint #11046
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TropicalDog17
wants to merge
26
commits into
foundry-rs:master
Choose a base branch
from
TropicalDog17:feat/unsafe-typecast-lint
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,716
−1
Open
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
e8aafe0
bet
TropicalDog17 0455b31
Merge branch 'master' into feat/unsafe-typecast-lint
TropicalDog17 befa78a
add more tests, emit fix
TropicalDog17 34e6a68
Merge branch 'feat/unsafe-typecast-lint' of github.com:TropicalDog17/…
TropicalDog17 45f5bda
remove unused deps
TropicalDog17 dff52fa
test: remove compiler error test
TropicalDog17 2768187
Merge branch 'master' into feat/unsafe-typecast-lint
TropicalDog17 47e80e4
lint
TropicalDog17 3614115
refactor
TropicalDog17 01210d8
Merge branch 'feat/unsafe-typecast-lint' of github.com:TropicalDog17/…
TropicalDog17 3d4f355
Merge branch 'master' into feat/unsafe-typecast-lint
0xrusowsky e7febc7
Update crates/lint/src/sol/med/unsafe_typecast.rs
TropicalDog17 7b541f9
refactor
TropicalDog17 a541299
refactor
TropicalDog17 c140190
Merge branch 'master' into feat/unsafe-typecast-lint
TropicalDog17 403792d
Merge branch 'master' into feat/unsafe-typecast-lint
0xrusowsky df675c8
Update crates/lint/src/sol/med/unsafe_typecast.rs
TropicalDog17 8816572
bet
TropicalDog17 bcf6760
Merge branch 'feat/unsafe-typecast-lint' of github.com:TropicalDog17/…
TropicalDog17 4883cba
fix: bless files + nits
0xrusowsky f20127b
fix: infer_source_type for string literals
0xrusowsky 30ee511
style: standardize imports
0xrusowsky 84f8f1b
nit: improve lint msg
0xrusowsky 6fc6866
fix: resolve call type to properly solve cast chains
0xrusowsky 114b609
Merge branch 'master' into feat/unsafe-typecast-lint
0xrusowsky 230e762
fix false positive
TropicalDog17 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,169 @@ | ||
use super::UnsafeTypecast; | ||
use crate::{ | ||
linter::{LateLintPass, LintContext, Snippet}, | ||
sol::{Severity, SolLint}, | ||
}; | ||
use solar_ast::{LitKind, StrKind}; | ||
use solar_sema::hir::{self, ElementaryType, ExprKind, ItemId, Res, TypeKind}; | ||
|
||
declare_forge_lint!( | ||
UNSAFE_TYPECAST, | ||
Severity::Med, | ||
"unsafe-typecast", | ||
"typecasts that can truncate values should be checked" | ||
); | ||
|
||
impl<'hir> LateLintPass<'hir> for UnsafeTypecast { | ||
fn check_expr( | ||
&mut self, | ||
ctx: &LintContext<'_>, | ||
hir: &'hir hir::Hir<'hir>, | ||
expr: &'hir hir::Expr<'hir>, | ||
) { | ||
// Check for type cast expressions: Type(value) | ||
if let ExprKind::Call(call, args, _) = &expr.kind | ||
&& let ExprKind::Type(hir::Type { kind: TypeKind::Elementary(ty), .. }) = &call.kind | ||
&& args.len() == 1 | ||
&& let Some(call_arg) = args.exprs().next() | ||
&& is_unsafe_typecast_hir(hir, call_arg, ty) | ||
{ | ||
ctx.emit_with_fix( | ||
&UNSAFE_TYPECAST, | ||
expr.span, | ||
Snippet::Block { | ||
desc: Some("Consider disabling this lint if you're certain the cast is safe:"), | ||
code: format!( | ||
"// casting to '{abi_ty}' is safe because [explain why]\n// forge-lint: disable-next-line(unsafe-typecast)", | ||
abi_ty = ty.to_abi_str() | ||
) | ||
} | ||
); | ||
} | ||
} | ||
} | ||
|
||
fn is_unsafe_typecast_hir( | ||
hir: &hir::Hir<'_>, | ||
source_expr: &hir::Expr<'_>, | ||
target_type: &hir::ElementaryType, | ||
) -> bool { | ||
let Some(source_elem_type) = infer_source_type(hir, source_expr) else { | ||
return false; | ||
}; | ||
|
||
if let ElementaryType::Int(tgt_size) = target_type { | ||
if let ExprKind::Call(call_expr, args, _) = &source_expr.kind { | ||
if let ExprKind::Type(hir::Type { | ||
kind: TypeKind::Elementary(ElementaryType::UInt(src_bits)), | ||
.. | ||
}) = &call_expr.kind | ||
{ | ||
if let Some(inner) = args.exprs().next() { | ||
if let Some(ElementaryType::UInt(orig_bits)) = infer_source_type(hir, inner) { | ||
if orig_bits.bits() < tgt_size.bits() { | ||
return false; | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
is_unsafe_elementary_typecast(&source_elem_type, target_type) | ||
} | ||
|
||
/// Infers the elementary type of a source expression. | ||
/// For cast chains, returns the ultimate source type, not intermediate cast results. | ||
fn infer_source_type(hir: &hir::Hir<'_>, expr: &hir::Expr<'_>) -> Option<ElementaryType> { | ||
match &expr.kind { | ||
// A type cast call: Type(val) | ||
ExprKind::Call(call_expr, args, _) => { | ||
if let ExprKind::Type(hir::Type { kind: TypeKind::Elementary(elem_type), .. }) = | ||
&call_expr.kind | ||
{ | ||
return Some(*elem_type); | ||
} | ||
None | ||
} | ||
|
||
// Identifiers (variables) | ||
ExprKind::Ident(resolutions) => { | ||
if let Some(Res::Item(ItemId::Variable(var_id))) = resolutions.first() { | ||
let variable = hir.variable(*var_id); | ||
if let TypeKind::Elementary(elem_type) = &variable.ty.kind { | ||
return Some(*elem_type); | ||
} | ||
} | ||
None | ||
} | ||
|
||
// Handle literal strings/hex | ||
ExprKind::Lit(hir::Lit { kind, .. }) => match kind { | ||
LitKind::Str(StrKind::Hex, ..) => Some(ElementaryType::Bytes), | ||
LitKind::Str(..) => Some(ElementaryType::String), | ||
LitKind::Address(_) => Some(ElementaryType::Address(false)), | ||
LitKind::Bool(_) => Some(ElementaryType::Bool), | ||
|
||
// Unnecessary to check numbers as assigning literal values which cannot fit into a type | ||
// throws a compiler error. Reference: <https://solang.readthedocs.io/en/latest/language/types.html> | ||
_ => None, | ||
}, | ||
|
||
// Unary operations | ||
ExprKind::Unary(op, inner_expr) => match op.kind { | ||
solar_ast::UnOpKind::Neg => match infer_source_type(hir, inner_expr) { | ||
Some(ElementaryType::UInt(size)) => Some(ElementaryType::Int(size)), | ||
Some(signed_type @ ElementaryType::Int(_)) => Some(signed_type), | ||
_ => Some(ElementaryType::Int(solar_ast::TypeSize::ZERO)), | ||
}, | ||
_ => infer_source_type(hir, inner_expr), | ||
}, | ||
|
||
ExprKind::Binary(lhs, _, rhs) => { | ||
if let Some(ty) = infer_source_type(hir, lhs) { | ||
return Some(ty); | ||
} | ||
infer_source_type(hir, rhs) | ||
} | ||
_ => None, | ||
} | ||
} | ||
|
||
/// Checks if a type cast from source_type to target_type is unsafe. | ||
fn is_unsafe_elementary_typecast( | ||
source_type: &ElementaryType, | ||
target_type: &ElementaryType, | ||
) -> bool { | ||
match (source_type, target_type) { | ||
// Numeric downcasts (smaller target size) | ||
(ElementaryType::UInt(source_size), ElementaryType::UInt(target_size)) | ||
| (ElementaryType::Int(source_size), ElementaryType::Int(target_size)) => { | ||
source_size.bits() > target_size.bits() | ||
} | ||
|
||
// Signed to unsigned conversion (potential loss of sign) | ||
(ElementaryType::Int(_), ElementaryType::UInt(_)) => true, | ||
|
||
// Unsigned to signed conversion with same or smaller size | ||
(ElementaryType::UInt(source_size), ElementaryType::Int(target_size)) => { | ||
source_size.bits() >= target_size.bits() | ||
} | ||
|
||
// Fixed bytes to smaller fixed bytes | ||
(ElementaryType::FixedBytes(source_size), ElementaryType::FixedBytes(target_size)) => { | ||
source_size.bytes() > target_size.bytes() | ||
} | ||
|
||
// Dynamic bytes to fixed bytes (potential truncation) | ||
(ElementaryType::Bytes, ElementaryType::FixedBytes(_)) | ||
| (ElementaryType::String, ElementaryType::FixedBytes(_)) => true, | ||
|
||
// Address to smaller uint (truncation) - address is 160 bits | ||
(ElementaryType::Address(_), ElementaryType::UInt(target_size)) => target_size.bits() < 160, | ||
|
||
// Address to int (sign issues) | ||
(ElementaryType::Address(_), ElementaryType::Int(_)) => true, | ||
|
||
_ => false, | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we check intermediate casts for cast chains? I think that's why this isn't throwing:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would suggest adding a test, you can also reproduce using the following commands:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
good call, fixed to support cast chains.
do you expect any other cases not covered by the unit tests?