Compare commits

..

23 Commits

Author SHA1 Message Date
e4f97adbdd Version 0.6.1 2023-11-22 00:11:33 -05:00
0ec7bf078b Highlight: Consider reg offsets and signed immediates equivalent
Fixes #32
2023-11-22 00:07:21 -05:00
74e89130a8 Repaint rework: more responsive, less energy
Previously, we repainted every frame on Windows at full refresh rate.
This is an enormous waste, as the UI will be static most of the time.
This was to work around a bug with `rfd` + `eframe`.
On other platforms, we only repainted every frame when a job was running,
which was better, but still not ideal. We also had a 100ms deadline, so
we'd repaint at ~10fps minimum to catch new events (file watcher, jobs).

This removes all repaint logic from the main loop and moves it into the
individual places where we change state from another thread.
For example, the file watcher thread will now immediately notify egui
to repaint, rather than relying on the 100ms deadline we had previously.
Jobs, when updating their status, also notify egui to repaint.

For `rfd` file dialogs, this migrates to using the async API built on top of
a polling thread + `pollster`. This interacts better with `eframe` on Windows.
Overall, this should reduce repaints and improve responsiveness to
file changes and background tasks.
2023-11-21 14:34:26 -05:00
236e4d8d26 CI updates, update deny.toml, clippy fix 2023-11-21 12:16:15 -05:00
b900ae5a00 Disable WSL integration
With WSL, objdiff is unable to get filesystem notifications.
It's recommended to run objdiff natively on Windows, so having this option
is more confusing than useful.
2023-11-21 12:15:41 -05:00
261e1b8e07 Upgrade all dependencies 2023-11-21 11:57:02 -05:00
a29e913b45 Add "Incomplete" filter to object tree
Allows filtering out objects marked as "complete".
2023-11-21 11:50:11 -05:00
49257dc73c Better logic to reload previous file on app start
Before, if "Rebuild on changes" was disabled, the last file
wouldn't be properly loaded when starting.
2023-11-21 11:49:26 -05:00
dc9eec66b0 Configurable diff algorithms & new default algorithm
Uses the similar crate to support new diff algorithms:
- Patience (new default)
- Levenshtein (old default)
- Myers
- LCS (Longest Common Subsequence)

Options in "Diff Options" -> "Algorithm..."
2023-11-21 11:48:18 -05:00
7b58f9a269 Adjust "Diffable" to exclude missing target objects 2023-10-09 12:47:22 -04:00
d9e7dacb6d Version 0.5.1 2023-10-07 14:49:01 -04:00
04b4fdcd21 Reload objects when changed externally
Uses file modification timestamp polling for project config and objects to avoid unneeded complexity from the filesystem notification watcher.

Allows disabling `build_base` as well for projects using an external build system.
2023-10-07 14:48:34 -04:00
803eaafee6 Hide hidden symbols by default; add "Diff Options" to menu 2023-10-07 13:27:12 -04:00
e1dc84698f Restore context menu on highlightable fields
Fixes #30
2023-10-07 13:04:08 -04:00
e68629c339 Update ppc750cl (subi{,s,c} mnemonics, capstone-style CR bits) 2023-10-06 01:22:26 -04:00
bb9ff4b928 Update all dependencies 2023-10-05 23:55:01 -04:00
57392daaeb Implement click-to-highlight
Highlights registers, instructions, arguments, symbols or addresses on click.

Resolves #7
2023-10-05 23:40:45 -04:00
2dd3dd60a8 Update webpki (advisory fix) 2023-10-05 00:01:09 -04:00
f4757b8d92 Version 0.4.4
Add `#[serde(default)]` to new AppConfig field
2023-10-04 23:52:00 -04:00
52f8c5d4f9 Add "Recent Projects" to file menu 2023-10-03 13:52:16 -04:00
711f40b591 I forgot to bump the Cargo.toml version, oops 2023-09-10 00:24:53 -04:00
26932b2e44 Support min_version field in objdiff.json 2023-09-09 23:54:25 -04:00
192a06bc0b Project configuration improvements
- Support `completed` field for objects in project config. In object tree, displays red for incomplete, green for complete.
- Add support for one-sided diffs. A project can include objects without an associated source file for viewing.
- Add versioning to AppConfig, supporting upgrades without losing user configuration.
2023-09-09 23:43:12 -04:00
30 changed files with 3579 additions and 1923 deletions

View File

@@ -9,6 +9,7 @@ on:
workflow_dispatch:
env:
BUILD_PROFILE: release-lto
CARGO_BIN_NAME: objdiff
CARGO_TARGET_DIR: target
@@ -30,9 +31,25 @@ jobs:
with:
components: rustfmt, clippy
- name: Cargo check
run: cargo check --all-features
run: cargo check
- name: Cargo clippy
run: cargo clippy --all-features
run: cargo clippy
fmt:
name: Format
runs-on: ubuntu-latest
env:
RUSTFLAGS: -D warnings
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Rust toolchain
# We use nightly options in rustfmt.toml
uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
- name: Cargo fmt
run: cargo fmt --all --check
deny:
name: Deny
@@ -52,6 +69,7 @@ jobs:
test:
name: Test
if: 'false' # No tests yet
strategy:
matrix:
platform: [ ubuntu-latest, windows-latest, macos-latest ]
@@ -68,7 +86,7 @@ jobs:
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
- name: Cargo test
run: cargo test --release --all-features
run: cargo test --release
build:
name: Build
@@ -103,16 +121,16 @@ jobs:
with:
targets: ${{ matrix.target }}
- name: Cargo build
run: cargo build --release --all-features --target ${{ matrix.target }} --bin ${{ env.CARGO_BIN_NAME }}
run: cargo build --profile ${{ env.BUILD_PROFILE }} --target ${{ matrix.target }} --bin ${{ env.CARGO_BIN_NAME }}
- name: Upload artifacts
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.name }}
path: |
${{ env.CARGO_TARGET_DIR }}/release/${{ env.CARGO_BIN_NAME }}
${{ env.CARGO_TARGET_DIR }}/release/${{ env.CARGO_BIN_NAME }}.exe
${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/release/${{ env.CARGO_BIN_NAME }}
${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/release/${{ env.CARGO_BIN_NAME }}.exe
${{ env.CARGO_TARGET_DIR }}/${{ env.BUILD_PROFILE }}/${{ env.CARGO_BIN_NAME }}
${{ env.CARGO_TARGET_DIR }}/${{ env.BUILD_PROFILE }}/${{ env.CARGO_BIN_NAME }}.exe
${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/${{ env.BUILD_PROFILE }}/${{ env.CARGO_BIN_NAME }}
${{ env.CARGO_TARGET_DIR }}/${{ matrix.target }}/${{ env.BUILD_PROFILE }}/${{ env.CARGO_BIN_NAME }}.exe
if-no-files-found: error
release:
@@ -129,8 +147,8 @@ jobs:
working-directory: artifacts
run: |
mkdir ../out
for i in */*/release/$CARGO_BIN_NAME*; do
mv "$i" "../out/$(sed -E "s/([^/]+)\/[^/]+\/release\/($CARGO_BIN_NAME)/\2-\1/" <<< "$i")"
for i in */*/$BUILD_PROFILE/$CARGO_BIN_NAME*; do
mv "$i" "../out/$(sed -E "s/([^/]+)\/[^/]+\/$BUILD_PROFILE\/($CARGO_BIN_NAME)/\2-\1/" <<< "$i")"
done
ls -R ../out
- name: Release

1858
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,8 @@
[package]
name = "objdiff"
version = "0.4.1"
version = "0.6.1"
edition = "2021"
rust-version = "1.65"
rust-version = "1.70"
authors = ["Luke Street <luke@street.dev>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/encounter/objdiff"
@@ -13,53 +13,60 @@ A local diffing tool for decompilation projects.
publish = false
build = "build.rs"
[profile.release]
[profile.release-lto]
inherits = "release"
lto = "thin"
strip = "debuginfo"
[features]
default = []
wgpu = ["eframe/wgpu"]
wsl = []
[dependencies]
anyhow = "1.0.71"
byteorder = "1.4.3"
bytes = "1.4.0"
anyhow = "1.0.75"
byteorder = "1.5.0"
bytes = "1.5.0"
cfg-if = "1.0.0"
const_format = "0.2.31"
const_format = "0.2.32"
cwdemangle = "0.1.6"
dirs = "5.0.1"
eframe = { version = "0.22.0", features = ["persistence"] }
egui = "0.22.0"
egui_extras = "0.22.0"
flagset = "0.4.3"
eframe = { version = "0.23.0", features = ["persistence"] }
egui = "0.23.0"
egui_extras = "0.23.0"
filetime = "0.2.22"
flagset = "0.4.4"
globset = { version = "0.4.13", features = ["serde1"] }
log = "0.4.19"
memmap2 = "0.7.1"
notify = "6.0.1"
object = { version = "0.31.1", features = ["read_core", "std", "elf"], default-features = false }
png = "0.17.9"
ppc750cl = { git = "https://github.com/terorie/ppc750cl", rev = "9ae36eef34aa6d74e00972c7671f547a2acfd0aa" }
rabbitizer = "1.7.4"
rfd = { version = "0.11.4" } #, default-features = false, features = ['xdg-portal']
log = "0.4.20"
memmap2 = "0.9.0"
notify = "6.1.1"
object = { version = "0.32.1", features = ["read_core", "std", "elf"], default-features = false }
png = "0.17.10"
pollster = "0.3.0"
ppc750cl = { git = "https://github.com/encounter/ppc750cl", rev = "4a2bbbc6f84dcb76255ab6f3595a8d4a0ce96618" }
rabbitizer = "1.8.0"
rfd = { version = "0.12.1" } #, default-features = false, features = ['xdg-portal']
ron = "0.8.1"
semver = "1.0.20"
serde = { version = "1", features = ["derive"] }
serde_json = "1.0.104"
serde_yaml = "0.9.25"
tempfile = "3.6.0"
thiserror = "1.0.41"
time = { version = "0.3.22", features = ["formatting", "local-offset"] }
toml = "0.7.6"
serde_json = "1.0.108"
serde_yaml = "0.9.27"
similar = "2.3.0"
tempfile = "3.8.1"
thiserror = "1.0.50"
time = { version = "0.3.30", features = ["formatting", "local-offset"] }
toml = "0.8.8"
twox-hash = "1.6.3"
# For Linux static binaries, use rustls
[target.'cfg(target_os = "linux")'.dependencies]
reqwest = { version = "0.11.18", default-features = false, features = ["blocking", "json", "rustls"] }
self_update = { version = "0.37.0", default-features = false, features = ["rustls"] }
reqwest = { version = "0.11.22", default-features = false, features = ["blocking", "json", "rustls"] }
self_update = { version = "0.39.0", default-features = false, features = ["rustls"] }
# For all other platforms, use native TLS
[target.'cfg(not(target_os = "linux"))'.dependencies]
reqwest = "0.11.18"
self_update = "0.37.0"
reqwest = "0.11.22"
self_update = "0.39.0"
[target.'cfg(windows)'.dependencies]
path-slash = "0.2.1"
@@ -81,5 +88,5 @@ console_error_panic_hook = "0.1.7"
tracing-wasm = "0.2"
[build-dependencies]
anyhow = "1.0.71"
vergen = { version = "8.2.4", features = ["build", "cargo", "git", "gitcl"] }
anyhow = "1.0.75"
vergen = { version = "8.2.6", features = ["build", "cargo", "git", "gitcl"] }

View File

@@ -47,13 +47,7 @@ yanked = "warn"
notice = "warn"
# A list of advisory IDs to ignore. Note that ignored advisories will still
# output a note when they are encountered.
ignore = [
"RUSTSEC-2023-0022",
"RUSTSEC-2023-0023",
"RUSTSEC-2023-0024",
"RUSTSEC-2023-0034",
"RUSTSEC-2023-0044",
]
ignore = []
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
# lower than the range specified will be ignored. Note that ignored advisories
# will still output a note when they are encountered.
@@ -76,6 +70,7 @@ unlicensed = "deny"
allow = [
"MIT",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"ISC",
"BSD-2-Clause",
"BSD-3-Clause",
@@ -159,7 +154,7 @@ registries = [
# https://embarkstudios.github.io/cargo-deny/checks/bans/cfg.html
[bans]
# Lint level for when multiple versions of the same crate are detected
multiple-versions = "warn"
multiple-versions = "allow"
# Lint level for when a crate version requirement is `*`
wildcards = "allow"
# The graph highlighting used when creating dotgraphs for crates

View File

@@ -1,28 +1,36 @@
use std::{
default::Default,
fs,
path::{Path, PathBuf},
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex, RwLock,
},
time::Duration,
};
use globset::{Glob, GlobSet, GlobSetBuilder};
use filetime::FileTime;
use globset::{Glob, GlobSet};
use notify::{RecursiveMode, Watcher};
use time::UtcOffset;
use crate::{
config::{
build_globset, load_project_config, ProjectObject, ProjectObjectNode, CONFIG_FILENAMES,
app_config::{deserialize_config, AppConfigVersion},
config::{build_globset, load_project_config, ProjectObject, ProjectObjectNode},
diff::DiffAlg,
jobs::{
objdiff::{start_build, ObjDiffConfig},
Job, JobQueue, JobResult, JobStatus,
},
jobs::{objdiff::start_build, Job, JobQueue, JobResult, JobStatus},
views::{
appearance::{appearance_window, Appearance},
config::{config_ui, project_window, ConfigViewState},
config::{
config_ui, diff_options_window, project_window, ConfigViewState, DEFAULT_WATCH_PATTERNS,
},
data_diff::data_diff_ui,
debug::debug_window,
demangle::{demangle_window, DemangleViewState},
frame_history::FrameHistory,
function_diff::function_diff_ui,
jobs::jobs_ui,
symbol_diff::{symbol_diff_ui, DiffViewState, View},
@@ -35,36 +43,72 @@ pub struct ViewState {
pub config_state: ConfigViewState,
pub demangle_state: DemangleViewState,
pub diff_state: DiffViewState,
pub frame_history: FrameHistory,
pub show_appearance_config: bool,
pub show_demangle: bool,
pub show_project_config: bool,
pub show_diff_options: bool,
pub show_debug: bool,
}
/// The configuration for a single object file.
#[derive(Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct ObjectConfig {
pub name: String,
pub target_path: PathBuf,
pub base_path: PathBuf,
pub target_path: Option<PathBuf>,
pub base_path: Option<PathBuf>,
pub reverse_fn_order: Option<bool>,
pub complete: Option<bool>,
}
#[derive(Clone, Eq, PartialEq)]
pub struct ProjectConfigInfo {
pub path: PathBuf,
pub timestamp: FileTime,
}
#[inline]
fn bool_true() -> bool { true }
#[derive(Default, Clone, serde::Deserialize, serde::Serialize)]
#[inline]
fn default_watch_patterns() -> Vec<Glob> {
DEFAULT_WATCH_PATTERNS.iter().map(|s| Glob::new(s).unwrap()).collect()
}
#[derive(Clone, serde::Deserialize, serde::Serialize)]
pub struct AppConfig {
// TODO: https://github.com/ron-rs/ron/pull/455
// #[serde(flatten)]
// pub version: AppConfigVersion,
pub version: u32,
#[serde(default)]
pub custom_make: Option<String>,
#[serde(default)]
pub selected_wsl_distro: Option<String>,
#[serde(default)]
pub project_dir: Option<PathBuf>,
#[serde(default)]
pub target_obj_dir: Option<PathBuf>,
#[serde(default)]
pub base_obj_dir: Option<PathBuf>,
#[serde(default)]
pub selected_obj: Option<ObjectConfig>,
#[serde(default = "bool_true")]
pub build_base: bool,
#[serde(default)]
pub build_target: bool,
#[serde(default = "bool_true")]
pub rebuild_on_changes: bool,
#[serde(default)]
pub auto_update_check: bool,
#[serde(default = "default_watch_patterns")]
pub watch_patterns: Vec<Glob>,
#[serde(default)]
pub recent_projects: Vec<PathBuf>,
#[serde(default)]
pub code_alg: DiffAlg,
#[serde(default)]
pub data_alg: DiffAlg,
#[serde(skip)]
pub objects: Vec<ProjectObject>,
@@ -79,11 +123,48 @@ pub struct AppConfig {
#[serde(skip)]
pub queue_build: bool,
#[serde(skip)]
pub project_config_loaded: bool,
pub queue_reload: bool,
#[serde(skip)]
pub project_config_info: Option<ProjectConfigInfo>,
}
impl Default for AppConfig {
fn default() -> Self {
Self {
version: AppConfigVersion::default().version,
custom_make: None,
selected_wsl_distro: None,
project_dir: None,
target_obj_dir: None,
base_obj_dir: None,
selected_obj: None,
build_base: true,
build_target: false,
rebuild_on_changes: true,
auto_update_check: true,
watch_patterns: DEFAULT_WATCH_PATTERNS.iter().map(|s| Glob::new(s).unwrap()).collect(),
recent_projects: vec![],
code_alg: Default::default(),
data_alg: Default::default(),
objects: vec![],
object_nodes: vec![],
watcher_change: false,
config_change: false,
obj_change: false,
queue_build: false,
queue_reload: false,
project_config_info: None,
}
}
}
impl AppConfig {
pub fn set_project_dir(&mut self, path: PathBuf) {
self.recent_projects.retain(|p| p != &path);
if self.recent_projects.len() > 9 {
self.recent_projects.truncate(9);
}
self.recent_projects.insert(0, path.clone());
self.project_dir = Some(path);
self.target_obj_dir = None;
self.base_obj_dir = None;
@@ -95,7 +176,7 @@ impl AppConfig {
self.config_change = true;
self.obj_change = true;
self.queue_build = false;
self.project_config_loaded = false;
self.project_config_info = None;
}
pub fn set_target_obj_dir(&mut self, path: PathBuf) {
@@ -127,14 +208,13 @@ pub struct App {
view_state: ViewState,
config: AppConfigRef,
modified: Arc<AtomicBool>,
config_modified: Arc<AtomicBool>,
watcher: Option<notify::RecommendedWatcher>,
relaunch_path: Rc<Mutex<Option<PathBuf>>>,
should_relaunch: bool,
}
const APPEARANCE_KEY: &str = "appearance";
const CONFIG_KEY: &str = "app_config";
pub const APPEARANCE_KEY: &str = "appearance";
pub const CONFIG_KEY: &str = "app_config";
impl App {
/// Called once before the first frame.
@@ -153,11 +233,13 @@ impl App {
if let Some(appearance) = eframe::get_value::<Appearance>(storage, APPEARANCE_KEY) {
app.appearance = appearance;
}
if let Some(mut config) = eframe::get_value::<AppConfig>(storage, CONFIG_KEY) {
if let Some(mut config) = deserialize_config(storage) {
if config.project_dir.is_some() {
config.config_change = true;
config.watcher_change = true;
app.modified.store(true, Ordering::Relaxed);
}
if config.selected_obj.is_some() {
config.queue_build = true;
}
app.view_state.config_state.queue_check_update = config.auto_update_check;
app.config = Arc::new(RwLock::new(config));
@@ -178,7 +260,7 @@ impl App {
log::info!("Job {} finished", job.id);
match result {
JobResult::None => {
if let Some(err) = &job.status.read().unwrap().error {
if let Some(err) = &job.context.status.read().unwrap().error {
log::error!("{:?}", err);
}
}
@@ -199,12 +281,12 @@ impl App {
} else {
anyhow::Error::msg("Thread panicked")
};
let result = job.status.write();
let result = job.context.status.write();
if let Ok(mut guard) = result {
guard.error = Some(err);
} else {
drop(result);
job.status = Arc::new(RwLock::new(JobStatus {
job.context.status = Arc::new(RwLock::new(JobStatus {
title: "Error".to_string(),
progress_percent: 0.0,
progress_items: None,
@@ -219,23 +301,25 @@ impl App {
jobs.clear_finished();
diff_state.pre_update(jobs, &self.config);
config_state.pre_update(jobs);
config_state.pre_update(jobs, &self.config);
debug_assert!(jobs.results.is_empty());
}
fn post_update(&mut self) {
fn post_update(&mut self, ctx: &egui::Context) {
let ViewState { jobs, diff_state, config_state, .. } = &mut self.view_state;
config_state.post_update(jobs, &self.config);
diff_state.post_update(jobs, &self.config);
config_state.post_update(ctx, jobs, &self.config);
diff_state.post_update(&self.config);
let Ok(mut config) = self.config.write() else {
return;
};
let config = &mut *config;
if self.config_modified.swap(false, Ordering::Relaxed) {
if let Some(info) = &config.project_config_info {
if file_modified(&info.path, info.timestamp) {
config.config_change = true;
}
}
if config.config_change {
config.config_change = false;
@@ -252,22 +336,15 @@ impl App {
drop(self.watcher.take());
if let Some(project_dir) = &config.project_dir {
if !config.watch_patterns.is_empty() {
match build_globset(&config.watch_patterns)
match build_globset(&config.watch_patterns).map_err(anyhow::Error::new).and_then(
|globset| {
create_watcher(ctx.clone(), self.modified.clone(), project_dir, globset)
.map_err(anyhow::Error::new)
.and_then(|globset| {
create_watcher(
self.modified.clone(),
self.config_modified.clone(),
project_dir,
globset,
)
.map_err(anyhow::Error::new)
}) {
},
) {
Ok(watcher) => self.watcher = Some(watcher),
Err(e) => log::error!("Failed to create watcher: {e}"),
}
}
config.watcher_change = false;
}
}
@@ -284,11 +361,32 @@ impl App {
config.queue_build = true;
}
if let Some(result) = &diff_state.build {
if let Some(obj) = &result.first_obj {
if file_modified(&obj.path, obj.timestamp) {
config.queue_reload = true;
}
}
if let Some(obj) = &result.second_obj {
if file_modified(&obj.path, obj.timestamp) {
config.queue_reload = true;
}
}
}
// Don't clear `queue_build` if a build is running. A file may have been modified during
// the build, so we'll start another build after the current one finishes.
if config.queue_build && config.selected_obj.is_some() && !jobs.is_running(Job::ObjDiff) {
jobs.push(start_build(self.config.clone()));
jobs.push(start_build(ctx, ObjDiffConfig::from_config(config)));
config.queue_build = false;
config.queue_reload = false;
} else if config.queue_reload && !jobs.is_running(Job::ObjDiff) {
let mut diff_config = ObjDiffConfig::from_config(config);
// Don't build, just reload the current files
diff_config.build_base = false;
diff_config.build_target = false;
jobs.push(start_build(ctx, diff_config));
config.queue_reload = false;
}
}
}
@@ -309,17 +407,52 @@ impl eframe::App for App {
let ViewState {
jobs,
show_appearance_config,
demangle_state,
show_demangle,
diff_state,
config_state,
demangle_state,
diff_state,
frame_history,
show_appearance_config,
show_demangle,
show_project_config,
show_diff_options,
show_debug,
} = view_state;
frame_history.on_new_frame(ctx.input(|i| i.time), frame.info().cpu_usage);
egui::TopBottomPanel::top("top_panel").show(ctx, |ui| {
egui::menu::bar(ui, |ui| {
ui.menu_button("File", |ui| {
#[cfg(debug_assertions)]
if ui.button("Debug…").clicked() {
*show_debug = !*show_debug;
ui.close_menu();
}
if ui.button("Project…").clicked() {
*show_project_config = !*show_project_config;
ui.close_menu();
}
let recent_projects = if let Ok(guard) = config.read() {
guard.recent_projects.clone()
} else {
vec![]
};
if recent_projects.is_empty() {
ui.add_enabled(false, egui::Button::new("Recent projects…"));
} else {
ui.menu_button("Recent Projects…", |ui| {
if ui.button("Clear").clicked() {
config.write().unwrap().recent_projects.clear();
};
ui.separator();
for path in recent_projects {
if ui.button(format!("{}", path.display())).clicked() {
config.write().unwrap().set_project_dir(path);
ui.close_menu();
}
}
});
}
if ui.button("Appearance…").clicked() {
*show_appearance_config = !*show_appearance_config;
ui.close_menu();
@@ -334,6 +467,33 @@ impl eframe::App for App {
ui.close_menu();
}
});
ui.menu_button("Diff Options", |ui| {
if ui.button("Algorithm…").clicked() {
*show_diff_options = !*show_diff_options;
ui.close_menu();
}
let mut config = config.write().unwrap();
let response = ui
.checkbox(&mut config.rebuild_on_changes, "Rebuild on changes")
.on_hover_text("Automatically re-run the build & diff when files change.");
if response.changed() {
config.watcher_change = true;
};
ui.add_enabled(
!diff_state.symbol_state.disable_reverse_fn_order,
egui::Checkbox::new(
&mut diff_state.symbol_state.reverse_fn_order,
"Reverse function order (-inline deferred)",
),
)
.on_disabled_hover_text(
"Option disabled because it's set by the project configuration file.",
);
ui.checkbox(
&mut diff_state.symbol_state.show_hidden_symbols,
"Show hidden symbols",
);
});
});
});
@@ -362,16 +522,10 @@ impl eframe::App for App {
project_window(ctx, config, show_project_config, config_state, appearance);
appearance_window(ctx, show_appearance_config, appearance);
demangle_window(ctx, show_demangle, demangle_state, appearance);
diff_options_window(ctx, config, show_diff_options, appearance);
debug_window(ctx, show_debug, frame_history, appearance);
self.post_update();
// Windows + request_repaint_after breaks dialogs:
// https://github.com/emilk/egui/issues/2003
if cfg!(windows) || self.view_state.jobs.any_running() {
ctx.request_repaint();
} else {
ctx.request_repaint_after(Duration::from_millis(100));
}
self.post_update(ctx);
}
/// Called by the frame work to save state before shutdown.
@@ -384,17 +538,11 @@ impl eframe::App for App {
}
fn create_watcher(
ctx: egui::Context,
modified: Arc<AtomicBool>,
config_modified: Arc<AtomicBool>,
project_dir: &Path,
patterns: GlobSet,
) -> notify::Result<notify::RecommendedWatcher> {
let mut config_patterns = GlobSetBuilder::new();
for filename in CONFIG_FILENAMES {
config_patterns.add(Glob::new(filename).unwrap());
}
let config_patterns = config_patterns.build().unwrap();
let base_dir = project_dir.to_owned();
let mut watcher =
notify::recommended_watcher(move |res: notify::Result<notify::Event>| match res {
@@ -409,10 +557,10 @@ fn create_watcher(
let Ok(path) = path.strip_prefix(&base_dir) else {
continue;
};
if config_patterns.is_match(path) {
config_modified.store(true, Ordering::Relaxed);
} else if patterns.is_match(path) {
if patterns.is_match(path) {
log::info!("File modified: {}", path.display());
modified.store(true, Ordering::Relaxed);
ctx.request_repaint();
}
}
}
@@ -422,3 +570,12 @@ fn create_watcher(
watcher.watch(project_dir, RecursiveMode::Recursive)?;
Ok(watcher)
}
#[inline]
fn file_modified(path: &Path, last_ts: FileTime) -> bool {
if let Ok(metadata) = fs::metadata(path) {
FileTime::from_last_modification_time(&metadata) != last_ts
} else {
false
}
}

96
src/app_config.rs Normal file
View File

@@ -0,0 +1,96 @@
use std::path::PathBuf;
use eframe::Storage;
use globset::Glob;
use crate::app::{AppConfig, ObjectConfig, CONFIG_KEY};
#[derive(Clone, serde::Deserialize, serde::Serialize)]
pub struct AppConfigVersion {
pub version: u32,
}
impl Default for AppConfigVersion {
fn default() -> Self { Self { version: 1 } }
}
/// Deserialize the AppConfig from storage, handling upgrades from older versions.
pub fn deserialize_config(storage: &dyn Storage) -> Option<AppConfig> {
let str = storage.get_string(CONFIG_KEY)?;
match ron::from_str::<AppConfigVersion>(&str) {
Ok(version) => match version.version {
1 => from_str::<AppConfig>(&str),
_ => {
log::warn!("Unknown config version: {}", version.version);
None
}
},
Err(e) => {
log::warn!("Failed to decode config version: {e}");
// Try to decode as v0
from_str::<AppConfigV0>(&str).map(|c| c.into_config())
}
}
}
fn from_str<T>(str: &str) -> Option<T>
where T: serde::de::DeserializeOwned {
match ron::from_str(str) {
Ok(config) => Some(config),
Err(err) => {
log::warn!("Failed to decode config: {err}");
None
}
}
}
#[derive(serde::Deserialize, serde::Serialize)]
pub struct ObjectConfigV0 {
pub name: String,
pub target_path: PathBuf,
pub base_path: PathBuf,
pub reverse_fn_order: Option<bool>,
}
impl ObjectConfigV0 {
fn into_config(self) -> ObjectConfig {
ObjectConfig {
name: self.name,
target_path: Some(self.target_path),
base_path: Some(self.base_path),
reverse_fn_order: self.reverse_fn_order,
complete: None,
}
}
}
#[derive(serde::Deserialize, serde::Serialize)]
pub struct AppConfigV0 {
pub custom_make: Option<String>,
pub selected_wsl_distro: Option<String>,
pub project_dir: Option<PathBuf>,
pub target_obj_dir: Option<PathBuf>,
pub base_obj_dir: Option<PathBuf>,
pub selected_obj: Option<ObjectConfigV0>,
pub build_target: bool,
pub auto_update_check: bool,
pub watch_patterns: Vec<Glob>,
}
impl AppConfigV0 {
fn into_config(self) -> AppConfig {
log::info!("Upgrading configuration from v0");
AppConfig {
custom_make: self.custom_make,
selected_wsl_distro: self.selected_wsl_distro,
project_dir: self.project_dir,
target_obj_dir: self.target_obj_dir,
base_obj_dir: self.base_obj_dir,
selected_obj: self.selected_obj.map(|obj| obj.into_config()),
build_target: self.build_target,
auto_update_check: self.auto_update_check,
watch_patterns: self.watch_patterns,
..Default::default()
}
}
}

View File

@@ -1,32 +1,55 @@
use std::{
fs::File,
io::Read,
path::{Component, Path, PathBuf},
};
use anyhow::{Context, Result};
use anyhow::{bail, Result};
use filetime::FileTime;
use globset::{Glob, GlobSet, GlobSetBuilder};
use crate::{app::AppConfig, views::config::DEFAULT_WATCH_PATTERNS};
use crate::{
app::{AppConfig, ProjectConfigInfo},
views::config::DEFAULT_WATCH_PATTERNS,
};
#[inline]
fn bool_true() -> bool { true }
#[derive(Default, Clone, serde::Deserialize)]
#[serde(default)]
pub struct ProjectConfig {
#[serde(default)]
pub min_version: Option<String>,
#[serde(default)]
pub custom_make: Option<String>,
#[serde(default)]
pub target_dir: Option<PathBuf>,
#[serde(default)]
pub base_dir: Option<PathBuf>,
#[serde(default = "bool_true")]
pub build_base: bool,
#[serde(default)]
pub build_target: bool,
#[serde(default)]
pub watch_patterns: Option<Vec<Glob>>,
#[serde(alias = "units")]
#[serde(default, alias = "units")]
pub objects: Vec<ProjectObject>,
}
#[derive(Default, Clone, serde::Deserialize)]
pub struct ProjectObject {
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub path: Option<PathBuf>,
#[serde(default)]
pub target_path: Option<PathBuf>,
#[serde(default)]
pub base_path: Option<PathBuf>,
#[serde(default)]
pub reverse_fn_order: Option<bool>,
#[serde(default)]
pub complete: Option<bool>,
}
impl ProjectObject {
@@ -118,11 +141,20 @@ pub fn load_project_config(config: &mut AppConfig) -> Result<()> {
let Some(project_dir) = &config.project_dir else {
return Ok(());
};
if let Some(result) = try_project_config(project_dir) {
if let Some((result, info)) = try_project_config(project_dir) {
let project_config = result?;
if let Some(min_version) = &project_config.min_version {
let version_str = env!("CARGO_PKG_VERSION");
let version = semver::Version::parse(version_str).unwrap();
let version_req = semver::VersionReq::parse(&format!(">={min_version}"))?;
if !version_req.matches(&version) {
bail!("Project requires objdiff version {} or higher", min_version);
}
}
config.custom_make = project_config.custom_make;
config.target_obj_dir = project_config.target_dir.map(|p| project_dir.join(p));
config.base_obj_dir = project_config.base_dir.map(|p| project_dir.join(p));
config.build_base = project_config.build_base;
config.build_target = project_config.build_target;
config.watch_patterns = project_config.watch_patterns.unwrap_or_else(|| {
DEFAULT_WATCH_PATTERNS.iter().map(|s| Glob::new(s).unwrap()).collect()
@@ -131,34 +163,39 @@ pub fn load_project_config(config: &mut AppConfig) -> Result<()> {
config.objects = project_config.objects;
config.object_nodes =
build_nodes(&config.objects, project_dir, &config.target_obj_dir, &config.base_obj_dir);
config.project_config_loaded = true;
config.project_config_info = Some(info);
}
Ok(())
}
fn try_project_config(dir: &Path) -> Option<Result<ProjectConfig>> {
fn try_project_config(dir: &Path) -> Option<(Result<ProjectConfig>, ProjectConfigInfo)> {
for filename in CONFIG_FILENAMES.iter() {
let config_path = dir.join(filename);
if config_path.is_file() {
return match filename.contains("json") {
true => Some(read_json_config(&config_path)),
false => Some(read_yml_config(&config_path)),
let Ok(mut file) = File::open(&config_path) else {
continue;
};
let metadata = file.metadata();
if let Ok(metadata) = metadata {
if !metadata.is_file() {
continue;
}
let ts = FileTime::from_last_modification_time(&metadata);
let config = match filename.contains("json") {
true => read_json_config(&mut file),
false => read_yml_config(&mut file),
};
return Some((config, ProjectConfigInfo { path: config_path, timestamp: ts }));
}
}
None
}
fn read_yml_config(config_path: &Path) -> Result<ProjectConfig> {
let mut reader = File::open(config_path)
.with_context(|| format!("Failed to open config file '{}'", config_path.display()))?;
Ok(serde_yaml::from_reader(&mut reader)?)
fn read_yml_config<R: Read>(reader: &mut R) -> Result<ProjectConfig> {
Ok(serde_yaml::from_reader(reader)?)
}
fn read_json_config(config_path: &Path) -> Result<ProjectConfig> {
let mut reader = File::open(config_path)
.with_context(|| format!("Failed to open config file '{}'", config_path.display()))?;
Ok(serde_json::from_reader(&mut reader)?)
fn read_json_config<R: Read>(reader: &mut R) -> Result<ProjectConfig> {
Ok(serde_json::from_reader(reader)?)
}
pub fn build_globset(vec: &[Glob]) -> std::result::Result<GlobSet, globset::Error> {

View File

@@ -1,712 +0,0 @@
use std::{collections::BTreeMap, mem::take};
use anyhow::Result;
use crate::{
editops::{editops_find, LevEditType},
obj::{
mips, ppc, ObjArchitecture, ObjDataDiff, ObjDataDiffKind, ObjInfo, ObjInsArg,
ObjInsArgDiff, ObjInsBranchFrom, ObjInsBranchTo, ObjInsDiff, ObjInsDiffKind, ObjReloc,
ObjSection, ObjSectionKind, ObjSymbol, ObjSymbolFlags,
},
};
fn no_diff_code(
arch: ObjArchitecture,
data: &[u8],
symbol: &mut ObjSymbol,
relocs: &[ObjReloc],
line_info: &Option<BTreeMap<u32, u32>>,
) -> Result<()> {
let code =
&data[symbol.section_address as usize..(symbol.section_address + symbol.size) as usize];
let (_, ins) = match arch {
ObjArchitecture::PowerPc => ppc::process_code(code, symbol.address, relocs, line_info)?,
ObjArchitecture::Mips => mips::process_code(
code,
symbol.address,
symbol.address + symbol.size,
relocs,
line_info,
)?,
};
let mut diff = Vec::<ObjInsDiff>::new();
for i in ins {
diff.push(ObjInsDiff { ins: Some(i), kind: ObjInsDiffKind::None, ..Default::default() });
}
resolve_branches(&mut diff);
symbol.instructions = diff;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn diff_code(
arch: ObjArchitecture,
left_data: &[u8],
right_data: &[u8],
left_symbol: &mut ObjSymbol,
right_symbol: &mut ObjSymbol,
left_relocs: &[ObjReloc],
right_relocs: &[ObjReloc],
left_line_info: &Option<BTreeMap<u32, u32>>,
right_line_info: &Option<BTreeMap<u32, u32>>,
) -> Result<()> {
let left_code = &left_data[left_symbol.section_address as usize
..(left_symbol.section_address + left_symbol.size) as usize];
let right_code = &right_data[right_symbol.section_address as usize
..(right_symbol.section_address + right_symbol.size) as usize];
let ((left_ops, left_insts), (right_ops, right_insts)) = match arch {
ObjArchitecture::PowerPc => (
ppc::process_code(left_code, left_symbol.address, left_relocs, left_line_info)?,
ppc::process_code(right_code, right_symbol.address, right_relocs, right_line_info)?,
),
ObjArchitecture::Mips => (
mips::process_code(
left_code,
left_symbol.address,
left_symbol.address + left_symbol.size,
left_relocs,
left_line_info,
)?,
mips::process_code(
right_code,
right_symbol.address,
left_symbol.address + left_symbol.size,
right_relocs,
right_line_info,
)?,
),
};
let mut left_diff = Vec::<ObjInsDiff>::new();
let mut right_diff = Vec::<ObjInsDiff>::new();
let edit_ops = editops_find(&left_ops, &right_ops);
{
let mut op_iter = edit_ops.iter();
let mut left_iter = left_insts.iter();
let mut right_iter = right_insts.iter();
let mut cur_op = op_iter.next();
let mut cur_left = left_iter.next();
let mut cur_right = right_iter.next();
while let Some(op) = cur_op {
let left_addr = op.first_start as u32 * 4;
let right_addr = op.second_start as u32 * 4;
while let (Some(left), Some(right)) = (cur_left, cur_right) {
if (left.address - left_symbol.address as u32) < left_addr {
left_diff.push(ObjInsDiff { ins: Some(left.clone()), ..ObjInsDiff::default() });
right_diff
.push(ObjInsDiff { ins: Some(right.clone()), ..ObjInsDiff::default() });
} else {
break;
}
cur_left = left_iter.next();
cur_right = right_iter.next();
}
if let (Some(left), Some(right)) = (cur_left, cur_right) {
if (left.address - left_symbol.address as u32) != left_addr {
return Err(anyhow::Error::msg("Instruction address mismatch (left)"));
}
if (right.address - right_symbol.address as u32) != right_addr {
return Err(anyhow::Error::msg("Instruction address mismatch (right)"));
}
match op.op_type {
LevEditType::Replace => {
left_diff
.push(ObjInsDiff { ins: Some(left.clone()), ..ObjInsDiff::default() });
right_diff
.push(ObjInsDiff { ins: Some(right.clone()), ..ObjInsDiff::default() });
cur_left = left_iter.next();
cur_right = right_iter.next();
}
LevEditType::Insert => {
left_diff.push(ObjInsDiff::default());
right_diff
.push(ObjInsDiff { ins: Some(right.clone()), ..ObjInsDiff::default() });
cur_right = right_iter.next();
}
LevEditType::Delete => {
left_diff
.push(ObjInsDiff { ins: Some(left.clone()), ..ObjInsDiff::default() });
right_diff.push(ObjInsDiff::default());
cur_left = left_iter.next();
}
}
} else {
break;
}
cur_op = op_iter.next();
}
// Finalize
while cur_left.is_some() || cur_right.is_some() {
left_diff.push(ObjInsDiff { ins: cur_left.cloned(), ..ObjInsDiff::default() });
right_diff.push(ObjInsDiff { ins: cur_right.cloned(), ..ObjInsDiff::default() });
cur_left = left_iter.next();
cur_right = right_iter.next();
}
}
resolve_branches(&mut left_diff);
resolve_branches(&mut right_diff);
let mut diff_state = InsDiffState::default();
for (left, right) in left_diff.iter_mut().zip(right_diff.iter_mut()) {
let result = compare_ins(left, right, &mut diff_state)?;
left.kind = result.kind;
right.kind = result.kind;
left.arg_diff = result.left_args_diff;
right.arg_diff = result.right_args_diff;
}
let total = left_insts.len();
let percent = if diff_state.diff_count >= total {
0.0
} else {
((total - diff_state.diff_count) as f32 / total as f32) * 100.0
};
left_symbol.match_percent = Some(percent);
right_symbol.match_percent = Some(percent);
left_symbol.instructions = left_diff;
right_symbol.instructions = right_diff;
Ok(())
}
fn resolve_branches(vec: &mut [ObjInsDiff]) {
let mut branch_idx = 0usize;
// Map addresses to indices
let mut addr_map = BTreeMap::<u32, usize>::new();
for (i, ins_diff) in vec.iter().enumerate() {
if let Some(ins) = &ins_diff.ins {
addr_map.insert(ins.address, i);
}
}
// Generate branches
let mut branches = BTreeMap::<usize, ObjInsBranchFrom>::new();
for (i, ins_diff) in vec.iter_mut().enumerate() {
if let Some(ins) = &ins_diff.ins {
// if ins.ins.is_blr() || ins.reloc.is_some() {
// continue;
// }
if let Some(ins_idx) = ins
.args
.iter()
.find_map(|a| if let ObjInsArg::BranchOffset(offs) = a { Some(offs) } else { None })
.and_then(|offs| addr_map.get(&((ins.address as i32 + offs) as u32)))
{
if let Some(branch) = branches.get_mut(ins_idx) {
ins_diff.branch_to =
Some(ObjInsBranchTo { ins_idx: *ins_idx, branch_idx: branch.branch_idx });
branch.ins_idx.push(i);
} else {
ins_diff.branch_to = Some(ObjInsBranchTo { ins_idx: *ins_idx, branch_idx });
branches.insert(*ins_idx, ObjInsBranchFrom { ins_idx: vec![i], branch_idx });
branch_idx += 1;
}
}
}
}
// Store branch from
for (i, branch) in branches {
vec[i].branch_from = Some(branch);
}
}
fn address_eq(left: &ObjSymbol, right: &ObjSymbol) -> bool {
left.address as i64 + left.addend == right.address as i64 + right.addend
}
fn reloc_eq(left_reloc: Option<&ObjReloc>, right_reloc: Option<&ObjReloc>) -> bool {
let (Some(left), Some(right)) = (left_reloc, right_reloc) else {
return false;
};
if left.kind != right.kind {
return false;
}
let name_matches = left.target.name == right.target.name;
match (&left.target_section, &right.target_section) {
(Some(sl), Some(sr)) => {
// Match if section and name or address match
sl == sr && (name_matches || address_eq(&left.target, &right.target))
}
(Some(_), None) => false,
(None, Some(_)) => {
// Match if possibly stripped weak symbol
name_matches && right.target.flags.0.contains(ObjSymbolFlags::Weak)
}
(None, None) => name_matches,
}
}
fn arg_eq(
left: &ObjInsArg,
right: &ObjInsArg,
left_diff: &ObjInsDiff,
right_diff: &ObjInsDiff,
) -> bool {
return match left {
ObjInsArg::PpcArg(l) => match right {
ObjInsArg::PpcArg(r) => format!("{l}") == format!("{r}"),
_ => false,
},
ObjInsArg::Reloc => {
matches!(right, ObjInsArg::Reloc)
&& reloc_eq(
left_diff.ins.as_ref().and_then(|i| i.reloc.as_ref()),
right_diff.ins.as_ref().and_then(|i| i.reloc.as_ref()),
)
}
ObjInsArg::RelocWithBase => {
matches!(right, ObjInsArg::RelocWithBase)
&& reloc_eq(
left_diff.ins.as_ref().and_then(|i| i.reloc.as_ref()),
right_diff.ins.as_ref().and_then(|i| i.reloc.as_ref()),
)
}
ObjInsArg::MipsArg(ls) | ObjInsArg::MipsArgWithBase(ls) => {
matches!(right, ObjInsArg::MipsArg(rs) | ObjInsArg::MipsArgWithBase(rs) if ls == rs)
}
ObjInsArg::BranchOffset(_) => {
// Compare dest instruction idx after diffing
left_diff.branch_to.as_ref().map(|b| b.ins_idx)
== right_diff.branch_to.as_ref().map(|b| b.ins_idx)
}
};
}
#[derive(Default)]
struct InsDiffState {
diff_count: usize,
left_arg_idx: usize,
right_arg_idx: usize,
left_args_idx: BTreeMap<String, usize>,
right_args_idx: BTreeMap<String, usize>,
}
#[derive(Default)]
struct InsDiffResult {
kind: ObjInsDiffKind,
left_args_diff: Vec<Option<ObjInsArgDiff>>,
right_args_diff: Vec<Option<ObjInsArgDiff>>,
}
fn compare_ins(
left: &ObjInsDiff,
right: &ObjInsDiff,
state: &mut InsDiffState,
) -> Result<InsDiffResult> {
let mut result = InsDiffResult::default();
if let (Some(left_ins), Some(right_ins)) = (&left.ins, &right.ins) {
if left_ins.args.len() != right_ins.args.len() || left_ins.op != right_ins.op {
// Totally different op
result.kind = ObjInsDiffKind::Replace;
state.diff_count += 1;
return Ok(result);
}
if left_ins.mnemonic != right_ins.mnemonic {
// Same op but different mnemonic, still cmp args
result.kind = ObjInsDiffKind::OpMismatch;
state.diff_count += 1;
}
for (a, b) in left_ins.args.iter().zip(&right_ins.args) {
if arg_eq(a, b, left, right) {
result.left_args_diff.push(None);
result.right_args_diff.push(None);
} else {
if result.kind == ObjInsDiffKind::None {
result.kind = ObjInsDiffKind::ArgMismatch;
state.diff_count += 1;
}
let a_str = match a {
ObjInsArg::PpcArg(arg) => format!("{arg}"),
ObjInsArg::Reloc | ObjInsArg::RelocWithBase => String::new(),
ObjInsArg::MipsArg(str) | ObjInsArg::MipsArgWithBase(str) => str.clone(),
ObjInsArg::BranchOffset(arg) => format!("{arg}"),
};
let a_diff = if let Some(idx) = state.left_args_idx.get(&a_str) {
ObjInsArgDiff { idx: *idx }
} else {
let idx = state.left_arg_idx;
state.left_args_idx.insert(a_str, idx);
state.left_arg_idx += 1;
ObjInsArgDiff { idx }
};
let b_str = match b {
ObjInsArg::PpcArg(arg) => format!("{arg}"),
ObjInsArg::Reloc | ObjInsArg::RelocWithBase => String::new(),
ObjInsArg::MipsArg(str) | ObjInsArg::MipsArgWithBase(str) => str.clone(),
ObjInsArg::BranchOffset(arg) => format!("{arg}"),
};
let b_diff = if let Some(idx) = state.right_args_idx.get(&b_str) {
ObjInsArgDiff { idx: *idx }
} else {
let idx = state.right_arg_idx;
state.right_args_idx.insert(b_str, idx);
state.right_arg_idx += 1;
ObjInsArgDiff { idx }
};
result.left_args_diff.push(Some(a_diff));
result.right_args_diff.push(Some(b_diff));
}
}
} else if left.ins.is_some() {
result.kind = ObjInsDiffKind::Delete;
state.diff_count += 1;
} else {
result.kind = ObjInsDiffKind::Insert;
state.diff_count += 1;
}
Ok(result)
}
fn find_section_and_symbol(obj: &ObjInfo, name: &str) -> Option<(usize, usize)> {
for (section_idx, section) in obj.sections.iter().enumerate() {
let symbol_idx = match section.symbols.iter().position(|symbol| symbol.name == name) {
Some(symbol_idx) => symbol_idx,
None => continue,
};
return Some((section_idx, symbol_idx));
}
None
}
pub fn diff_objs(left: &mut ObjInfo, right: &mut ObjInfo) -> Result<()> {
for left_section in &mut left.sections {
if left_section.kind == ObjSectionKind::Code {
for left_symbol in &mut left_section.symbols {
if let Some((right_section_idx, right_symbol_idx)) =
find_section_and_symbol(right, &left_symbol.name)
{
let right_section = &mut right.sections[right_section_idx];
let right_symbol = &mut right_section.symbols[right_symbol_idx];
left_symbol.diff_symbol = Some(right_symbol.name.clone());
right_symbol.diff_symbol = Some(left_symbol.name.clone());
diff_code(
left.architecture,
&left_section.data,
&right_section.data,
left_symbol,
right_symbol,
&left_section.relocations,
&right_section.relocations,
&left.line_info,
&right.line_info,
)?;
} else {
no_diff_code(
left.architecture,
&left_section.data,
left_symbol,
&left_section.relocations,
&left.line_info,
)?;
}
}
} else {
let Some(right_section) =
right.sections.iter_mut().find(|s| s.name == left_section.name)
else {
continue;
};
if left_section.kind == ObjSectionKind::Data {
diff_data(left_section, right_section);
// diff_data_symbols(left_section, right_section)?;
} else if left_section.kind == ObjSectionKind::Bss {
diff_bss_symbols(&mut left_section.symbols, &mut right_section.symbols)?;
}
}
}
for right_section in right.sections.iter_mut().filter(|s| s.kind == ObjSectionKind::Code) {
for right_symbol in &mut right_section.symbols {
if right_symbol.instructions.is_empty() {
no_diff_code(
right.architecture,
&right_section.data,
right_symbol,
&right_section.relocations,
&right.line_info,
)?;
}
}
}
diff_bss_symbols(&mut left.common, &mut right.common)?;
Ok(())
}
fn diff_bss_symbols(left_symbols: &mut [ObjSymbol], right_symbols: &mut [ObjSymbol]) -> Result<()> {
for left_symbol in left_symbols {
if let Some(right_symbol) = right_symbols.iter_mut().find(|s| s.name == left_symbol.name) {
left_symbol.diff_symbol = Some(right_symbol.name.clone());
right_symbol.diff_symbol = Some(left_symbol.name.clone());
let percent = if left_symbol.size == right_symbol.size { 100.0 } else { 50.0 };
left_symbol.match_percent = Some(percent);
right_symbol.match_percent = Some(percent);
}
}
Ok(())
}
// WIP diff-by-symbol
#[allow(dead_code)]
fn diff_data_symbols(left: &mut ObjSection, right: &mut ObjSection) -> Result<()> {
let mut left_ops = Vec::<u32>::with_capacity(left.symbols.len());
let mut right_ops = Vec::<u32>::with_capacity(right.symbols.len());
for left_symbol in &left.symbols {
let data = &left.data
[left_symbol.address as usize..(left_symbol.address + left_symbol.size) as usize];
let hash = twox_hash::xxh3::hash64(data);
left_ops.push(hash as u32);
}
for symbol in &right.symbols {
let data = &right.data[symbol.address as usize..(symbol.address + symbol.size) as usize];
let hash = twox_hash::xxh3::hash64(data);
right_ops.push(hash as u32);
}
let edit_ops = editops_find(&left_ops, &right_ops);
if edit_ops.is_empty() && !left.data.is_empty() {
let mut left_iter = left.symbols.iter_mut();
let mut right_iter = right.symbols.iter_mut();
loop {
let (left_symbol, right_symbol) = match (left_iter.next(), right_iter.next()) {
(Some(l), Some(r)) => (l, r),
(None, None) => break,
_ => return Err(anyhow::Error::msg("L/R mismatch in diff_data_symbols")),
};
let left_data = &left.data
[left_symbol.address as usize..(left_symbol.address + left_symbol.size) as usize];
let right_data = &right.data[right_symbol.address as usize
..(right_symbol.address + right_symbol.size) as usize];
left.data_diff.push(ObjDataDiff {
data: left_data.to_vec(),
kind: ObjDataDiffKind::None,
len: left_symbol.size as usize,
symbol: left_symbol.name.clone(),
});
right.data_diff.push(ObjDataDiff {
data: right_data.to_vec(),
kind: ObjDataDiffKind::None,
len: right_symbol.size as usize,
symbol: right_symbol.name.clone(),
});
left_symbol.diff_symbol = Some(right_symbol.name.clone());
left_symbol.match_percent = Some(100.0);
right_symbol.diff_symbol = Some(left_symbol.name.clone());
right_symbol.match_percent = Some(100.0);
}
return Ok(());
}
Ok(())
}
fn diff_data(left: &mut ObjSection, right: &mut ObjSection) {
let edit_ops = editops_find(&left.data, &right.data);
if edit_ops.is_empty() && !left.data.is_empty() {
left.data_diff = vec![ObjDataDiff {
data: left.data.clone(),
kind: ObjDataDiffKind::None,
len: left.data.len(),
symbol: String::new(),
}];
right.data_diff = vec![ObjDataDiff {
data: right.data.clone(),
kind: ObjDataDiffKind::None,
len: right.data.len(),
symbol: String::new(),
}];
return;
}
let mut left_diff = Vec::<ObjDataDiff>::new();
let mut right_diff = Vec::<ObjDataDiff>::new();
let mut left_cur = 0usize;
let mut right_cur = 0usize;
let mut cur_op = LevEditType::Replace;
let mut cur_left_data = Vec::<u8>::new();
let mut cur_right_data = Vec::<u8>::new();
for op in edit_ops {
if cur_op != op.op_type || left_cur < op.first_start || right_cur < op.second_start {
match cur_op {
LevEditType::Replace => {
let left_data = take(&mut cur_left_data);
let right_data = take(&mut cur_right_data);
let left_data_len = left_data.len();
let right_data_len = right_data.len();
left_diff.push(ObjDataDiff {
data: left_data,
kind: ObjDataDiffKind::Replace,
len: left_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: right_data,
kind: ObjDataDiffKind::Replace,
len: right_data_len,
symbol: String::new(),
});
}
LevEditType::Insert => {
let right_data = take(&mut cur_right_data);
let right_data_len = right_data.len();
left_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Insert,
len: right_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: right_data,
kind: ObjDataDiffKind::Insert,
len: right_data_len,
symbol: String::new(),
});
}
LevEditType::Delete => {
let left_data = take(&mut cur_left_data);
let left_data_len = left_data.len();
left_diff.push(ObjDataDiff {
data: left_data,
kind: ObjDataDiffKind::Delete,
len: left_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Delete,
len: left_data_len,
symbol: String::new(),
});
}
}
}
if left_cur < op.first_start {
left_diff.push(ObjDataDiff {
data: left.data[left_cur..op.first_start].to_vec(),
kind: ObjDataDiffKind::None,
len: op.first_start - left_cur,
symbol: String::new(),
});
left_cur = op.first_start;
}
if right_cur < op.second_start {
right_diff.push(ObjDataDiff {
data: right.data[right_cur..op.second_start].to_vec(),
kind: ObjDataDiffKind::None,
len: op.second_start - right_cur,
symbol: String::new(),
});
right_cur = op.second_start;
}
match op.op_type {
LevEditType::Replace => {
cur_left_data.push(left.data[left_cur]);
cur_right_data.push(right.data[right_cur]);
left_cur += 1;
right_cur += 1;
}
LevEditType::Insert => {
cur_right_data.push(right.data[right_cur]);
right_cur += 1;
}
LevEditType::Delete => {
cur_left_data.push(left.data[left_cur]);
left_cur += 1;
}
}
cur_op = op.op_type;
}
// if left_cur < left.data.len() {
// let len = left.data.len() - left_cur;
// left_diff.push(ObjDataDiff {
// data: left.data[left_cur..].to_vec(),
// kind: ObjDataDiffKind::Delete,
// len,
// });
// right_diff.push(ObjDataDiff { data: vec![], kind: ObjDataDiffKind::Delete, len });
// } else if right_cur < right.data.len() {
// let len = right.data.len() - right_cur;
// left_diff.push(ObjDataDiff { data: vec![], kind: ObjDataDiffKind::Insert, len });
// right_diff.push(ObjDataDiff {
// data: right.data[right_cur..].to_vec(),
// kind: ObjDataDiffKind::Insert,
// len,
// });
// }
// TODO: merge with above
match cur_op {
LevEditType::Replace => {
let left_data = take(&mut cur_left_data);
let right_data = take(&mut cur_right_data);
let left_data_len = left_data.len();
let right_data_len = right_data.len();
left_diff.push(ObjDataDiff {
data: left_data,
kind: ObjDataDiffKind::Replace,
len: left_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: right_data,
kind: ObjDataDiffKind::Replace,
len: right_data_len,
symbol: String::new(),
});
}
LevEditType::Insert => {
let right_data = take(&mut cur_right_data);
let right_data_len = right_data.len();
left_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Insert,
len: right_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: right_data,
kind: ObjDataDiffKind::Insert,
len: right_data_len,
symbol: String::new(),
});
}
LevEditType::Delete => {
let left_data = take(&mut cur_left_data);
let left_data_len = left_data.len();
left_diff.push(ObjDataDiff {
data: left_data,
kind: ObjDataDiffKind::Delete,
len: left_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Delete,
len: left_data_len,
symbol: String::new(),
});
}
}
if left_cur < left.data.len() {
left_diff.push(ObjDataDiff {
data: left.data[left_cur..].to_vec(),
kind: ObjDataDiffKind::None,
len: left.data.len() - left_cur,
symbol: String::new(),
});
}
if right_cur < right.data.len() {
right_diff.push(ObjDataDiff {
data: right.data[right_cur..].to_vec(),
kind: ObjDataDiffKind::None,
len: right.data.len() - right_cur,
symbol: String::new(),
});
}
left.data_diff = left_diff;
right.data_diff = right_diff;
}

478
src/diff/code.rs Normal file
View File

@@ -0,0 +1,478 @@
use std::{
cmp::max,
collections::BTreeMap,
time::{Duration, Instant},
};
use anyhow::Result;
use similar::{capture_diff_slices_deadline, Algorithm};
use crate::{
diff::{
editops::{editops_find, LevEditType},
DiffAlg, ProcessCodeResult,
},
obj::{
mips, ppc, ObjArchitecture, ObjInfo, ObjInsArg, ObjInsArgDiff, ObjInsBranchFrom,
ObjInsBranchTo, ObjInsDiff, ObjInsDiffKind, ObjReloc, ObjSymbol, ObjSymbolFlags,
},
};
pub fn no_diff_code(
arch: ObjArchitecture,
data: &[u8],
symbol: &mut ObjSymbol,
relocs: &[ObjReloc],
line_info: &Option<BTreeMap<u32, u32>>,
) -> Result<()> {
let code =
&data[symbol.section_address as usize..(symbol.section_address + symbol.size) as usize];
let out = match arch {
ObjArchitecture::PowerPc => ppc::process_code(code, symbol.address, relocs, line_info)?,
ObjArchitecture::Mips => mips::process_code(
code,
symbol.address,
symbol.address + symbol.size,
relocs,
line_info,
)?,
};
let mut diff = Vec::<ObjInsDiff>::new();
for i in out.insts {
diff.push(ObjInsDiff { ins: Some(i), kind: ObjInsDiffKind::None, ..Default::default() });
}
resolve_branches(&mut diff);
symbol.instructions = diff;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn diff_code(
alg: DiffAlg,
arch: ObjArchitecture,
left_data: &[u8],
right_data: &[u8],
left_symbol: &mut ObjSymbol,
right_symbol: &mut ObjSymbol,
left_relocs: &[ObjReloc],
right_relocs: &[ObjReloc],
left_line_info: &Option<BTreeMap<u32, u32>>,
right_line_info: &Option<BTreeMap<u32, u32>>,
) -> Result<()> {
let left_code = &left_data[left_symbol.section_address as usize
..(left_symbol.section_address + left_symbol.size) as usize];
let right_code = &right_data[right_symbol.section_address as usize
..(right_symbol.section_address + right_symbol.size) as usize];
let (left_out, right_out) = match arch {
ObjArchitecture::PowerPc => (
ppc::process_code(left_code, left_symbol.address, left_relocs, left_line_info)?,
ppc::process_code(right_code, right_symbol.address, right_relocs, right_line_info)?,
),
ObjArchitecture::Mips => (
mips::process_code(
left_code,
left_symbol.address,
left_symbol.address + left_symbol.size,
left_relocs,
left_line_info,
)?,
mips::process_code(
right_code,
right_symbol.address,
left_symbol.address + left_symbol.size,
right_relocs,
right_line_info,
)?,
),
};
let mut left_diff = Vec::<ObjInsDiff>::new();
let mut right_diff = Vec::<ObjInsDiff>::new();
match alg {
DiffAlg::Levenshtein => {
diff_instructions_lev(
&mut left_diff,
&mut right_diff,
left_symbol,
right_symbol,
&left_out,
&right_out,
)?;
}
DiffAlg::Lcs => {
diff_instructions_similar(
Algorithm::Lcs,
&mut left_diff,
&mut right_diff,
&left_out,
&right_out,
)?;
}
DiffAlg::Myers => {
diff_instructions_similar(
Algorithm::Myers,
&mut left_diff,
&mut right_diff,
&left_out,
&right_out,
)?;
}
DiffAlg::Patience => {
diff_instructions_similar(
Algorithm::Patience,
&mut left_diff,
&mut right_diff,
&left_out,
&right_out,
)?;
}
}
resolve_branches(&mut left_diff);
resolve_branches(&mut right_diff);
let mut diff_state = InsDiffState::default();
for (left, right) in left_diff.iter_mut().zip(right_diff.iter_mut()) {
let result = compare_ins(left, right, &mut diff_state)?;
left.kind = result.kind;
right.kind = result.kind;
left.arg_diff = result.left_args_diff;
right.arg_diff = result.right_args_diff;
}
let total = left_out.insts.len();
let percent = if diff_state.diff_count >= total {
0.0
} else {
((total - diff_state.diff_count) as f32 / total as f32) * 100.0
};
left_symbol.match_percent = Some(percent);
right_symbol.match_percent = Some(percent);
left_symbol.instructions = left_diff;
right_symbol.instructions = right_diff;
Ok(())
}
fn diff_instructions_similar(
alg: Algorithm,
left_diff: &mut Vec<ObjInsDiff>,
right_diff: &mut Vec<ObjInsDiff>,
left_code: &ProcessCodeResult,
right_code: &ProcessCodeResult,
) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(5);
let ops = capture_diff_slices_deadline(alg, &left_code.ops, &right_code.ops, Some(deadline));
if ops.is_empty() {
left_diff.extend(
left_code
.insts
.iter()
.map(|i| ObjInsDiff { ins: Some(i.clone()), ..Default::default() }),
);
right_diff.extend(
right_code
.insts
.iter()
.map(|i| ObjInsDiff { ins: Some(i.clone()), ..Default::default() }),
);
return Ok(());
}
for op in ops {
let (_tag, left_range, right_range) = op.as_tag_tuple();
let len = max(left_range.len(), right_range.len());
left_diff.extend(
left_code.insts[left_range.clone()]
.iter()
.map(|i| ObjInsDiff { ins: Some(i.clone()), ..Default::default() }),
);
right_diff.extend(
right_code.insts[right_range.clone()]
.iter()
.map(|i| ObjInsDiff { ins: Some(i.clone()), ..Default::default() }),
);
if left_range.len() < len {
left_diff.extend((left_range.len()..len).map(|_| ObjInsDiff::default()));
}
if right_range.len() < len {
right_diff.extend((right_range.len()..len).map(|_| ObjInsDiff::default()));
}
}
Ok(())
}
fn diff_instructions_lev(
left_diff: &mut Vec<ObjInsDiff>,
right_diff: &mut Vec<ObjInsDiff>,
left_symbol: &ObjSymbol,
right_symbol: &ObjSymbol,
left_code: &ProcessCodeResult,
right_code: &ProcessCodeResult,
) -> Result<()> {
let edit_ops = editops_find(&left_code.ops, &right_code.ops);
let mut op_iter = edit_ops.iter();
let mut left_iter = left_code.insts.iter();
let mut right_iter = right_code.insts.iter();
let mut cur_op = op_iter.next();
let mut cur_left = left_iter.next();
let mut cur_right = right_iter.next();
while let Some(op) = cur_op {
let left_addr = op.first_start as u32 * 4;
let right_addr = op.second_start as u32 * 4;
while let (Some(left), Some(right)) = (cur_left, cur_right) {
if (left.address - left_symbol.address as u32) < left_addr {
left_diff.push(ObjInsDiff { ins: Some(left.clone()), ..ObjInsDiff::default() });
right_diff.push(ObjInsDiff { ins: Some(right.clone()), ..ObjInsDiff::default() });
} else {
break;
}
cur_left = left_iter.next();
cur_right = right_iter.next();
}
if let (Some(left), Some(right)) = (cur_left, cur_right) {
if (left.address - left_symbol.address as u32) != left_addr {
return Err(anyhow::Error::msg("Instruction address mismatch (left)"));
}
if (right.address - right_symbol.address as u32) != right_addr {
return Err(anyhow::Error::msg("Instruction address mismatch (right)"));
}
match op.op_type {
LevEditType::Replace => {
left_diff.push(ObjInsDiff { ins: Some(left.clone()), ..ObjInsDiff::default() });
right_diff
.push(ObjInsDiff { ins: Some(right.clone()), ..ObjInsDiff::default() });
cur_left = left_iter.next();
cur_right = right_iter.next();
}
LevEditType::Insert => {
left_diff.push(ObjInsDiff::default());
right_diff
.push(ObjInsDiff { ins: Some(right.clone()), ..ObjInsDiff::default() });
cur_right = right_iter.next();
}
LevEditType::Delete => {
left_diff.push(ObjInsDiff { ins: Some(left.clone()), ..ObjInsDiff::default() });
right_diff.push(ObjInsDiff::default());
cur_left = left_iter.next();
}
}
} else {
break;
}
cur_op = op_iter.next();
}
// Finalize
while cur_left.is_some() || cur_right.is_some() {
left_diff.push(ObjInsDiff { ins: cur_left.cloned(), ..ObjInsDiff::default() });
right_diff.push(ObjInsDiff { ins: cur_right.cloned(), ..ObjInsDiff::default() });
cur_left = left_iter.next();
cur_right = right_iter.next();
}
Ok(())
}
fn resolve_branches(vec: &mut [ObjInsDiff]) {
let mut branch_idx = 0usize;
// Map addresses to indices
let mut addr_map = BTreeMap::<u32, usize>::new();
for (i, ins_diff) in vec.iter().enumerate() {
if let Some(ins) = &ins_diff.ins {
addr_map.insert(ins.address, i);
}
}
// Generate branches
let mut branches = BTreeMap::<usize, ObjInsBranchFrom>::new();
for (i, ins_diff) in vec.iter_mut().enumerate() {
if let Some(ins) = &ins_diff.ins {
// if ins.ins.is_blr() || ins.reloc.is_some() {
// continue;
// }
if let Some(ins_idx) = ins
.args
.iter()
.find_map(|a| if let ObjInsArg::BranchOffset(offs) = a { Some(offs) } else { None })
.and_then(|offs| addr_map.get(&((ins.address as i32 + offs) as u32)))
{
if let Some(branch) = branches.get_mut(ins_idx) {
ins_diff.branch_to =
Some(ObjInsBranchTo { ins_idx: *ins_idx, branch_idx: branch.branch_idx });
branch.ins_idx.push(i);
} else {
ins_diff.branch_to = Some(ObjInsBranchTo { ins_idx: *ins_idx, branch_idx });
branches.insert(*ins_idx, ObjInsBranchFrom { ins_idx: vec![i], branch_idx });
branch_idx += 1;
}
}
}
}
// Store branch from
for (i, branch) in branches {
vec[i].branch_from = Some(branch);
}
}
fn address_eq(left: &ObjSymbol, right: &ObjSymbol) -> bool {
left.address as i64 + left.addend == right.address as i64 + right.addend
}
fn reloc_eq(left_reloc: Option<&ObjReloc>, right_reloc: Option<&ObjReloc>) -> bool {
let (Some(left), Some(right)) = (left_reloc, right_reloc) else {
return false;
};
if left.kind != right.kind {
return false;
}
let name_matches = left.target.name == right.target.name;
match (&left.target_section, &right.target_section) {
(Some(sl), Some(sr)) => {
// Match if section and name or address match
sl == sr && (name_matches || address_eq(&left.target, &right.target))
}
(Some(_), None) => false,
(None, Some(_)) => {
// Match if possibly stripped weak symbol
name_matches && right.target.flags.0.contains(ObjSymbolFlags::Weak)
}
(None, None) => name_matches,
}
}
fn arg_eq(
left: &ObjInsArg,
right: &ObjInsArg,
left_diff: &ObjInsDiff,
right_diff: &ObjInsDiff,
) -> bool {
return match left {
ObjInsArg::PpcArg(l) => match right {
ObjInsArg::PpcArg(r) => format!("{l}") == format!("{r}"),
_ => false,
},
ObjInsArg::Reloc => {
matches!(right, ObjInsArg::Reloc)
&& reloc_eq(
left_diff.ins.as_ref().and_then(|i| i.reloc.as_ref()),
right_diff.ins.as_ref().and_then(|i| i.reloc.as_ref()),
)
}
ObjInsArg::RelocWithBase => {
matches!(right, ObjInsArg::RelocWithBase)
&& reloc_eq(
left_diff.ins.as_ref().and_then(|i| i.reloc.as_ref()),
right_diff.ins.as_ref().and_then(|i| i.reloc.as_ref()),
)
}
ObjInsArg::MipsArg(ls) | ObjInsArg::MipsArgWithBase(ls) => {
matches!(right, ObjInsArg::MipsArg(rs) | ObjInsArg::MipsArgWithBase(rs) if ls == rs)
}
ObjInsArg::BranchOffset(_) => {
// Compare dest instruction idx after diffing
left_diff.branch_to.as_ref().map(|b| b.ins_idx)
== right_diff.branch_to.as_ref().map(|b| b.ins_idx)
}
};
}
#[derive(Default)]
struct InsDiffState {
diff_count: usize,
left_arg_idx: usize,
right_arg_idx: usize,
left_args_idx: BTreeMap<String, usize>,
right_args_idx: BTreeMap<String, usize>,
}
#[derive(Default)]
struct InsDiffResult {
kind: ObjInsDiffKind,
left_args_diff: Vec<Option<ObjInsArgDiff>>,
right_args_diff: Vec<Option<ObjInsArgDiff>>,
}
fn compare_ins(
left: &ObjInsDiff,
right: &ObjInsDiff,
state: &mut InsDiffState,
) -> Result<InsDiffResult> {
let mut result = InsDiffResult::default();
if let (Some(left_ins), Some(right_ins)) = (&left.ins, &right.ins) {
if left_ins.args.len() != right_ins.args.len() || left_ins.op != right_ins.op {
// Totally different op
result.kind = ObjInsDiffKind::Replace;
state.diff_count += 1;
return Ok(result);
}
if left_ins.mnemonic != right_ins.mnemonic {
// Same op but different mnemonic, still cmp args
result.kind = ObjInsDiffKind::OpMismatch;
state.diff_count += 1;
}
for (a, b) in left_ins.args.iter().zip(&right_ins.args) {
if arg_eq(a, b, left, right) {
result.left_args_diff.push(None);
result.right_args_diff.push(None);
} else {
if result.kind == ObjInsDiffKind::None {
result.kind = ObjInsDiffKind::ArgMismatch;
state.diff_count += 1;
}
let a_str = match a {
ObjInsArg::PpcArg(arg) => format!("{arg}"),
ObjInsArg::Reloc | ObjInsArg::RelocWithBase => String::new(),
ObjInsArg::MipsArg(str) | ObjInsArg::MipsArgWithBase(str) => str.clone(),
ObjInsArg::BranchOffset(arg) => format!("{arg}"),
};
let a_diff = if let Some(idx) = state.left_args_idx.get(&a_str) {
ObjInsArgDiff { idx: *idx }
} else {
let idx = state.left_arg_idx;
state.left_args_idx.insert(a_str, idx);
state.left_arg_idx += 1;
ObjInsArgDiff { idx }
};
let b_str = match b {
ObjInsArg::PpcArg(arg) => format!("{arg}"),
ObjInsArg::Reloc | ObjInsArg::RelocWithBase => String::new(),
ObjInsArg::MipsArg(str) | ObjInsArg::MipsArgWithBase(str) => str.clone(),
ObjInsArg::BranchOffset(arg) => format!("{arg}"),
};
let b_diff = if let Some(idx) = state.right_args_idx.get(&b_str) {
ObjInsArgDiff { idx: *idx }
} else {
let idx = state.right_arg_idx;
state.right_args_idx.insert(b_str, idx);
state.right_arg_idx += 1;
ObjInsArgDiff { idx }
};
result.left_args_diff.push(Some(a_diff));
result.right_args_diff.push(Some(b_diff));
}
}
} else if left.ins.is_some() {
result.kind = ObjInsDiffKind::Delete;
state.diff_count += 1;
} else {
result.kind = ObjInsDiffKind::Insert;
state.diff_count += 1;
}
Ok(result)
}
pub fn find_section_and_symbol(obj: &ObjInfo, name: &str) -> Option<(usize, usize)> {
for (section_idx, section) in obj.sections.iter().enumerate() {
let symbol_idx = match section.symbols.iter().position(|symbol| symbol.name == name) {
Some(symbol_idx) => symbol_idx,
None => continue,
};
return Some((section_idx, symbol_idx));
}
None
}

406
src/diff/data.rs Normal file
View File

@@ -0,0 +1,406 @@
use std::{
cmp::{max, min, Ordering},
mem::take,
time::{Duration, Instant},
};
use anyhow::{bail, Result};
use similar::{capture_diff_slices_deadline, Algorithm};
use crate::{
diff::{
editops::{editops_find, LevEditType},
DiffAlg,
},
obj::{ObjDataDiff, ObjDataDiffKind, ObjSection, ObjSymbol},
};
pub fn diff_data(alg: DiffAlg, left: &mut ObjSection, right: &mut ObjSection) -> Result<()> {
match alg {
DiffAlg::Levenshtein => diff_data_lev(left, right),
DiffAlg::Lcs => diff_data_similar(Algorithm::Lcs, left, right),
DiffAlg::Myers => diff_data_similar(Algorithm::Myers, left, right),
DiffAlg::Patience => diff_data_similar(Algorithm::Patience, left, right),
}
}
pub fn diff_bss_symbols(
left_symbols: &mut [ObjSymbol],
right_symbols: &mut [ObjSymbol],
) -> Result<()> {
for left_symbol in left_symbols {
if let Some(right_symbol) = right_symbols.iter_mut().find(|s| s.name == left_symbol.name) {
left_symbol.diff_symbol = Some(right_symbol.name.clone());
right_symbol.diff_symbol = Some(left_symbol.name.clone());
let percent = if left_symbol.size == right_symbol.size { 100.0 } else { 50.0 };
left_symbol.match_percent = Some(percent);
right_symbol.match_percent = Some(percent);
}
}
Ok(())
}
// WIP diff-by-symbol
#[allow(dead_code)]
pub fn diff_data_symbols(left: &mut ObjSection, right: &mut ObjSection) -> Result<()> {
let mut left_ops = Vec::<u32>::with_capacity(left.symbols.len());
let mut right_ops = Vec::<u32>::with_capacity(right.symbols.len());
for left_symbol in &left.symbols {
let data = &left.data
[left_symbol.address as usize..(left_symbol.address + left_symbol.size) as usize];
let hash = twox_hash::xxh3::hash64(data);
left_ops.push(hash as u32);
}
for symbol in &right.symbols {
let data = &right.data[symbol.address as usize..(symbol.address + symbol.size) as usize];
let hash = twox_hash::xxh3::hash64(data);
right_ops.push(hash as u32);
}
let edit_ops = editops_find(&left_ops, &right_ops);
if edit_ops.is_empty() && !left.data.is_empty() {
let mut left_iter = left.symbols.iter_mut();
let mut right_iter = right.symbols.iter_mut();
loop {
let (left_symbol, right_symbol) = match (left_iter.next(), right_iter.next()) {
(Some(l), Some(r)) => (l, r),
(None, None) => break,
_ => return Err(anyhow::Error::msg("L/R mismatch in diff_data_symbols")),
};
let left_data = &left.data
[left_symbol.address as usize..(left_symbol.address + left_symbol.size) as usize];
let right_data = &right.data[right_symbol.address as usize
..(right_symbol.address + right_symbol.size) as usize];
left.data_diff.push(ObjDataDiff {
data: left_data.to_vec(),
kind: ObjDataDiffKind::None,
len: left_symbol.size as usize,
symbol: left_symbol.name.clone(),
});
right.data_diff.push(ObjDataDiff {
data: right_data.to_vec(),
kind: ObjDataDiffKind::None,
len: right_symbol.size as usize,
symbol: right_symbol.name.clone(),
});
left_symbol.diff_symbol = Some(right_symbol.name.clone());
left_symbol.match_percent = Some(100.0);
right_symbol.diff_symbol = Some(left_symbol.name.clone());
right_symbol.match_percent = Some(100.0);
}
return Ok(());
}
Ok(())
}
pub fn diff_data_similar(
alg: Algorithm,
left: &mut ObjSection,
right: &mut ObjSection,
) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(5);
let ops = capture_diff_slices_deadline(alg, &left.data, &right.data, Some(deadline));
let mut left_diff = Vec::<ObjDataDiff>::new();
let mut right_diff = Vec::<ObjDataDiff>::new();
for op in ops {
let (tag, left_range, right_range) = op.as_tag_tuple();
let left_len = left_range.len();
let right_len = right_range.len();
let mut len = max(left_len, right_len);
let kind = match tag {
similar::DiffTag::Equal => ObjDataDiffKind::None,
similar::DiffTag::Delete => ObjDataDiffKind::Delete,
similar::DiffTag::Insert => ObjDataDiffKind::Insert,
similar::DiffTag::Replace => {
// Ensure replacements are equal length
len = min(left_len, right_len);
ObjDataDiffKind::Replace
}
};
let left_data = &left.data[left_range];
let right_data = &right.data[right_range];
left_diff.push(ObjDataDiff {
data: left_data[..min(len, left_data.len())].to_vec(),
kind,
len,
..Default::default()
});
right_diff.push(ObjDataDiff {
data: right_data[..min(len, right_data.len())].to_vec(),
kind,
len,
..Default::default()
});
if kind == ObjDataDiffKind::Replace {
match left_len.cmp(&right_len) {
Ordering::Less => {
let len = right_len - left_len;
left_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Insert,
len,
..Default::default()
});
right_diff.push(ObjDataDiff {
data: right_data[left_len..right_len].to_vec(),
kind: ObjDataDiffKind::Insert,
len,
..Default::default()
});
}
Ordering::Greater => {
let len = left_len - right_len;
left_diff.push(ObjDataDiff {
data: left_data[right_len..left_len].to_vec(),
kind: ObjDataDiffKind::Delete,
len,
..Default::default()
});
right_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Delete,
len,
..Default::default()
});
}
Ordering::Equal => {}
}
}
}
left.data_diff = left_diff;
right.data_diff = right_diff;
Ok(())
}
pub fn diff_data_lev(left: &mut ObjSection, right: &mut ObjSection) -> Result<()> {
let matrix_size = (left.data.len() as u64).saturating_mul(right.data.len() as u64);
if matrix_size > 1_000_000_000 {
bail!(
"Data section {} too large for Levenshtein diff ({} * {} = {})",
left.name,
left.data.len(),
right.data.len(),
matrix_size
);
}
let edit_ops = editops_find(&left.data, &right.data);
if edit_ops.is_empty() && !left.data.is_empty() {
left.data_diff = vec![ObjDataDiff {
data: left.data.clone(),
kind: ObjDataDiffKind::None,
len: left.data.len(),
symbol: String::new(),
}];
right.data_diff = vec![ObjDataDiff {
data: right.data.clone(),
kind: ObjDataDiffKind::None,
len: right.data.len(),
symbol: String::new(),
}];
return Ok(());
}
let mut left_diff = Vec::<ObjDataDiff>::new();
let mut right_diff = Vec::<ObjDataDiff>::new();
let mut left_cur = 0usize;
let mut right_cur = 0usize;
let mut cur_op = LevEditType::Replace;
let mut cur_left_data = Vec::<u8>::new();
let mut cur_right_data = Vec::<u8>::new();
for op in edit_ops {
if cur_op != op.op_type || left_cur < op.first_start || right_cur < op.second_start {
match cur_op {
LevEditType::Replace => {
let left_data = take(&mut cur_left_data);
let right_data = take(&mut cur_right_data);
let left_data_len = left_data.len();
let right_data_len = right_data.len();
left_diff.push(ObjDataDiff {
data: left_data,
kind: ObjDataDiffKind::Replace,
len: left_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: right_data,
kind: ObjDataDiffKind::Replace,
len: right_data_len,
symbol: String::new(),
});
}
LevEditType::Insert => {
let right_data = take(&mut cur_right_data);
let right_data_len = right_data.len();
left_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Insert,
len: right_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: right_data,
kind: ObjDataDiffKind::Insert,
len: right_data_len,
symbol: String::new(),
});
}
LevEditType::Delete => {
let left_data = take(&mut cur_left_data);
let left_data_len = left_data.len();
left_diff.push(ObjDataDiff {
data: left_data,
kind: ObjDataDiffKind::Delete,
len: left_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Delete,
len: left_data_len,
symbol: String::new(),
});
}
}
}
if left_cur < op.first_start {
left_diff.push(ObjDataDiff {
data: left.data[left_cur..op.first_start].to_vec(),
kind: ObjDataDiffKind::None,
len: op.first_start - left_cur,
symbol: String::new(),
});
left_cur = op.first_start;
}
if right_cur < op.second_start {
right_diff.push(ObjDataDiff {
data: right.data[right_cur..op.second_start].to_vec(),
kind: ObjDataDiffKind::None,
len: op.second_start - right_cur,
symbol: String::new(),
});
right_cur = op.second_start;
}
match op.op_type {
LevEditType::Replace => {
cur_left_data.push(left.data[left_cur]);
cur_right_data.push(right.data[right_cur]);
left_cur += 1;
right_cur += 1;
}
LevEditType::Insert => {
cur_right_data.push(right.data[right_cur]);
right_cur += 1;
}
LevEditType::Delete => {
cur_left_data.push(left.data[left_cur]);
left_cur += 1;
}
}
cur_op = op.op_type;
}
// if left_cur < left.data.len() {
// let len = left.data.len() - left_cur;
// left_diff.push(ObjDataDiff {
// data: left.data[left_cur..].to_vec(),
// kind: ObjDataDiffKind::Delete,
// len,
// });
// right_diff.push(ObjDataDiff { data: vec![], kind: ObjDataDiffKind::Delete, len });
// } else if right_cur < right.data.len() {
// let len = right.data.len() - right_cur;
// left_diff.push(ObjDataDiff { data: vec![], kind: ObjDataDiffKind::Insert, len });
// right_diff.push(ObjDataDiff {
// data: right.data[right_cur..].to_vec(),
// kind: ObjDataDiffKind::Insert,
// len,
// });
// }
// TODO: merge with above
match cur_op {
LevEditType::Replace => {
let left_data = take(&mut cur_left_data);
let right_data = take(&mut cur_right_data);
let left_data_len = left_data.len();
let right_data_len = right_data.len();
left_diff.push(ObjDataDiff {
data: left_data,
kind: ObjDataDiffKind::Replace,
len: left_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: right_data,
kind: ObjDataDiffKind::Replace,
len: right_data_len,
symbol: String::new(),
});
}
LevEditType::Insert => {
let right_data = take(&mut cur_right_data);
let right_data_len = right_data.len();
left_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Insert,
len: right_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: right_data,
kind: ObjDataDiffKind::Insert,
len: right_data_len,
symbol: String::new(),
});
}
LevEditType::Delete => {
let left_data = take(&mut cur_left_data);
let left_data_len = left_data.len();
left_diff.push(ObjDataDiff {
data: left_data,
kind: ObjDataDiffKind::Delete,
len: left_data_len,
symbol: String::new(),
});
right_diff.push(ObjDataDiff {
data: vec![],
kind: ObjDataDiffKind::Delete,
len: left_data_len,
symbol: String::new(),
});
}
}
if left_cur < left.data.len() {
left_diff.push(ObjDataDiff {
data: left.data[left_cur..].to_vec(),
kind: ObjDataDiffKind::None,
len: left.data.len() - left_cur,
symbol: String::new(),
});
}
if right_cur < right.data.len() {
right_diff.push(ObjDataDiff {
data: right.data[right_cur..].to_vec(),
kind: ObjDataDiffKind::None,
len: right.data.len() - right_cur,
symbol: String::new(),
});
}
left.data_diff = left_diff;
right.data_diff = right_diff;
Ok(())
}
pub fn no_diff_data(section: &mut ObjSection) {
section.data_diff = vec![ObjDataDiff {
data: section.data.clone(),
kind: ObjDataDiffKind::None,
len: section.data.len(),
symbol: String::new(),
}];
}

114
src/diff/mod.rs Normal file
View File

@@ -0,0 +1,114 @@
pub mod code;
pub mod data;
pub mod editops;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use crate::{
diff::{
code::{diff_code, find_section_and_symbol, no_diff_code},
data::{diff_bss_symbols, diff_data, no_diff_data},
},
obj::{ObjInfo, ObjIns, ObjSectionKind},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum DiffAlg {
#[default]
Patience,
Levenshtein,
Myers,
Lcs,
}
pub struct DiffObjConfig {
pub code_alg: DiffAlg,
pub data_alg: DiffAlg,
}
pub struct ProcessCodeResult {
pub ops: Vec<u8>,
pub insts: Vec<ObjIns>,
}
pub fn diff_objs(
config: &DiffObjConfig,
mut left: Option<&mut ObjInfo>,
mut right: Option<&mut ObjInfo>,
) -> Result<()> {
if let Some(left) = left.as_mut() {
for left_section in &mut left.sections {
if left_section.kind == ObjSectionKind::Code {
for left_symbol in &mut left_section.symbols {
if let Some((right, (right_section_idx, right_symbol_idx))) =
right.as_mut().and_then(|obj| {
find_section_and_symbol(obj, &left_symbol.name).map(|s| (obj, s))
})
{
let right_section = &mut right.sections[right_section_idx];
let right_symbol = &mut right_section.symbols[right_symbol_idx];
left_symbol.diff_symbol = Some(right_symbol.name.clone());
right_symbol.diff_symbol = Some(left_symbol.name.clone());
diff_code(
config.code_alg,
left.architecture,
&left_section.data,
&right_section.data,
left_symbol,
right_symbol,
&left_section.relocations,
&right_section.relocations,
&left.line_info,
&right.line_info,
)?;
} else {
no_diff_code(
left.architecture,
&left_section.data,
left_symbol,
&left_section.relocations,
&left.line_info,
)?;
}
}
} else if let Some(right_section) = right
.as_mut()
.and_then(|obj| obj.sections.iter_mut().find(|s| s.name == left_section.name))
{
if left_section.kind == ObjSectionKind::Data {
diff_data(config.data_alg, left_section, right_section)?;
} else if left_section.kind == ObjSectionKind::Bss {
diff_bss_symbols(&mut left_section.symbols, &mut right_section.symbols)?;
}
} else if left_section.kind == ObjSectionKind::Data {
no_diff_data(left_section);
}
}
}
if let Some(right) = right.as_mut() {
for right_section in right.sections.iter_mut() {
if right_section.kind == ObjSectionKind::Code {
for right_symbol in &mut right_section.symbols {
if right_symbol.instructions.is_empty() {
no_diff_code(
right.architecture,
&right_section.data,
right_symbol,
&right_section.relocations,
&right.line_info,
)?;
}
}
} else if right_section.kind == ObjSectionKind::Data
&& right_section.data_diff.is_empty()
{
no_diff_data(right_section);
}
}
}
if let (Some(left), Some(right)) = (left, right) {
diff_bss_symbols(&mut left.common, &mut right.common)?;
}
Ok(())
}

View File

@@ -4,7 +4,7 @@ use anyhow::{Context, Result};
use self_update::{cargo_crate_version, update::Release};
use crate::{
jobs::{start_job, update_status, Job, JobResult, JobState, JobStatusRef},
jobs::{start_job, update_status, Job, JobContext, JobResult, JobState},
update::{build_updater, BIN_NAME},
};
@@ -14,20 +14,20 @@ pub struct CheckUpdateResult {
pub found_binary: bool,
}
fn run_check_update(status: &JobStatusRef, cancel: Receiver<()>) -> Result<Box<CheckUpdateResult>> {
update_status(status, "Fetching latest release".to_string(), 0, 1, &cancel)?;
fn run_check_update(context: &JobContext, cancel: Receiver<()>) -> Result<Box<CheckUpdateResult>> {
update_status(context, "Fetching latest release".to_string(), 0, 1, &cancel)?;
let updater = build_updater().context("Failed to create release updater")?;
let latest_release = updater.get_latest_release()?;
let update_available =
self_update::version::bump_is_greater(cargo_crate_version!(), &latest_release.version)?;
let found_binary = latest_release.assets.iter().any(|a| a.name == BIN_NAME);
update_status(status, "Complete".to_string(), 1, 1, &cancel)?;
update_status(context, "Complete".to_string(), 1, 1, &cancel)?;
Ok(Box::new(CheckUpdateResult { update_available, latest_release, found_binary }))
}
pub fn start_check_update() -> JobState {
start_job("Check for updates", Job::CheckUpdate, move |status, cancel| {
run_check_update(status, cancel).map(|result| JobResult::CheckUpdate(Some(result)))
pub fn start_check_update(ctx: &egui::Context) -> JobState {
start_job(ctx, "Check for updates", Job::CheckUpdate, move |context, cancel| {
run_check_update(&context, cancel).map(|result| JobResult::CheckUpdate(Some(result)))
})
}

View File

@@ -48,6 +48,7 @@ impl JobQueue {
}
/// Returns whether any job is running.
#[allow(dead_code)]
pub fn any_running(&self) -> bool {
self.jobs.iter().any(|job| {
if let Some(handle) = &job.handle {
@@ -81,7 +82,7 @@ impl JobQueue {
self.jobs.retain(|job| {
!(job.should_remove
&& job.handle.is_none()
&& job.status.read().unwrap().error.is_none())
&& job.context.status.read().unwrap().error.is_none())
});
}
@@ -89,13 +90,17 @@ impl JobQueue {
pub fn remove(&mut self, id: usize) { self.jobs.retain(|job| job.id != id); }
}
pub type JobStatusRef = Arc<RwLock<JobStatus>>;
#[derive(Clone)]
pub struct JobContext {
pub status: Arc<RwLock<JobStatus>>,
pub egui: egui::Context,
}
pub struct JobState {
pub id: usize,
pub kind: Job,
pub handle: Option<JoinHandle<JobResult>>,
pub status: JobStatusRef,
pub context: JobContext,
pub cancel: Sender<()>,
pub should_remove: bool,
}
@@ -124,9 +129,10 @@ fn should_cancel(rx: &Receiver<()>) -> bool {
}
fn start_job(
ctx: &egui::Context,
title: &str,
kind: Job,
run: impl FnOnce(&JobStatusRef, Receiver<()>) -> Result<JobResult> + Send + 'static,
run: impl FnOnce(JobContext, Receiver<()>) -> Result<JobResult> + Send + 'static,
) -> JobState {
let status = Arc::new(RwLock::new(JobStatus {
title: title.to_string(),
@@ -135,10 +141,11 @@ fn start_job(
status: String::new(),
error: None,
}));
let status_clone = status.clone();
let context = JobContext { status: status.clone(), egui: ctx.clone() };
let context_inner = JobContext { status: status.clone(), egui: ctx.clone() };
let (tx, rx) = std::sync::mpsc::channel();
let handle = std::thread::spawn(move || {
return match run(&status, rx) {
return match run(context_inner, rx) {
Ok(state) => state,
Err(e) => {
if let Ok(mut w) = status.write() {
@@ -150,24 +157,18 @@ fn start_job(
});
let id = JOB_ID.fetch_add(1, Ordering::Relaxed);
log::info!("Started job {}", id);
JobState {
id,
kind,
handle: Some(handle),
status: status_clone,
cancel: tx,
should_remove: true,
}
JobState { id, kind, handle: Some(handle), context, cancel: tx, should_remove: true }
}
fn update_status(
status: &JobStatusRef,
context: &JobContext,
str: String,
count: u32,
total: u32,
cancel: &Receiver<()>,
) -> Result<()> {
let mut w = status.write().map_err(|_| anyhow::Error::msg("Failed to lock job status"))?;
let mut w =
context.status.write().map_err(|_| anyhow::Error::msg("Failed to lock job status"))?;
w.progress_items = Some([count, total]);
w.progress_percent = count as f32 / total as f32;
if should_cancel(cancel) {
@@ -176,5 +177,7 @@ fn update_status(
} else {
w.status = str;
}
drop(w);
context.egui.request_repaint();
Ok(())
}

View File

@@ -1,12 +1,17 @@
use std::{path::Path, process::Command, str::from_utf8, sync::mpsc::Receiver};
use std::{
path::{Path, PathBuf},
process::Command,
str::from_utf8,
sync::mpsc::Receiver,
};
use anyhow::{anyhow, Context, Error, Result};
use time::OffsetDateTime;
use crate::{
app::{AppConfig, AppConfigRef},
diff::diff_objs,
jobs::{start_job, update_status, Job, JobResult, JobState, JobStatusRef},
app::{AppConfig, ObjectConfig},
diff::{diff_objs, DiffAlg, DiffObjConfig},
jobs::{start_job, update_status, Job, JobContext, JobResult, JobState},
obj::{elf, ObjInfo},
};
@@ -15,6 +20,32 @@ pub struct BuildStatus {
pub log: String,
}
pub struct ObjDiffConfig {
pub build_base: bool,
pub build_target: bool,
pub custom_make: Option<String>,
pub project_dir: Option<PathBuf>,
pub selected_obj: Option<ObjectConfig>,
pub selected_wsl_distro: Option<String>,
pub code_alg: DiffAlg,
pub data_alg: DiffAlg,
}
impl ObjDiffConfig {
pub(crate) fn from_config(config: &AppConfig) -> Self {
ObjDiffConfig {
build_base: config.build_base,
build_target: config.build_target,
custom_make: config.custom_make.clone(),
project_dir: config.project_dir.clone(),
selected_obj: config.selected_obj.clone(),
selected_wsl_distro: config.selected_wsl_distro.clone(),
code_alg: config.code_alg,
data_alg: config.data_alg,
}
}
}
pub struct ObjDiffResult {
pub first_status: BuildStatus,
pub second_status: BuildStatus,
@@ -23,7 +54,7 @@ pub struct ObjDiffResult {
pub time: OffsetDateTime,
}
fn run_make(cwd: &Path, arg: &Path, config: &AppConfig) -> BuildStatus {
fn run_make(cwd: &Path, arg: &Path, config: &ObjDiffConfig) -> BuildStatus {
match (|| -> Result<BuildStatus> {
let make = config.custom_make.as_deref().unwrap_or("make");
#[cfg(not(windows))]
@@ -71,71 +102,117 @@ fn run_make(cwd: &Path, arg: &Path, config: &AppConfig) -> BuildStatus {
}
fn run_build(
status: &JobStatusRef,
context: &JobContext,
cancel: Receiver<()>,
config: AppConfigRef,
config: ObjDiffConfig,
) -> Result<Box<ObjDiffResult>> {
let config = config.read().map_err(|_| Error::msg("Failed to lock app config"))?.clone();
let obj_config = config.selected_obj.as_ref().ok_or_else(|| Error::msg("Missing obj path"))?;
let project_dir =
config.project_dir.as_ref().ok_or_else(|| Error::msg("Missing project dir"))?;
let target_path_rel = obj_config.target_path.strip_prefix(project_dir).map_err(|_| {
let target_path_rel = if let Some(target_path) = &obj_config.target_path {
Some(target_path.strip_prefix(project_dir).map_err(|_| {
anyhow!(
"Target path '{}' doesn't begin with '{}'",
obj_config.target_path.display(),
target_path.display(),
project_dir.display()
)
})?;
let base_path_rel = obj_config.base_path.strip_prefix(project_dir).map_err(|_| {
})?)
} else {
None
};
let base_path_rel = if let Some(base_path) = &obj_config.base_path {
Some(base_path.strip_prefix(project_dir).map_err(|_| {
anyhow!(
"Base path '{}' doesn't begin with '{}'",
obj_config.base_path.display(),
base_path.display(),
project_dir.display()
)
})?;
let total = if config.build_target { 5 } else { 4 };
let first_status = if config.build_target {
update_status(status, format!("Building target {}", target_path_rel.display()), 0, total, &cancel)?;
run_make(project_dir, target_path_rel, &config)
})?)
} else {
BuildStatus { success: true, log: String::new() }
None
};
update_status(status, format!("Building base {}", base_path_rel.display()), 1, total, &cancel)?;
let second_status = run_make(project_dir, base_path_rel, &config);
let mut total = 3;
if config.build_target && target_path_rel.is_some() {
total += 1;
}
if config.build_base && base_path_rel.is_some() {
total += 1;
}
let first_status = match target_path_rel {
Some(target_path_rel) if config.build_target => {
update_status(
context,
format!("Building target {}", target_path_rel.display()),
0,
total,
&cancel,
)?;
run_make(project_dir, target_path_rel, &config)
}
_ => BuildStatus { success: true, log: String::new() },
};
let second_status = match base_path_rel {
Some(base_path_rel) if config.build_base => {
update_status(
context,
format!("Building base {}", base_path_rel.display()),
0,
total,
&cancel,
)?;
run_make(project_dir, base_path_rel, &config)
}
_ => BuildStatus { success: true, log: String::new() },
};
let time = OffsetDateTime::now_utc();
let mut first_obj = if first_status.success {
update_status(status, format!("Loading target {}", target_path_rel.display()), 2, total, &cancel)?;
Some(elf::read(&obj_config.target_path).with_context(|| {
format!("Failed to read object '{}'", obj_config.target_path.display())
let mut first_obj =
match &obj_config.target_path {
Some(target_path) if first_status.success => {
update_status(
context,
format!("Loading target {}", target_path_rel.unwrap().display()),
2,
total,
&cancel,
)?;
Some(elf::read(target_path).with_context(|| {
format!("Failed to read object '{}'", target_path.display())
})?)
} else {
None
};
let mut second_obj = if second_status.success {
update_status(status, format!("Loading base {}", base_path_rel.display()), 3, total, &cancel)?;
Some(elf::read(&obj_config.base_path).with_context(|| {
format!("Failed to read object '{}'", obj_config.base_path.display())
})?)
} else {
None
};
if let (Some(first_obj), Some(second_obj)) = (&mut first_obj, &mut second_obj) {
update_status(status, "Performing diff".to_string(), 4, total, &cancel)?;
diff_objs(first_obj, second_obj)?;
}
_ => None,
};
update_status(status, "Complete".to_string(), total, total, &cancel)?;
let mut second_obj = match &obj_config.base_path {
Some(base_path) if second_status.success => {
update_status(
context,
format!("Loading base {}", base_path_rel.unwrap().display()),
3,
total,
&cancel,
)?;
Some(
elf::read(base_path)
.with_context(|| format!("Failed to read object '{}'", base_path.display()))?,
)
}
_ => None,
};
update_status(context, "Performing diff".to_string(), 4, total, &cancel)?;
let diff_config = DiffObjConfig { code_alg: config.code_alg, data_alg: config.data_alg };
diff_objs(&diff_config, first_obj.as_mut(), second_obj.as_mut())?;
update_status(context, "Complete".to_string(), total, total, &cancel)?;
Ok(Box::new(ObjDiffResult { first_status, second_status, first_obj, second_obj, time }))
}
pub fn start_build(config: AppConfigRef) -> JobState {
start_job("Object diff", Job::ObjDiff, move |status, cancel| {
run_build(status, cancel, config).map(|result| JobResult::ObjDiff(Some(result)))
pub fn start_build(ctx: &egui::Context, config: ObjDiffConfig) -> JobState {
start_job(ctx, "Object diff", Job::ObjDiff, move |context, cancel| {
run_build(&context, cancel, config).map(|result| JobResult::ObjDiff(Some(result)))
})
}

View File

@@ -9,7 +9,7 @@ use anyhow::{Context, Result};
use const_format::formatcp;
use crate::{
jobs::{start_job, update_status, Job, JobResult, JobState, JobStatusRef},
jobs::{start_job, update_status, Job, JobContext, JobResult, JobState},
update::{build_updater, BIN_NAME},
};
@@ -17,7 +17,7 @@ pub struct UpdateResult {
pub exe_path: PathBuf,
}
fn run_update(status: &JobStatusRef, cancel: Receiver<()>) -> Result<Box<UpdateResult>> {
fn run_update(status: &JobContext, cancel: Receiver<()>) -> Result<Box<UpdateResult>> {
update_status(status, "Fetching latest release".to_string(), 0, 3, &cancel)?;
let updater = build_updater().context("Failed to create release updater")?;
let latest_release = updater.get_latest_release()?;
@@ -53,8 +53,8 @@ fn run_update(status: &JobStatusRef, cancel: Receiver<()>) -> Result<Box<UpdateR
Ok(Box::from(UpdateResult { exe_path: target_file }))
}
pub fn start_update() -> JobState {
start_job("Update app", Job::Update, move |status, cancel| {
run_update(status, cancel).map(JobResult::Update)
pub fn start_update(ctx: &egui::Context) -> JobState {
start_job(ctx, "Update app", Job::Update, move |context, cancel| {
run_update(&context, cancel).map(JobResult::Update)
})
}

View File

@@ -3,9 +3,9 @@
pub use app::App;
mod app;
mod app_config;
mod config;
mod diff;
mod editops;
mod jobs;
mod obj;
mod update;

View File

@@ -3,10 +3,11 @@ use std::{collections::BTreeMap, fs, io::Cursor, path::Path};
use anyhow::{anyhow, bail, Context, Result};
use byteorder::{BigEndian, ReadBytesExt};
use cwdemangle::demangle;
use filetime::FileTime;
use flagset::Flags;
use object::{
elf, Architecture, File, Object, ObjectSection, ObjectSymbol, RelocationKind, RelocationTarget,
SectionIndex, SectionKind, Symbol, SymbolKind, SymbolSection,
SectionIndex, SectionKind, Symbol, SymbolKind, SymbolScope, SymbolSection,
};
use crate::obj::{
@@ -42,6 +43,9 @@ fn to_obj_symbol(obj_file: &File<'_>, symbol: &Symbol<'_, '_>, addend: i64) -> R
if symbol.is_weak() {
flags = ObjSymbolFlagSet(flags.0 | ObjSymbolFlags::Weak);
}
if symbol.scope() == SymbolScope::Linkage {
flags = ObjSymbolFlagSet(flags.0 | ObjSymbolFlags::Hidden);
}
let section_address = if let Some(section) =
symbol.section_index().and_then(|idx| obj_file.section_by_index(idx).ok())
{
@@ -294,16 +298,17 @@ fn line_info(obj_file: &File<'_>) -> Result<Option<BTreeMap<u32, u32>>> {
let address_delta = reader.read_u32::<BigEndian>()?;
map.insert(base_address + address_delta, line_number);
}
log::debug!("Line info: {map:#X?}");
// log::debug!("Line info: {map:#X?}");
return Ok(Some(map));
}
Ok(None)
}
pub fn read(obj_path: &Path) -> Result<ObjInfo> {
let data = {
let (data, timestamp) = {
let file = fs::File::open(obj_path)?;
unsafe { memmap2::Mmap::map(&file) }?
let timestamp = FileTime::from_last_modification_time(&file.metadata()?);
(unsafe { memmap2::Mmap::map(&file) }?, timestamp)
};
let obj_file = File::parse(&*data)?;
let architecture = match obj_file.architecture() {
@@ -319,6 +324,7 @@ pub fn read(obj_path: &Path) -> Result<ObjInfo> {
let mut result = ObjInfo {
architecture,
path: obj_path.to_owned(),
timestamp,
sections: filter_sections(&obj_file)?,
common: common_symbols(&obj_file)?,
line_info: line_info(&obj_file)?,

View File

@@ -3,7 +3,10 @@ use std::collections::BTreeMap;
use anyhow::Result;
use rabbitizer::{config, Abi, InstrCategory, Instruction, OperandType};
use crate::obj::{ObjIns, ObjInsArg, ObjReloc};
use crate::{
diff::ProcessCodeResult,
obj::{ObjIns, ObjInsArg, ObjReloc},
};
fn configure_rabbitizer() {
unsafe {
@@ -17,7 +20,7 @@ pub fn process_code(
end_address: u64,
relocs: &[ObjReloc],
line_info: &Option<BTreeMap<u32, u32>>,
) -> Result<(Vec<u8>, Vec<ObjIns>)> {
) -> Result<ProcessCodeResult> {
configure_rabbitizer();
let ins_count = data.len() / 4;
@@ -91,8 +94,9 @@ pub fn process_code(
reloc: reloc.cloned(),
branch_dest,
line,
orig: None,
});
cur_addr += 4;
}
Ok((ops, insts))
Ok(ProcessCodeResult { ops, insts })
}

View File

@@ -4,6 +4,7 @@ pub mod ppc;
use std::{collections::BTreeMap, path::PathBuf};
use filetime::FileTime;
use flagset::{flags, FlagSet};
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
@@ -18,6 +19,7 @@ flags! {
Local,
Weak,
Common,
Hidden,
}
}
#[derive(Debug, Copy, Clone, Default)]
@@ -37,7 +39,8 @@ pub struct ObjSection {
pub data_diff: Vec<ObjDataDiff>,
pub match_percent: f32,
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ObjInsArg {
PpcArg(ppc750cl::Argument),
MipsArg(String),
@@ -46,6 +49,31 @@ pub enum ObjInsArg {
RelocWithBase,
BranchOffset(i32),
}
impl ObjInsArg {
pub fn loose_eq(&self, other: &ObjInsArg) -> bool {
match (self, other) {
(ObjInsArg::PpcArg(a), ObjInsArg::PpcArg(b)) => {
a == b
|| match (a, b) {
// Consider Simm and Offset equivalent
(ppc750cl::Argument::Simm(simm), ppc750cl::Argument::Offset(off))
| (ppc750cl::Argument::Offset(off), ppc750cl::Argument::Simm(simm)) => {
simm.0 == off.0
}
_ => false,
}
}
(ObjInsArg::MipsArg(a), ObjInsArg::MipsArg(b)) => a == b,
(ObjInsArg::MipsArgWithBase(a), ObjInsArg::MipsArgWithBase(b)) => a == b,
(ObjInsArg::Reloc, ObjInsArg::Reloc) => true,
(ObjInsArg::RelocWithBase, ObjInsArg::RelocWithBase) => true,
(ObjInsArg::BranchOffset(a), ObjInsArg::BranchOffset(b)) => a == b,
_ => false,
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct ObjInsArgDiff {
/// Incrementing index for coloring
@@ -86,6 +114,8 @@ pub struct ObjIns {
pub branch_dest: Option<u32>,
/// Line info
pub line: Option<u32>,
/// Original (unsimplified) instruction
pub orig: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct ObjInsDiff {
@@ -139,6 +169,7 @@ pub enum ObjArchitecture {
pub struct ObjInfo {
pub architecture: ObjArchitecture,
pub path: PathBuf,
pub timestamp: FileTime,
pub sections: Vec<ObjSection>,
pub common: Vec<ObjSymbol>,
pub line_info: Option<BTreeMap<u32, u32>>,

View File

@@ -1,9 +1,12 @@
use std::collections::BTreeMap;
use anyhow::Result;
use ppc750cl::{disasm_iter, Argument};
use ppc750cl::{disasm_iter, Argument, SimplifiedIns};
use crate::obj::{ObjIns, ObjInsArg, ObjReloc, ObjRelocKind};
use crate::{
diff::ProcessCodeResult,
obj::{ObjIns, ObjInsArg, ObjReloc, ObjRelocKind},
};
// Relative relocation, can be Simm or BranchOffset
fn is_relative_arg(arg: &ObjInsArg) -> bool {
@@ -22,7 +25,7 @@ pub fn process_code(
address: u64,
relocs: &[ObjReloc],
line_info: &Option<BTreeMap<u32, u32>>,
) -> Result<(Vec<u8>, Vec<ObjIns>)> {
) -> Result<ProcessCodeResult> {
let ins_count = data.len() / 4;
let mut ops = Vec::<u8>::with_capacity(ins_count);
let mut insts = Vec::<ObjIns>::with_capacity(ins_count);
@@ -40,7 +43,7 @@ pub fn process_code(
_ => ins.code,
};
}
let simplified = ins.simplified();
let simplified = ins.clone().simplified();
let mut args: Vec<ObjInsArg> = simplified
.args
.iter()
@@ -86,10 +89,11 @@ pub fn process_code(
mnemonic: format!("{}{}", simplified.mnemonic, simplified.suffix),
args,
reloc: reloc.cloned(),
op: 0,
op: ins.op as u8,
branch_dest: None,
line,
orig: Some(format!("{}", SimplifiedIns::basic_form(ins))),
});
}
Ok((ops, insts))
Ok(ProcessCodeResult { ops, insts })
}

View File

@@ -1,4 +1,4 @@
#[cfg(windows)]
#[cfg(feature = "wsl")]
use std::string::FromUtf16Error;
use std::{
borrow::Cow,
@@ -6,12 +6,12 @@ use std::{
path::{PathBuf, MAIN_SEPARATOR},
};
#[cfg(windows)]
#[cfg(feature = "wsl")]
use anyhow::{Context, Result};
use const_format::formatcp;
use egui::{
output::OpenUrl, text::LayoutJob, CollapsingHeader, FontFamily, FontId, RichText,
SelectableLabel, TextFormat, Widget,
SelectableLabel, TextFormat, Widget, WidgetText,
};
use globset::Glob;
use self_update::cargo_crate_version;
@@ -19,13 +19,17 @@ use self_update::cargo_crate_version;
use crate::{
app::{AppConfig, AppConfigRef, ObjectConfig},
config::{ProjectObject, ProjectObjectNode},
diff::DiffAlg,
jobs::{
check_update::{start_check_update, CheckUpdateResult},
update::start_update,
Job, JobQueue, JobResult,
},
update::RELEASE_URL,
views::appearance::Appearance,
views::{
appearance::Appearance,
file::{FileDialogResult, FileDialogState},
},
};
#[derive(Default)]
@@ -40,12 +44,15 @@ pub struct ConfigViewState {
pub watch_pattern_text: String,
pub load_error: Option<String>,
pub object_search: String,
#[cfg(windows)]
pub filter_diffable: bool,
pub filter_incomplete: bool,
#[cfg(feature = "wsl")]
pub available_wsl_distros: Option<Vec<String>>,
pub file_dialog_state: FileDialogState,
}
impl ConfigViewState {
pub fn pre_update(&mut self, jobs: &mut JobQueue) {
pub fn pre_update(&mut self, jobs: &mut JobQueue, config: &AppConfigRef) {
jobs.results.retain_mut(|result| {
if let JobResult::CheckUpdate(result) = result {
self.check_update = take(result);
@@ -57,9 +64,52 @@ impl ConfigViewState {
self.build_running = jobs.is_running(Job::ObjDiff);
self.check_update_running = jobs.is_running(Job::CheckUpdate);
self.update_running = jobs.is_running(Job::Update);
// Check async file dialog results
match self.file_dialog_state.poll() {
FileDialogResult::None => {}
FileDialogResult::ProjectDir(path) => {
let mut guard = config.write().unwrap();
guard.set_project_dir(path.to_path_buf());
}
FileDialogResult::TargetDir(path) => {
let mut guard = config.write().unwrap();
guard.set_target_obj_dir(path.to_path_buf());
}
FileDialogResult::BaseDir(path) => {
let mut guard = config.write().unwrap();
guard.set_base_obj_dir(path.to_path_buf());
}
FileDialogResult::Object(path) => {
let mut guard = config.write().unwrap();
if let (Some(base_dir), Some(target_dir)) =
(&guard.base_obj_dir, &guard.target_obj_dir)
{
if let Ok(obj_path) = path.strip_prefix(base_dir) {
let target_path = target_dir.join(obj_path);
guard.set_selected_obj(ObjectConfig {
name: obj_path.display().to_string(),
target_path: Some(target_path),
base_path: Some(path),
reverse_fn_order: None,
complete: None,
});
} else if let Ok(obj_path) = path.strip_prefix(target_dir) {
let base_path = base_dir.join(obj_path);
guard.set_selected_obj(ObjectConfig {
name: obj_path.display().to_string(),
target_path: Some(path),
base_path: Some(base_path),
reverse_fn_order: None,
complete: None,
});
}
}
}
}
}
pub fn post_update(&mut self, jobs: &mut JobQueue, config: &AppConfigRef) {
pub fn post_update(&mut self, ctx: &egui::Context, jobs: &mut JobQueue, config: &AppConfigRef) {
if self.queue_build {
self.queue_build = false;
if let Ok(mut config) = config.write() {
@@ -69,12 +119,12 @@ impl ConfigViewState {
if self.queue_check_update {
self.queue_check_update = false;
jobs.push_once(Job::CheckUpdate, start_check_update);
jobs.push_once(Job::CheckUpdate, || start_check_update(ctx));
}
if self.queue_update {
self.queue_update = false;
jobs.push_once(Job::Update, start_update);
jobs.push_once(Job::Update, || start_update(ctx));
}
}
}
@@ -84,7 +134,7 @@ pub const DEFAULT_WATCH_PATTERNS: &[&str] = &[
"*.inc", "*.py", "*.yml", "*.txt", "*.json",
];
#[cfg(windows)]
#[cfg(feature = "wsl")]
fn process_utf16(bytes: &[u8]) -> Result<String, FromUtf16Error> {
let u16_bytes: Vec<u16> = bytes
.chunks_exact(2)
@@ -93,7 +143,7 @@ fn process_utf16(bytes: &[u8]) -> Result<String, FromUtf16Error> {
String::from_utf16(&u16_bytes)
}
#[cfg(windows)]
#[cfg(feature = "wsl")]
fn wsl_cmd(args: &[&str]) -> Result<String> {
use std::{os::windows::process::CommandExt, process::Command};
let output = Command::new("wsl")
@@ -104,7 +154,7 @@ fn wsl_cmd(args: &[&str]) -> Result<String> {
process_utf16(&output.stdout).context("Failed to process stdout")
}
#[cfg(windows)]
#[cfg(feature = "wsl")]
fn fetch_wsl2_distros() -> Vec<String> {
wsl_cmd(&["-l", "-q"])
.map(|stdout| {
@@ -177,7 +227,7 @@ pub fn config_ui(
}
ui.separator();
#[cfg(windows)]
#[cfg(feature = "wsl")]
{
ui.heading("Build");
if state.available_wsl_distros.is_none() {
@@ -193,7 +243,7 @@ pub fn config_ui(
});
ui.separator();
}
#[cfg(not(windows))]
#[cfg(not(feature = "wsl"))]
{
let _ = selected_wsl_distro;
}
@@ -207,31 +257,19 @@ pub fn config_ui(
let mut new_selected_obj = selected_obj.clone();
if objects.is_empty() {
if let (Some(base_dir), Some(target_dir)) = (base_obj_dir, target_obj_dir) {
if let (Some(_base_dir), Some(target_dir)) = (base_obj_dir, target_obj_dir) {
if ui.button("Select object").clicked() {
if let Some(path) = rfd::FileDialog::new()
state.file_dialog_state.queue(
|| {
Box::pin(
rfd::AsyncFileDialog::new()
.set_directory(&target_dir)
.add_filter("Object file", &["o", "elf"])
.pick_file()
{
if let Ok(obj_path) = path.strip_prefix(&base_dir) {
let target_path = target_dir.join(obj_path);
new_selected_obj = Some(ObjectConfig {
name: obj_path.display().to_string(),
target_path,
base_path: path,
reverse_fn_order: None,
});
} else if let Ok(obj_path) = path.strip_prefix(&target_dir) {
let base_path = base_dir.join(obj_path);
new_selected_obj = Some(ObjectConfig {
name: obj_path.display().to_string(),
target_path: path,
base_path,
reverse_fn_order: None,
});
}
}
.pick_file(),
)
},
FileDialogResult::Object,
);
}
if let Some(obj) = selected_obj {
ui.label(
@@ -266,6 +304,20 @@ pub fn config_ui(
root_open = Some(true);
node_open = NodeOpen::Object;
}
if ui
.selectable_label(state.filter_diffable, "Diffable")
.on_hover_text_at_pointer("Only show objects with a source file")
.clicked()
{
state.filter_diffable = !state.filter_diffable;
}
if ui
.selectable_label(state.filter_incomplete, "Incomplete")
.on_hover_text_at_pointer("Only show objects not marked complete")
.clicked()
{
state.filter_incomplete = !state.filter_incomplete;
}
});
if state.object_search.is_empty() {
if had_search {
@@ -285,10 +337,20 @@ pub fn config_ui(
.default_open(true)
.show(ui, |ui| {
let mut nodes = Cow::Borrowed(object_nodes);
if !state.object_search.is_empty() {
if !state.object_search.is_empty() || state.filter_diffable || state.filter_incomplete {
let search = state.object_search.to_ascii_lowercase();
nodes = Cow::Owned(
object_nodes.iter().filter_map(|node| filter_node(node, &search)).collect(),
object_nodes
.iter()
.filter_map(|node| {
filter_node(
node,
&search,
state.filter_diffable,
state.filter_incomplete,
)
})
.collect(),
);
}
@@ -322,8 +384,18 @@ fn display_object(
) {
let object_name = object.name();
let selected = matches!(selected_obj, Some(obj) if obj.name == object_name);
let color = if selected { appearance.emphasized_text_color } else { appearance.text_color };
if SelectableLabel::new(
let color = if selected {
appearance.emphasized_text_color
} else if let Some(complete) = object.complete {
if complete {
appearance.insert_color
} else {
appearance.delete_color
}
} else {
appearance.text_color
};
let clicked = SelectableLabel::new(
selected,
RichText::new(name)
.font(FontId {
@@ -333,13 +405,16 @@ fn display_object(
.color(color),
)
.ui(ui)
.clicked()
{
.clicked();
// Always recreate ObjectConfig if selected, in case the project config changed.
// ObjectConfig is compared using equality, so this won't unnecessarily trigger a rebuild.
if selected || clicked {
*selected_obj = Some(ObjectConfig {
name: object_name.to_string(),
target_path: object.target_path.clone().unwrap_or_default(),
base_path: object.base_path.clone().unwrap_or_default(),
target_path: object.target_path.clone(),
base_path: object.base_path.clone(),
reverse_fn_order: object.reverse_fn_order,
complete: object.complete,
});
}
}
@@ -404,21 +479,35 @@ fn contains_node(node: &ProjectObjectNode, selected_obj: &ObjectConfig) -> bool
}
}
fn filter_node(node: &ProjectObjectNode, search: &str) -> Option<ProjectObjectNode> {
fn filter_node(
node: &ProjectObjectNode,
search: &str,
filter_diffable: bool,
filter_incomplete: bool,
) -> Option<ProjectObjectNode> {
match node {
ProjectObjectNode::File(name, _) => {
if name.to_ascii_lowercase().contains(search) {
ProjectObjectNode::File(name, object) => {
if (search.is_empty() || name.to_ascii_lowercase().contains(search))
&& (!filter_diffable
|| (object.base_path.is_some() && object.target_path.is_some()))
&& (!filter_incomplete || matches!(object.complete, None | Some(false)))
{
Some(node.clone())
} else {
None
}
}
ProjectObjectNode::Dir(name, children) => {
if name.to_ascii_lowercase().contains(search) {
if (search.is_empty() || name.to_ascii_lowercase().contains(search))
&& !filter_diffable
&& !filter_incomplete
{
return Some(node.clone());
}
let new_children =
children.iter().filter_map(|child| filter_node(child, search)).collect::<Vec<_>>();
let new_children = children
.iter()
.filter_map(|child| filter_node(child, search, filter_diffable, filter_incomplete))
.collect::<Vec<_>>();
if !new_children.is_empty() {
Some(ProjectObjectNode::Dir(name.clone(), new_children))
} else {
@@ -523,9 +612,10 @@ fn split_obj_config_ui(
true,
);
if response.clicked() {
if let Some(path) = rfd::FileDialog::new().pick_folder() {
config.set_project_dir(path);
}
state.file_dialog_state.queue(
|| Box::pin(rfd::AsyncFileDialog::new().pick_folder()),
FileDialogResult::ProjectDir,
);
}
ui.separator();
@@ -581,12 +671,13 @@ fn split_obj_config_ui(
ui.label(job);
},
appearance,
!config.project_config_loaded,
config.project_config_info.is_none(),
);
if response.clicked() {
if let Some(path) = rfd::FileDialog::new().set_directory(&project_dir).pick_folder() {
config.set_target_obj_dir(path);
}
state.file_dialog_state.queue(
|| Box::pin(rfd::AsyncFileDialog::new().set_directory(&project_dir).pick_folder()),
FileDialogResult::TargetDir,
);
}
ui.checkbox(&mut config.build_target, "Build target objects").on_hover_ui(|ui| {
let mut job = LayoutJob::default();
@@ -631,13 +722,37 @@ fn split_obj_config_ui(
ui.label(job);
},
appearance,
!config.project_config_loaded,
config.project_config_info.is_none(),
);
if response.clicked() {
if let Some(path) = rfd::FileDialog::new().set_directory(&project_dir).pick_folder() {
config.set_base_obj_dir(path);
}
state.file_dialog_state.queue(
|| Box::pin(rfd::AsyncFileDialog::new().set_directory(&project_dir).pick_folder()),
FileDialogResult::BaseDir,
);
}
ui.checkbox(&mut config.build_base, "Build base objects").on_hover_ui(|ui| {
let mut job = LayoutJob::default();
job.append(
"Tells the build system to produce the base object.\n",
0.0,
text_format.clone(),
);
job.append("For example, this would call ", 0.0, text_format.clone());
job.append("make path/to/base.o", 0.0, code_format.clone());
job.append(".\n\n", 0.0, text_format.clone());
job.append(
"This can be disabled if you're running the build system\n",
0.0,
text_format.clone(),
);
job.append(
"externally, and just want objdiff to reload the files\n",
0.0,
text_format.clone(),
);
job.append("when they change.", 0.0, text_format.clone());
ui.label(job);
});
ui.separator();
}
@@ -692,3 +807,70 @@ fn split_obj_config_ui(
}
});
}
pub fn diff_options_window(
ctx: &egui::Context,
config: &AppConfigRef,
show: &mut bool,
appearance: &Appearance,
) {
let mut config_guard = config.write().unwrap();
egui::Window::new("Diff Options").open(show).show(ctx, |ui| {
diff_options_ui(ui, &mut config_guard, appearance);
});
}
fn diff_options_ui(ui: &mut egui::Ui, config: &mut AppConfig, appearance: &Appearance) {
let mut job = LayoutJob::default();
job.append(
"Current default: ",
0.0,
TextFormat::simple(appearance.ui_font.clone(), appearance.text_color),
);
job.append(
diff_alg_to_string(DiffAlg::default()),
0.0,
TextFormat::simple(appearance.ui_font.clone(), appearance.emphasized_text_color),
);
ui.label(job);
let mut job = LayoutJob::default();
job.append(
"Previous default: ",
0.0,
TextFormat::simple(appearance.ui_font.clone(), appearance.text_color),
);
job.append(
"Levenshtein",
0.0,
TextFormat::simple(appearance.ui_font.clone(), appearance.emphasized_text_color),
);
ui.label(job);
ui.label("Please provide feedback!");
if diff_alg_ui(ui, "Code diff algorithm", &mut config.code_alg) {
config.queue_reload = true;
}
if diff_alg_ui(ui, "Data diff algorithm", &mut config.data_alg) {
config.queue_reload = true;
}
}
fn diff_alg_ui(ui: &mut egui::Ui, label: impl Into<WidgetText>, alg: &mut DiffAlg) -> bool {
let response = egui::ComboBox::from_label(label)
.selected_text(diff_alg_to_string(*alg))
.show_ui(ui, |ui| {
ui.selectable_value(alg, DiffAlg::Patience, "Patience").changed()
| ui.selectable_value(alg, DiffAlg::Levenshtein, "Levenshtein").changed()
| ui.selectable_value(alg, DiffAlg::Myers, "Myers").changed()
| ui.selectable_value(alg, DiffAlg::Lcs, "LCS").changed()
});
response.inner.unwrap_or(false)
}
const fn diff_alg_to_string(alg: DiffAlg) -> &'static str {
match alg {
DiffAlg::Patience => "Patience",
DiffAlg::Levenshtein => "Levenshtein",
DiffAlg::Lcs => "LCS",
DiffAlg::Myers => "Myers",
}
}

View File

@@ -132,31 +132,39 @@ fn split_diffs(diffs: &[ObjDataDiff]) -> Vec<Vec<ObjDataDiff>> {
fn data_table_ui(
table: TableBuilder<'_>,
left_obj: &ObjInfo,
right_obj: &ObjInfo,
left_obj: Option<&ObjInfo>,
right_obj: Option<&ObjInfo>,
selected_symbol: &SymbolReference,
config: &Appearance,
) -> Option<()> {
let left_section = find_section(left_obj, selected_symbol)?;
let right_section = find_section(right_obj, selected_symbol)?;
let left_section = left_obj.and_then(|obj| find_section(obj, selected_symbol));
let right_section = right_obj.and_then(|obj| find_section(obj, selected_symbol));
let total_bytes = left_section.data_diff.iter().fold(0usize, |accum, item| accum + item.len);
let total_bytes = left_section
.or(right_section)?
.data_diff
.iter()
.fold(0usize, |accum, item| accum + item.len);
if total_bytes == 0 {
return None;
}
let total_rows = (total_bytes - 1) / BYTES_PER_ROW + 1;
let left_diffs = split_diffs(&left_section.data_diff);
let right_diffs = split_diffs(&right_section.data_diff);
let left_diffs = left_section.map(|section| split_diffs(&section.data_diff));
let right_diffs = right_section.map(|section| split_diffs(&section.data_diff));
table.body(|body| {
body.rows(config.code_font.size, total_rows, |row_index, mut row| {
let address = row_index * BYTES_PER_ROW;
row.col(|ui| {
if let Some(left_diffs) = &left_diffs {
data_row_ui(ui, address, &left_diffs[row_index], config);
}
});
row.col(|ui| {
if let Some(right_diffs) = &right_diffs {
data_row_ui(ui, address, &right_diffs[row_index], config);
}
});
});
});
@@ -243,7 +251,6 @@ pub fn data_diff_ui(ui: &mut egui::Ui, state: &mut DiffViewState, appearance: &A
ui.separator();
// Table
if let (Some(left_obj), Some(right_obj)) = (&result.first_obj, &result.second_obj) {
let available_height = ui.available_height();
let table = TableBuilder::new(ui)
.striped(false)
@@ -252,6 +259,11 @@ pub fn data_diff_ui(ui: &mut egui::Ui, state: &mut DiffViewState, appearance: &A
.resizable(false)
.auto_shrink([false, false])
.min_scrolled_height(available_height);
data_table_ui(table, left_obj, right_obj, selected_symbol, appearance);
}
data_table_ui(
table,
result.first_obj.as_ref(),
result.second_obj.as_ref(),
selected_symbol,
appearance,
);
}

17
src/views/debug.rs Normal file
View File

@@ -0,0 +1,17 @@
use crate::views::{appearance::Appearance, frame_history::FrameHistory};
pub fn debug_window(
ctx: &egui::Context,
show: &mut bool,
frame_history: &mut FrameHistory,
appearance: &Appearance,
) {
egui::Window::new("Debug").open(show).show(ctx, |ui| {
debug_ui(ui, frame_history, appearance);
});
}
fn debug_ui(ui: &mut egui::Ui, frame_history: &mut FrameHistory, _appearance: &Appearance) {
ui.label(format!("Repainting the UI each frame. FPS: {:.1}", frame_history.fps()));
frame_history.ui(ui);
}

51
src/views/file.rs Normal file
View File

@@ -0,0 +1,51 @@
use std::{future::Future, path::PathBuf, pin::Pin, thread::JoinHandle};
use pollster::FutureExt;
use rfd::FileHandle;
#[derive(Default)]
pub enum FileDialogResult {
#[default]
None,
ProjectDir(PathBuf),
TargetDir(PathBuf),
BaseDir(PathBuf),
Object(PathBuf),
}
#[derive(Default)]
pub struct FileDialogState {
thread: Option<JoinHandle<FileDialogResult>>,
}
impl FileDialogState {
pub fn queue<InitCb, ResultCb>(&mut self, init: InitCb, result_cb: ResultCb)
where
InitCb: FnOnce() -> Pin<Box<dyn Future<Output = Option<FileHandle>> + Send>>,
ResultCb: FnOnce(PathBuf) -> FileDialogResult + Send + 'static,
{
if self.thread.is_some() {
return;
}
let future = init();
self.thread = Some(std::thread::spawn(move || {
if let Some(handle) = future.block_on() {
result_cb(PathBuf::from(handle))
} else {
FileDialogResult::None
}
}));
}
pub fn poll(&mut self) -> FileDialogResult {
if let Some(thread) = &mut self.thread {
if thread.is_finished() {
self.thread.take().unwrap().join().unwrap_or(FileDialogResult::None)
} else {
FileDialogResult::None
}
} else {
FileDialogResult::None
}
}
}

142
src/views/frame_history.rs Normal file
View File

@@ -0,0 +1,142 @@
// From https://github.com/emilk/egui/blob/e037489ac20a9e419715ae75d205a8baa117c3cf/crates/egui_demo_app/src/frame_history.rs
// Copyright (c) 2018-2021 Emil Ernerfeldt <emil.ernerfeldt@gmail.com>
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use egui::util::History;
pub struct FrameHistory {
frame_times: History<f32>,
}
impl Default for FrameHistory {
fn default() -> Self {
let max_age: f32 = 1.0;
let max_len = (max_age * 300.0).round() as usize;
Self { frame_times: History::new(0..max_len, max_age) }
}
}
impl FrameHistory {
// Called first
pub fn on_new_frame(&mut self, now: f64, previous_frame_time: Option<f32>) {
let previous_frame_time = previous_frame_time.unwrap_or_default();
if let Some(latest) = self.frame_times.latest_mut() {
*latest = previous_frame_time; // rewrite history now that we know
}
self.frame_times.add(now, previous_frame_time); // projected
}
pub fn mean_frame_time(&self) -> f32 { self.frame_times.average().unwrap_or_default() }
pub fn fps(&self) -> f32 { 1.0 / self.frame_times.mean_time_interval().unwrap_or_default() }
pub fn ui(&mut self, ui: &mut egui::Ui) {
ui.label(format!("Mean CPU usage: {:.2} ms / frame", 1e3 * self.mean_frame_time()))
.on_hover_text(
"Includes egui layout and tessellation time.\n\
Does not include GPU usage, nor overhead for sending data to GPU.",
);
egui::warn_if_debug_build(ui);
if !cfg!(target_arch = "wasm32") {
egui::CollapsingHeader::new("📊 CPU usage history").default_open(false).show(
ui,
|ui| {
self.graph(ui);
},
);
}
}
fn graph(&mut self, ui: &mut egui::Ui) -> egui::Response {
use egui::*;
ui.label("egui CPU usage history");
let history = &self.frame_times;
// TODO(emilk): we should not use `slider_width` as default graph width.
let height = ui.spacing().slider_width;
let size = vec2(ui.available_size_before_wrap().x, height);
let (rect, response) = ui.allocate_at_least(size, Sense::hover());
let style = ui.style().noninteractive();
let graph_top_cpu_usage = 0.010;
let graph_rect = Rect::from_x_y_ranges(history.max_age()..=0.0, graph_top_cpu_usage..=0.0);
let to_screen = emath::RectTransform::from_to(graph_rect, rect);
let mut shapes = Vec::with_capacity(3 + 2 * history.len());
shapes.push(Shape::Rect(epaint::RectShape::new(
rect,
style.rounding,
ui.visuals().extreme_bg_color,
ui.style().noninteractive().bg_stroke,
)));
let rect = rect.shrink(4.0);
let color = ui.visuals().text_color();
let line_stroke = Stroke::new(1.0, color);
if let Some(pointer_pos) = response.hover_pos() {
let y = pointer_pos.y;
shapes.push(Shape::line_segment(
[pos2(rect.left(), y), pos2(rect.right(), y)],
line_stroke,
));
let cpu_usage = to_screen.inverse().transform_pos(pointer_pos).y;
let text = format!("{:.1} ms", 1e3 * cpu_usage);
shapes.push(ui.fonts(|f| {
Shape::text(
f,
pos2(rect.left(), y),
egui::Align2::LEFT_BOTTOM,
text,
TextStyle::Monospace.resolve(ui.style()),
color,
)
}));
}
let circle_color = color;
let radius = 2.0;
let right_side_time = ui.input(|i| i.time); // Time at right side of screen
for (time, cpu_usage) in history.iter() {
let age = (right_side_time - time) as f32;
let pos = to_screen.transform_pos_clamped(Pos2::new(age, cpu_usage));
shapes.push(Shape::line_segment([pos2(pos.x, rect.bottom()), pos], line_stroke));
if cpu_usage < graph_top_cpu_usage {
shapes.push(Shape::circle_filled(pos, radius, circle_color));
}
}
ui.painter().extend(shapes);
response
}
}

View File

@@ -1,9 +1,12 @@
use std::{cmp::Ordering, default::Default};
use std::{
cmp::{max, Ordering},
default::Default,
};
use cwdemangle::demangle;
use eframe::emath::Align;
use egui::{text::LayoutJob, Color32, FontId, Label, Layout, Sense, Vec2};
use egui_extras::{Column, TableBuilder};
use egui::{text::LayoutJob, Color32, Label, Layout, RichText, Sense, TextFormat, Vec2};
use egui_extras::{Column, TableBuilder, TableRow};
use ppc750cl::Argument;
use time::format_description;
@@ -19,21 +22,49 @@ use crate::{
},
};
#[derive(Default)]
pub enum HighlightKind {
#[default]
None,
Opcode(u8),
Arg(ObjInsArg),
Symbol(String),
Address(u32),
}
#[derive(Default)]
pub struct FunctionViewState {
pub highlight: HighlightKind,
}
fn write_reloc_name(
reloc: &ObjReloc,
color: Color32,
background_color: Color32,
job: &mut LayoutJob,
font_id: FontId,
appearance: &Appearance,
) {
let name = reloc.target.demangled_name.as_ref().unwrap_or(&reloc.target.name);
write_text(name, appearance.emphasized_text_color, job, font_id.clone());
job.append(name, 0.0, TextFormat {
font_id: appearance.code_font.clone(),
color: appearance.emphasized_text_color,
background: background_color,
..Default::default()
});
match reloc.target.addend.cmp(&0i64) {
Ordering::Greater => {
write_text(&format!("+{:#X}", reloc.target.addend), color, job, font_id)
}
Ordering::Greater => write_text(
&format!("+{:#X}", reloc.target.addend),
color,
job,
appearance.code_font.clone(),
),
Ordering::Less => {
write_text(&format!("-{:#X}", -reloc.target.addend), color, job, font_id);
write_text(
&format!("-{:#X}", -reloc.target.addend),
color,
job,
appearance.code_font.clone(),
);
}
_ => {}
}
@@ -42,57 +73,57 @@ fn write_reloc_name(
fn write_reloc(
reloc: &ObjReloc,
color: Color32,
background_color: Color32,
job: &mut LayoutJob,
font_id: FontId,
appearance: &Appearance,
) {
match reloc.kind {
ObjRelocKind::PpcAddr16Lo => {
write_reloc_name(reloc, color, job, font_id.clone(), appearance);
write_text("@l", color, job, font_id);
write_reloc_name(reloc, color, background_color, job, appearance);
write_text("@l", color, job, appearance.code_font.clone());
}
ObjRelocKind::PpcAddr16Hi => {
write_reloc_name(reloc, color, job, font_id.clone(), appearance);
write_text("@h", color, job, font_id);
write_reloc_name(reloc, color, background_color, job, appearance);
write_text("@h", color, job, appearance.code_font.clone());
}
ObjRelocKind::PpcAddr16Ha => {
write_reloc_name(reloc, color, job, font_id.clone(), appearance);
write_text("@ha", color, job, font_id);
write_reloc_name(reloc, color, background_color, job, appearance);
write_text("@ha", color, job, appearance.code_font.clone());
}
ObjRelocKind::PpcEmbSda21 => {
write_reloc_name(reloc, color, job, font_id.clone(), appearance);
write_text("@sda21", color, job, font_id);
write_reloc_name(reloc, color, background_color, job, appearance);
write_text("@sda21", color, job, appearance.code_font.clone());
}
ObjRelocKind::MipsHi16 => {
write_text("%hi(", color, job, font_id.clone());
write_reloc_name(reloc, color, job, font_id.clone(), appearance);
write_text(")", color, job, font_id);
write_text("%hi(", color, job, appearance.code_font.clone());
write_reloc_name(reloc, color, background_color, job, appearance);
write_text(")", color, job, appearance.code_font.clone());
}
ObjRelocKind::MipsLo16 => {
write_text("%lo(", color, job, font_id.clone());
write_reloc_name(reloc, color, job, font_id.clone(), appearance);
write_text(")", color, job, font_id);
write_text("%lo(", color, job, appearance.code_font.clone());
write_reloc_name(reloc, color, background_color, job, appearance);
write_text(")", color, job, appearance.code_font.clone());
}
ObjRelocKind::MipsGot16 => {
write_text("%got(", color, job, font_id.clone());
write_reloc_name(reloc, color, job, font_id.clone(), appearance);
write_text(")", color, job, font_id);
write_text("%got(", color, job, appearance.code_font.clone());
write_reloc_name(reloc, color, background_color, job, appearance);
write_text(")", color, job, appearance.code_font.clone());
}
ObjRelocKind::MipsCall16 => {
write_text("%call16(", color, job, font_id.clone());
write_reloc_name(reloc, color, job, font_id.clone(), appearance);
write_text(")", color, job, font_id);
write_text("%call16(", color, job, appearance.code_font.clone());
write_reloc_name(reloc, color, background_color, job, appearance);
write_text(")", color, job, appearance.code_font.clone());
}
ObjRelocKind::MipsGpRel16 => {
write_text("%gp_rel(", color, job, font_id.clone());
write_reloc_name(reloc, color, job, font_id.clone(), appearance);
write_text(")", color, job, font_id);
write_text("%gp_rel(", color, job, appearance.code_font.clone());
write_reloc_name(reloc, color, background_color, job, appearance);
write_text(")", color, job, appearance.code_font.clone());
}
ObjRelocKind::PpcRel24 | ObjRelocKind::PpcRel14 | ObjRelocKind::Mips26 => {
write_reloc_name(reloc, color, job, font_id, appearance);
write_reloc_name(reloc, color, background_color, job, appearance);
}
ObjRelocKind::Absolute | ObjRelocKind::MipsGpRel32 => {
write_text("[INVALID]", color, job, font_id);
write_text("[INVALID]", color, job, appearance.code_font.clone());
}
};
}
@@ -102,8 +133,9 @@ fn write_ins(
diff_kind: &ObjInsDiffKind,
args: &[Option<ObjInsArgDiff>],
base_addr: u32,
job: &mut LayoutJob,
ui: &mut egui::Ui,
appearance: &Appearance,
ins_view_state: &mut FunctionViewState,
) {
let base_color = match diff_kind {
ObjInsDiffKind::None | ObjInsDiffKind::OpMismatch | ObjInsDiffKind::ArgMismatch => {
@@ -113,49 +145,96 @@ fn write_ins(
ObjInsDiffKind::Delete => appearance.delete_color,
ObjInsDiffKind::Insert => appearance.insert_color,
};
write_text(
&format!("{:<11}", ins.mnemonic),
let highlighted_op =
matches!(ins_view_state.highlight, HighlightKind::Opcode(op) if op == ins.op);
let op_label = RichText::new(ins.mnemonic.clone())
.font(appearance.code_font.clone())
.color(if highlighted_op {
appearance.emphasized_text_color
} else {
match diff_kind {
ObjInsDiffKind::OpMismatch => appearance.replace_color,
_ => base_color,
},
job,
appearance.code_font.clone(),
);
}
})
.background_color(if highlighted_op {
appearance.deemphasized_text_color
} else {
Color32::TRANSPARENT
});
if ui
.add(Label::new(op_label).sense(Sense::click()))
.context_menu(|ui| ins_context_menu(ui, ins))
.clicked()
{
if highlighted_op {
ins_view_state.highlight = HighlightKind::None;
} else {
ins_view_state.highlight = HighlightKind::Opcode(ins.op);
}
}
let space_width = ui.fonts(|f| f.glyph_width(&appearance.code_font, ' '));
ui.add_space(space_width * (max(11, ins.mnemonic.len()) - ins.mnemonic.len()) as f32);
let mut writing_offset = false;
for (i, arg) in ins.args.iter().enumerate() {
let mut job = LayoutJob::default();
if i == 0 {
write_text(" ", base_color, job, appearance.code_font.clone());
write_text(" ", base_color, &mut job, appearance.code_font.clone());
}
if i > 0 && !writing_offset {
write_text(", ", base_color, job, appearance.code_font.clone());
write_text(", ", base_color, &mut job, appearance.code_font.clone());
}
let color = if let Some(diff) = args.get(i).and_then(|a| a.as_ref()) {
let highlighted_arg = match &ins_view_state.highlight {
HighlightKind::Symbol(v) => {
matches!(arg, ObjInsArg::Reloc | ObjInsArg::RelocWithBase)
&& matches!(&ins.reloc, Some(reloc) if &reloc.target.name == v)
}
HighlightKind::Address(v) => {
matches!(arg, ObjInsArg::BranchOffset(offset) if (offset + ins.address as i32 - base_addr as i32) as u32 == *v)
}
HighlightKind::Arg(v) => v.loose_eq(arg),
_ => false,
};
let color = if highlighted_arg {
appearance.emphasized_text_color
} else if let Some(diff) = args.get(i).and_then(|a| a.as_ref()) {
appearance.diff_colors[diff.idx % appearance.diff_colors.len()]
} else {
base_color
};
let text_format = TextFormat {
font_id: appearance.code_font.clone(),
color,
background: if highlighted_arg {
appearance.deemphasized_text_color
} else {
Color32::TRANSPARENT
},
..Default::default()
};
let mut new_writing_offset = false;
match arg {
ObjInsArg::PpcArg(arg) => match arg {
Argument::Offset(val) => {
write_text(&format!("{val}"), color, job, appearance.code_font.clone());
write_text("(", base_color, job, appearance.code_font.clone());
writing_offset = true;
continue;
job.append(&format!("{val}"), 0.0, text_format);
write_text("(", base_color, &mut job, appearance.code_font.clone());
new_writing_offset = true;
}
Argument::Uimm(_) | Argument::Simm(_) => {
write_text(&format!("{arg}"), color, job, appearance.code_font.clone());
job.append(&format!("{arg}"), 0.0, text_format);
}
_ => {
write_text(&format!("{arg}"), color, job, appearance.code_font.clone());
job.append(&format!("{arg}"), 0.0, text_format);
}
},
ObjInsArg::Reloc => {
write_reloc(
ins.reloc.as_ref().unwrap(),
base_color,
job,
appearance.code_font.clone(),
text_format.background,
&mut job,
appearance,
);
}
@@ -163,41 +242,46 @@ fn write_ins(
write_reloc(
ins.reloc.as_ref().unwrap(),
base_color,
job,
appearance.code_font.clone(),
text_format.background,
&mut job,
appearance,
);
write_text("(", base_color, job, appearance.code_font.clone());
writing_offset = true;
continue;
write_text("(", base_color, &mut job, appearance.code_font.clone());
new_writing_offset = true;
}
ObjInsArg::MipsArg(str) => {
write_text(
str.strip_prefix('$').unwrap_or(str),
color,
job,
appearance.code_font.clone(),
);
job.append(str.strip_prefix('$').unwrap_or(str), 0.0, text_format);
}
ObjInsArg::MipsArgWithBase(str) => {
write_text(
str.strip_prefix('$').unwrap_or(str),
color,
job,
appearance.code_font.clone(),
);
write_text("(", base_color, job, appearance.code_font.clone());
writing_offset = true;
continue;
job.append(str.strip_prefix('$').unwrap_or(str), 0.0, text_format);
write_text("(", base_color, &mut job, appearance.code_font.clone());
new_writing_offset = true;
}
ObjInsArg::BranchOffset(offset) => {
let addr = offset + ins.address as i32 - base_addr as i32;
write_text(&format!("{addr:x}"), color, job, appearance.code_font.clone());
job.append(&format!("{addr:x}"), 0.0, text_format);
}
}
if writing_offset {
write_text(")", base_color, job, appearance.code_font.clone());
writing_offset = false;
write_text(")", base_color, &mut job, appearance.code_font.clone());
}
writing_offset = new_writing_offset;
if ui
.add(Label::new(job).sense(Sense::click()))
.context_menu(|ui| ins_context_menu(ui, ins))
.clicked()
{
if highlighted_arg {
ins_view_state.highlight = HighlightKind::None;
} else if matches!(arg, ObjInsArg::Reloc | ObjInsArg::RelocWithBase) {
ins_view_state.highlight =
HighlightKind::Symbol(ins.reloc.as_ref().unwrap().target.name.clone());
} else if let ObjInsArg::BranchOffset(offset) = arg {
ins_view_state.highlight =
HighlightKind::Address((offset + ins.address as i32 - base_addr as i32) as u32);
} else {
ins_view_state.highlight = HighlightKind::Arg(arg.clone());
}
}
}
}
@@ -209,6 +293,10 @@ fn ins_hover_ui(ui: &mut egui::Ui, ins: &ObjIns, appearance: &Appearance) {
ui.label(format!("{:02X?}", ins.code.to_be_bytes()));
if let Some(orig) = &ins.orig {
ui.label(format!("Original: {}", orig));
}
for arg in &ins.args {
if let ObjInsArg::PpcArg(arg) = arg {
match arg {
@@ -316,7 +404,9 @@ fn asm_row_ui(
ins_diff: &ObjInsDiff,
symbol: &ObjSymbol,
appearance: &Appearance,
ins_view_state: &mut FunctionViewState,
) {
ui.spacing_mut().item_spacing.x = 0.0;
if ins_diff.kind != ObjInsDiffKind::None {
ui.painter().rect_filled(ui.available_rect_before_wrap(), 0.0, ui.visuals().faint_bg_color);
}
@@ -345,60 +435,134 @@ fn asm_row_ui(
);
pad = 12 - line_str.len();
}
write_text(
&format!("{:<1$}", format!("{:x}: ", ins.address - symbol.address as u32), pad),
base_color,
&mut job,
appearance.code_font.clone(),
);
if let Some(branch) = &ins_diff.branch_from {
write_text(
"~> ",
appearance.diff_colors[branch.branch_idx % appearance.diff_colors.len()],
&mut job,
appearance.code_font.clone(),
let base_addr = symbol.address as u32;
let addr_highlight = matches!(
&ins_view_state.highlight,
HighlightKind::Address(v) if *v == (ins.address - base_addr)
);
let addr_string = format!("{:x}", ins.address - symbol.address as u32);
pad -= addr_string.len();
job.append(&addr_string, 0.0, TextFormat {
font_id: appearance.code_font.clone(),
color: if addr_highlight { appearance.emphasized_text_color } else { base_color },
background: if addr_highlight {
appearance.deemphasized_text_color
} else {
write_text(" ", base_color, &mut job, appearance.code_font.clone());
Color32::TRANSPARENT
},
..Default::default()
});
if ui
.add(Label::new(job).sense(Sense::click()))
.context_menu(|ui| ins_context_menu(ui, ins))
.clicked()
{
if addr_highlight {
ins_view_state.highlight = HighlightKind::None;
} else {
ins_view_state.highlight = HighlightKind::Address(ins.address - base_addr);
}
write_ins(ins, &ins_diff.kind, &ins_diff.arg_diff, symbol.address as u32, &mut job, appearance);
}
let mut job = LayoutJob::default();
let space_width = ui.fonts(|f| f.glyph_width(&appearance.code_font, ' '));
let spacing = space_width * pad as f32;
job.append(": ", 0.0, TextFormat {
font_id: appearance.code_font.clone(),
color: base_color,
..Default::default()
});
if let Some(branch) = &ins_diff.branch_from {
job.append("~> ", spacing, TextFormat {
font_id: appearance.code_font.clone(),
color: appearance.diff_colors[branch.branch_idx % appearance.diff_colors.len()],
..Default::default()
});
} else {
job.append(" ", spacing, TextFormat {
font_id: appearance.code_font.clone(),
color: base_color,
..Default::default()
});
}
ui.add(Label::new(job));
write_ins(ins, &ins_diff.kind, &ins_diff.arg_diff, base_addr, ui, appearance, ins_view_state);
if let Some(branch) = &ins_diff.branch_to {
let mut job = LayoutJob::default();
write_text(
" ~>",
appearance.diff_colors[branch.branch_idx % appearance.diff_colors.len()],
&mut job,
appearance.code_font.clone(),
);
ui.add(Label::new(job));
}
ui.add(Label::new(job).sense(Sense::click()))
.on_hover_ui_at_pointer(|ui| ins_hover_ui(ui, ins, appearance))
.context_menu(|ui| ins_context_menu(ui, ins));
}
fn asm_col_ui(
row: &mut TableRow<'_, '_>,
ins_diff: &ObjInsDiff,
symbol: &ObjSymbol,
appearance: &Appearance,
ins_view_state: &mut FunctionViewState,
) {
let (_, response) = row.col(|ui| {
asm_row_ui(ui, ins_diff, symbol, appearance, ins_view_state);
});
if let Some(ins) = &ins_diff.ins {
response
.on_hover_ui_at_pointer(|ui| {
ins_hover_ui(ui, ins, appearance);
})
.context_menu(|ui| {
ins_context_menu(ui, ins);
});
}
}
fn empty_col_ui(row: &mut TableRow<'_, '_>) {
row.col(|ui| {
ui.label("");
});
}
fn asm_table_ui(
table: TableBuilder<'_>,
left_obj: &ObjInfo,
right_obj: &ObjInfo,
left_obj: Option<&ObjInfo>,
right_obj: Option<&ObjInfo>,
selected_symbol: &SymbolReference,
appearance: &Appearance,
ins_view_state: &mut FunctionViewState,
) -> Option<()> {
let left_symbol = find_symbol(left_obj, selected_symbol);
let right_symbol = find_symbol(right_obj, selected_symbol);
let left_symbol = left_obj.and_then(|obj| find_symbol(obj, selected_symbol));
let right_symbol = right_obj.and_then(|obj| find_symbol(obj, selected_symbol));
let instructions_len = left_symbol.or(right_symbol).map(|s| s.instructions.len())?;
table.body(|body| {
body.rows(appearance.code_font.size, instructions_len, |row_index, mut row| {
row.col(|ui| {
if let Some(symbol) = left_symbol {
asm_row_ui(ui, &symbol.instructions[row_index], symbol, appearance);
asm_col_ui(
&mut row,
&symbol.instructions[row_index],
symbol,
appearance,
ins_view_state,
);
} else {
empty_col_ui(&mut row);
}
});
row.col(|ui| {
if let Some(symbol) = right_symbol {
asm_row_ui(ui, &symbol.instructions[row_index], symbol, appearance);
asm_col_ui(
&mut row,
&symbol.instructions[row_index],
symbol,
appearance,
ins_view_state,
);
} else {
empty_col_ui(&mut row);
}
});
});
});
Some(())
}
@@ -492,7 +656,7 @@ pub fn function_diff_ui(ui: &mut egui::Ui, state: &mut DiffViewState, appearance
&format!("{match_percent:.0}%"),
);
} else {
ui.label("");
ui.colored_label(appearance.replace_color, "Missing");
}
ui.label("Diff base:");
});
@@ -503,7 +667,6 @@ pub fn function_diff_ui(ui: &mut egui::Ui, state: &mut DiffViewState, appearance
ui.separator();
// Table
if let (Some(left_obj), Some(right_obj)) = (&result.first_obj, &result.second_obj) {
let available_height = ui.available_height();
let table = TableBuilder::new(ui)
.striped(false)
@@ -512,6 +675,12 @@ pub fn function_diff_ui(ui: &mut egui::Ui, state: &mut DiffViewState, appearance
.resizable(false)
.auto_shrink([false, false])
.min_scrolled_height(available_height);
asm_table_ui(table, left_obj, right_obj, selected_symbol, appearance);
}
asm_table_ui(
table,
result.first_obj.as_ref(),
result.second_obj.as_ref(),
selected_symbol,
appearance,
&mut state.function_state,
);
}

View File

@@ -7,7 +7,7 @@ pub fn jobs_ui(ui: &mut egui::Ui, jobs: &mut JobQueue, appearance: &Appearance)
let mut remove_job: Option<usize> = None;
for job in jobs.iter_mut() {
let Ok(status) = job.status.read() else {
let Ok(status) = job.context.status.read() else {
continue;
};
ui.group(|ui| {

View File

@@ -3,7 +3,10 @@ use egui::{text::LayoutJob, Color32, FontId, TextFormat};
pub(crate) mod appearance;
pub(crate) mod config;
pub(crate) mod data_diff;
pub(crate) mod debug;
pub(crate) mod demangle;
pub(crate) mod file;
pub(crate) mod frame_history;
pub(crate) mod function_diff;
pub(crate) mod jobs;
pub(crate) mod symbol_diff;

View File

@@ -1,7 +1,7 @@
use std::mem::take;
use egui::{
text::LayoutJob, Align, CollapsingHeader, Color32, Layout, Rgba, ScrollArea, SelectableLabel,
text::LayoutJob, Align, CollapsingHeader, Color32, Layout, ScrollArea, SelectableLabel,
TextEdit, Ui, Vec2, Widget,
};
use egui_extras::{Size, StripBuilder};
@@ -13,7 +13,7 @@ use crate::{
Job, JobQueue, JobResult,
},
obj::{ObjInfo, ObjSection, ObjSectionKind, ObjSymbol, ObjSymbolFlags},
views::{appearance::Appearance, write_text},
views::{appearance::Appearance, function_diff::FunctionViewState, write_text},
};
pub struct SymbolReference {
@@ -35,6 +35,7 @@ pub struct DiffViewState {
pub build: Option<Box<ObjDiffResult>>,
pub current_view: View,
pub symbol_state: SymbolViewState,
pub function_state: FunctionViewState,
pub search: String,
pub queue_build: bool,
pub build_running: bool,
@@ -46,6 +47,7 @@ pub struct SymbolViewState {
pub selected_symbol: Option<SymbolReference>,
pub reverse_fn_order: bool,
pub disable_reverse_fn_order: bool,
pub show_hidden_symbols: bool,
}
impl DiffViewState {
@@ -71,7 +73,7 @@ impl DiffViewState {
}
}
pub fn post_update(&mut self, _jobs: &mut JobQueue, config: &AppConfigRef) {
pub fn post_update(&mut self, config: &AppConfigRef) {
if self.queue_build {
self.queue_build = false;
if let Ok(mut config) = config.write() {
@@ -135,6 +137,9 @@ fn symbol_ui(
state: &mut SymbolViewState,
appearance: &Appearance,
) -> Option<View> {
if symbol.flags.0.contains(ObjSymbolFlags::Hidden) && !state.show_hidden_symbols {
return None;
}
let mut ret = None;
let mut job = LayoutJob::default();
let name: &str =
@@ -154,6 +159,9 @@ fn symbol_ui(
if symbol.flags.0.contains(ObjSymbolFlags::Weak) {
write_text("w", appearance.text_color, &mut job, appearance.code_font.clone());
}
if symbol.flags.0.contains(ObjSymbolFlags::Hidden) {
write_text("h", appearance.deemphasized_text_color, &mut job, appearance.code_font.clone());
}
write_text("] ", appearance.text_color, &mut job, appearance.code_font.clone());
if let Some(match_percent) = symbol.match_percent {
write_text("(", appearance.text_color, &mut job, appearance.code_font.clone());
@@ -263,6 +271,15 @@ fn build_log_ui(ui: &mut Ui, status: &BuildStatus, appearance: &Appearance) {
});
}
fn missing_obj_ui(ui: &mut Ui, appearance: &Appearance) {
ui.scope(|ui| {
ui.style_mut().override_text_style = Some(egui::TextStyle::Monospace);
ui.style_mut().wrap = Some(false);
ui.colored_label(appearance.replace_color, "No object configured");
});
}
pub fn symbol_diff_ui(ui: &mut Ui, state: &mut DiffViewState, appearance: &Appearance) {
let DiffViewState { build, current_view, symbol_state, search, .. } = state;
let Some(result) = build else {
@@ -289,9 +306,13 @@ pub fn symbol_diff_ui(ui: &mut Ui, state: &mut DiffViewState, appearance: &Appea
ui.label("Build target:");
if result.first_status.success {
ui.label("OK");
if result.first_obj.is_none() {
ui.colored_label(appearance.replace_color, "Missing");
} else {
ui.colored_label(Rgba::from_rgb(1.0, 0.0, 0.0), "Fail");
ui.label("OK");
}
} else {
ui.colored_label(appearance.delete_color, "Fail");
}
});
@@ -312,19 +333,19 @@ pub fn symbol_diff_ui(ui: &mut Ui, state: &mut DiffViewState, appearance: &Appea
ui.label("Build base:");
if result.second_status.success {
ui.label("OK");
if result.second_obj.is_none() {
ui.colored_label(appearance.replace_color, "Missing");
} else {
ui.colored_label(Rgba::from_rgb(1.0, 0.0, 0.0), "Fail");
ui.label("OK");
}
} else {
ui.colored_label(appearance.delete_color, "Fail");
}
});
ui.add_enabled(
!symbol_state.disable_reverse_fn_order,
egui::Checkbox::new(
&mut symbol_state.reverse_fn_order,
"Reverse function order (-inline deferred)",
),
);
if ui.add_enabled(!state.build_running, egui::Button::new("Build")).clicked() {
state.queue_build = true;
}
},
);
},
@@ -348,6 +369,8 @@ pub fn symbol_diff_ui(ui: &mut Ui, state: &mut DiffViewState, appearance: &Appea
&lower_search,
appearance,
));
} else {
missing_obj_ui(ui, appearance);
}
} else {
build_log_ui(ui, &result.first_status, appearance);
@@ -365,6 +388,8 @@ pub fn symbol_diff_ui(ui: &mut Ui, state: &mut DiffViewState, appearance: &Appea
&lower_search,
appearance,
));
} else {
missing_obj_ui(ui, appearance);
}
} else {
build_log_ui(ui, &result.second_status, appearance);