Skip to content

Commit

Permalink
lib: fix codestyle
Browse files Browse the repository at this point in the history
  • Loading branch information
Valentin Obst committed Oct 16, 2024
1 parent e18387e commit ef3016b
Show file tree
Hide file tree
Showing 16 changed files with 54 additions and 39 deletions.
2 changes: 1 addition & 1 deletion src/cwe_checker_lib/src/analysis/graph/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ impl<'a> CallGraphBuilder<'a> {
Self {
graph: DiGraph::new(),
fn_tid_to_idx_map: HashMap::new(),
p: &p,
p,
ext_fns: p.extern_symbols.keys().collect(),
full_cfgs: false,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ impl<'a> IntraproceduralCfg<'a> {

/// Returns all blocks that contain __direct__ function calls to
/// __internal__ and __external__ functions.
pub fn call_sites<'b>(&'b self) -> impl Iterator<Item = BlockIdxs> + 'b {
pub fn call_sites(&self) -> impl Iterator<Item = BlockIdxs> + '_ {
self.calls.iter().chain(self.ext_calls.iter()).copied()
}

Expand Down
1 change: 1 addition & 0 deletions src/cwe_checker_lib/src/checkers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub mod cwe_782;
pub mod cwe_789;

pub mod prelude {
//! Prelude imports for CWE checkers.
pub use crate::utils::log::{CweWarning, LogMessage, WithLogs};
pub use crate::CweModule;
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl IrPass for ReorderFnBlocksPass {
f.blocks()
.filter(|b| Self::is_fn_start_blk(&f.tid, &b.tid))
.fold(String::new(), |mut a, i| {
a.push_str(format!("{},", i.tid.to_string()).as_str());
a.push_str(format!("{},", i.tid).as_str());
a
})
);
Expand Down
8 changes: 3 additions & 5 deletions src/cwe_checker_lib/src/intermediate_representation/blk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ pub struct Blk {
/// this field contains possible jump target addresses for the jump.
///
/// Note that possible targets of indirect calls are *not* contained,
/// since the [`Project` normalization passes](Project::normalize) assume
/// that only intraprocedural jump targets are contained in this field.
/// i.e., only intraprocedural jump targets are contained in this field.
pub indirect_jmp_targets: Vec<Tid>,
}

Expand Down Expand Up @@ -104,9 +103,8 @@ impl Blk {
.map(|d| d.referenced_constants())
.chain(self.jmps().map(|j| j.referenced_constants()))
.fold(Vec::new(), |mut acc, c| {
match c {
Some(c) => acc.extend(c),
None => (),
if let Some(c) = c {
acc.extend(c)
}

acc
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,12 @@ impl Program {
self.functions()
.flat_map(|f| f.blocks())
.flat_map(|b| b.defs())
.filter_map(|d| match &d.term {
.map(|d| match &d.term {
Def::Assign { var, value: expr } | Def::Load { var, address: expr } => {
let mut vars = expr.input_vars();
vars.push(var);

Some(vars.into_iter())
vars.into_iter()
}
Def::Store {
address: expr0,
Expand All @@ -125,7 +125,7 @@ impl Program {
let vars1 = expr1.input_vars();
vars0.extend(vars1);

Some(vars0.into_iter())
vars0.into_iter()
}
})
.chain(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,6 @@ impl Project {
impl WithLogs<Project> {
/// Performs only the optimizing normalization passes.
///
/// [`Project::normalize_basic`] **must** be called before this method.
///
/// Runs only the optimization passes that transform the program to an
/// equivalent, simpler representation. This step is exprected to improve
/// the speed and precision of later analyses.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl IrPass for DeadVariableElimPass {
}

fn run(&mut self, program: &mut Self::Input) -> Vec<LogMessage> {
let mut graph = get_program_cfg(&program);
let mut graph = get_program_cfg(program);
graph.reverse();
let all_variables = program.all_variables();
let all_variables_ref = all_variables.iter().collect::<BTreeSet<&Variable>>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ pub fn compute_alive_vars<'a, 'b>(
.iter()
.collect::<BTreeSet<&'b Variable>>(),
);
let context = Context::new(all_variables.clone(), all_phys_registers.clone(), &graph);
let context = Context::new(all_variables.clone(), all_phys_registers.clone(), graph);

let no_alive_vars = AliveVariables::default();
let mut computation = create_computation(context, None);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,15 @@ impl InputExpressionPropagationPass {
}
}
}

/// Wherever possible, substitute input variables of expressions
/// with the input expression that defines the input variable.
///
/// Note that substitution is only possible
/// if the input variables of the input expression itself did not change since the definition of said variable.
///
/// The expression propagation allows more dead stores to be removed during
/// [dead variable elimination](crate::analysis::dead_variable_elimination).
/// [dead variable elimination](super::DeadVariableElimPass).
fn propagate_input_expressions(
blk: &mut Term<Blk>,
apriori_insertable_expressions: Option<HashMap<Variable, Expression>>,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use super::prelude::*;

/// TODO
pub struct IntraproceduralDeadBlockElimPass;

impl IrPass for IntraproceduralDeadBlockElimPass {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Transforming passes that optimize the IR.
mod control_flow_propagation;
pub use control_flow_propagation::*;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
//! Substitutes stack pointer alignment operations utilising logical AND with an arithmetic SUB operation.
//!
//! The first basic block of every function is searched for a logical AND operation on the stack pointer.
//! By journaling changes to the stack pointer an offset is calculated which is going to be used to alter the operation
//! into a subtraction.
//!
//! # Log Messages
//! Following cases trigger log messages:
//! - alignment is untypical for the architecture
//! - the argument for the AND operation is not a constant
//! - an operation alters the stack pointer, which can not be journaled.
use super::prelude::*;

use crate::intermediate_representation::{Project, Variable};

mod legacy;

/// Substitutes stack pointer alignment operations utilising logical AND with an
/// arithmetic SUB operation.
///
/// The first basic block of every function is searched for a logical AND
/// operation on the stack pointer.
/// By journaling changes to the stack pointer an offset is calculated which is
/// going to be used to alter the operation into a subtraction.
///
/// # Log Messages
/// Following cases trigger log messages:
/// - alignment is untypical for the architecture
/// - the argument for the AND operation is not a constant
/// - an operation alters the stack pointer, which can not be journaled.
pub struct StackPointerAlignmentSubstitutionPass {
stack_pointer_register: Variable,
cpu_architecture: String,
Expand Down
10 changes: 5 additions & 5 deletions src/cwe_checker_lib/src/intermediate_representation/term.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,15 @@ impl Tid {

/// Returns the term identifier for the program that is based at the
/// given `address`.
pub fn new_program<T: Into<TidAddress> + Display + ?Sized>(address: T) -> Self {
pub fn new_program<T: Into<TidAddress> + Display>(address: T) -> Self {
Self {
id: format!("{}_{}", Self::PROGRAM_ID_PREFIX, address),
address: address.into(),
}
}

/// Returns the TID for the function at the given address.
pub fn new_function<T: Into<TidAddress> + Display + ?Sized>(address: T) -> Self {
pub fn new_function<T: Into<TidAddress> + Display>(address: T) -> Self {
Self {
id: format!("{}_{}", Self::FUNCTION_ID_PREFIX, address),
address: address.into(),
Expand All @@ -119,7 +119,7 @@ impl Tid {
}

/// Generate a new term identifier for the block with `index` at `address`.
pub fn new_block<T: Into<TidAddress> + Display + ?Sized>(address: T, index: u64) -> Self {
pub fn new_block<T: Into<TidAddress> + Display>(address: T, index: u64) -> Self {
let id = match index {
0 => format!("{}_{}", Self::BLOCK_ID_PREFIX, address),
_ => format!("{}_{}_{}", Self::BLOCK_ID_PREFIX, address, index),
Expand All @@ -133,7 +133,7 @@ impl Tid {

/// Generate a new term identifier for the instruction with `index` at
/// `address`.
pub fn new_instr<T: Into<TidAddress> + Display + ?Sized>(address: T, index: u64) -> Self {
pub fn new_instr<T: Into<TidAddress> + Display>(address: T, index: u64) -> Self {
Tid::new_instr_with_suffix::<_, &str>(address, index, None)
}

Expand All @@ -149,7 +149,7 @@ impl Tid {
/// `address`.
pub fn new_instr_with_suffix<T, U>(address: T, index: u64, suffix: Option<&U>) -> Self
where
T: Display + Into<TidAddress> + ?Sized,
T: Display + Into<TidAddress>,
U: Display + ?Sized,
{
match suffix {
Expand Down
22 changes: 17 additions & 5 deletions src/cwe_checker_lib/src/utils/debug.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
//! Little helpers for developers that try to understand what their code is
//! doing.
#![allow(dead_code)]
#![allow(missing_docs)]

use std::path::PathBuf;

#[derive(PartialEq, Eq, Copy, Clone, Debug, Default)]
/// Stages of the analysis that can be debugged separately.
#[non_exhaustive]
pub enum Stage {
/// No stages.
#[default]
No,
/// All stages.
All,
/// Construction of whole-program call graph.
CallGraph,
Expand Down Expand Up @@ -75,19 +74,22 @@ pub enum IrForm {
/// Substages of the Pcode transformation that can be debugged separately.
#[non_exhaustive]
pub enum PcodeForm {
/// The JSON string that comes from the Ghidra plugin.
/// JSON string that comes from the Ghidra plugin.
Raw,
/// JSON deserialized into Rust types.
Parsed,
Processed,
}

#[derive(PartialEq, Eq, Copy, Clone, Debug, Default)]
/// Controls generation of log messages.
#[non_exhaustive]
pub enum Verbosity {
/// Print no log messages.
Quiet,
/// Print warning and error-level log messages.
#[default]
Normal,
/// Print extra log messages.
Verbose,
}

Expand All @@ -96,9 +98,12 @@ pub enum Verbosity {
/// interest.
#[non_exhaustive]
pub enum TerminationPolicy {
/// Continue.
KeepRunning,
/// Exit.
#[default]
EarlyExit,
/// Panic.
Panic,
}

Expand All @@ -111,34 +116,40 @@ pub struct Settings {
saved_pcode_raw: Option<PathBuf>,
}

/// Builder for debug [`Settings`].
#[derive(PartialEq, Eq, Clone, Default, Debug)]
pub struct SettingsBuilder {
inner: Settings,
}

impl SettingsBuilder {
/// Constructs the final settings.
pub fn build(self) -> Settings {
self.inner
}

/// Sets the stage that is being debugged.
pub fn set_stage(mut self, stage: Stage) -> Self {
self.inner.stage = stage;

self
}

/// Sets the verbosity level.
pub fn set_verbosity(mut self, verbosity: Verbosity) -> Self {
self.inner.verbose = verbosity;

self
}

/// Sets the termination policy.
pub fn set_termination_policy(mut self, policy: TerminationPolicy) -> Self {
self.inner.terminate = policy;

self
}

/// Sets the path to the file with the saved output of the Ghidra plugin.
pub fn set_saved_pcode_raw(mut self, saved_pcode_raw: PathBuf) -> Self {
self.inner.saved_pcode_raw = Some(saved_pcode_raw);

Expand All @@ -147,6 +158,7 @@ impl SettingsBuilder {
}

impl Settings {
/// Returns the path to the file with the saved output of the Ghidra plugin.
pub fn get_saved_pcode_raw(&self) -> Option<PathBuf> {
self.saved_pcode_raw.clone()
}
Expand Down
4 changes: 2 additions & 2 deletions src/cwe_checker_lib/src/utils/ghidra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ pub fn get_project_from_ghidra(
)
}

/// Normalize the given P-Code project
/// and then parse it into a project struct of the internally used intermediate representation.
/// Normalize the given P-Code project and then parse it into a project struct
/// of the internally used intermediate representation.
pub fn parse_pcode_project_to_ir_project(
pcode_project: PcodeProject,
binary: &[u8],
Expand Down

0 comments on commit ef3016b

Please sign in to comment.