Skip to content

Commit

Permalink
feature: payload conversion (to jtag and to isp) + flake, rust updates (
Browse files Browse the repository at this point in the history
#82)

A convenience function to convert (full) isp payloads for programming
via JTAG and vice versa.
  • Loading branch information
carlossless authored Jul 9, 2024
1 parent 6e02ea7 commit 942bad0
Show file tree
Hide file tree
Showing 7 changed files with 198 additions and 66 deletions.
74 changes: 20 additions & 54 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion flake.nix
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-23.11";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
utils.url = "github:numtide/flake-utils";
naersk.url = "github:nix-community/naersk";
rust-overlay.url = "github:oxalica/rust-overlay";
Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[toolchain]
channel = "1.76"
channel = "1.78"
components = [
"rustfmt",
"rustc",
Expand Down
7 changes: 3 additions & 4 deletions src/isp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ use std::{thread, time};
use log::{debug, info};
use thiserror::Error;

use super::{part::*, util};
use crate::VerificationError;
use crate::{part::*, util, VerificationError};

extern crate hidapi;

Expand Down Expand Up @@ -317,10 +316,10 @@ impl ISPDevice {
self.reboot()?;
}

return Ok(firmware);
Ok(firmware)
}

pub fn write_cycle(&self, firmware: &mut Vec<u8>) -> Result<(), ISPError> {
pub fn write_cycle(&self, firmware: &mut [u8]) -> Result<(), ISPError> {
// ensure that the address at <firmware_size-4> is the same as the reset vector
firmware.copy_within(1..3, self.part.firmware_size - 4);

Expand Down
82 changes: 77 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ pub enum CLIError {
ISPError(#[from] ISPError),
#[error(transparent)]
IHEXError(#[from] ConversionError),
#[error(transparent)]
PayloadConversionError(#[from] PayloadConversionError),
}

fn main() -> ExitCode {
Expand All @@ -39,7 +41,7 @@ fn main() -> ExitCode {
}

fn cli() -> Command {
return Command::new("sinowealth-kb-tool")
Command::new("sinowealth-kb-tool")
.about("A programming tool for Sinowealth Gaming KB devices")
.version(env!("CARGO_PKG_VERSION"))
.subcommand_required(true)
Expand All @@ -50,6 +52,15 @@ fn cli() -> Command {
.short_flag('l')
.about("List all connected devices and their identifiers. This is useful to find the manufacturer and product id for your device.")
)
.subcommand(
Command::new("convert")
.short_flag('c')
.about("Convert payload from bootloader to JTAG and vice versa.")
.arg(arg!(-d --direction <DIRECTION> "direction of conversion").value_parser(["to_jtag", "to_isp"]).required(true))
.part_args()
.arg(arg!(input_file: <INPUT_FILE> "file to convert"))
.arg(arg!(output_file: <OUTPUT_FILE> "file to write results to"))
)
.subcommand(
Command::new("read")
.short_flag('r')
Expand All @@ -68,11 +79,11 @@ fn cli() -> Command {
.about("Write file (Intel HEX) into flash.")
.arg(arg!(input_file: <INPUT_FILE> "payload to write into flash"))
.part_args(),
);
)
}

fn get_log_level() -> log::LevelFilter {
return if let Ok(debug) = env::var("DEBUG") {
if let Ok(debug) = env::var("DEBUG") {
if debug == "1" {
log::LevelFilter::Debug
} else {
Expand All @@ -83,7 +94,7 @@ fn get_log_level() -> log::LevelFilter {
return log::LevelFilter::Debug;
#[cfg(not(debug_assertions))]
log::LevelFilter::Info
};
}
}

fn err_main() -> Result<(), CLIError> {
Expand Down Expand Up @@ -146,6 +157,67 @@ fn err_main() -> Result<(), CLIError> {
Some(("list", _)) => {
ISPDevice::print_connected_devices().map_err(CLIError::from)?;
}
Some(("convert", sub_matches)) => {
let input_file = sub_matches
.get_one::<String>("input_file")
.map(|s| s.as_str())
.unwrap();

let output_file = sub_matches
.get_one::<String>("output_file")
.map(|s| s.as_str())
.unwrap();

let direction = sub_matches
.get_one::<String>("direction")
.map(|s| s.as_str())
.unwrap();

let part = get_part_from_matches(sub_matches);

let mut file = fs::File::open(input_file).map_err(CLIError::from)?;
let mut file_buf = Vec::new();
file.read_to_end(&mut file_buf).map_err(CLIError::from)?;
let file_str = String::from_utf8_lossy(&file_buf[..]);
let mut firmware = from_ihex(&file_str, part.firmware_size + part.bootloader_size)
.map_err(CLIError::from)?;

if firmware.len() < part.firmware_size {
log::warn!(
"Firmware size is more than expected ({}). Increasing to {}",
firmware.len(),
part.firmware_size
);
firmware.resize(part.firmware_size, 0);
}

match direction {
"to_jtag" => {
convert_to_jtag_payload(&mut firmware, part).map_err(CLIError::from)?;
if firmware.len() < part.total_flash_size() {
log::warn!(
"Firmware is smaller ({} bytes) than expected ({} bytes). This payload might not be suitable for JTAG flashing.",
firmware.len(),
part.total_flash_size()
);
}
}
"to_isp" => {
convert_to_isp_payload(&mut firmware, part).map_err(CLIError::from)?;
if firmware.len() > part.firmware_size {
log::warn!(
"Firmware size is larger ({} bytes) than expected ({} bytes). This payload might not be suitable for ISP flashing.",
firmware.len(),
part.firmware_size
);
}
}
_ => unreachable!(),
}

let ihex = to_ihex(firmware).map_err(CLIError::from)?;
fs::write(output_file, ihex).map_err(CLIError::from)?;
}
_ => unreachable!(),
}
Ok(())
Expand Down Expand Up @@ -236,5 +308,5 @@ fn get_part_from_matches(sub_matches: &ArgMatches) -> Part {
if let Some(reboot) = reboot {
part.reboot = *reboot;
}
return part;
part
}
4 changes: 4 additions & 0 deletions src/part.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,10 @@ impl Part {
pub fn num_pages(&self) -> usize {
self.firmware_size / self.page_size
}

pub fn total_flash_size(&self) -> usize {
self.firmware_size + self.bootloader_size
}
}

#[test]
Expand Down
Loading

0 comments on commit 942bad0

Please sign in to comment.