use std::process::ExitCode;
use ch32rv_contract::policy::{EraseMode, ResetPolicy, VerifyMode};
use ch32rv_contract::{ErrorKind, ResultEnvelope, Warning};
use ch32rv_flash::{BootArea, CODE_FLASH_START, Image, Segment};
use crate::args::{Cli, FlashArgs};
use crate::cmd_flash::{covered_pages, overlay_page, refuse_flags};
use crate::cmd_probe::fail;
use crate::cmd_target::OnTarget;
use crate::parse;
const CMD: &str = "flash";
const SYSTEM_SPAN: std::ops::Range<u32> = 0x1FF0_0000..0x2000_0000;
pub(crate) fn image_for_boot_area(cli: &Cli, args: &FlashArgs) -> Result<Option<Image>, ExitCode> {
let bin_offset = match &args.at {
Some(s) => match parse::u32_addr(s) {
Ok(a) => Some(a),
Err(_) => return Ok(None),
},
None => None,
};
let Ok(bytes) = std::fs::read(&args.file) else {
return Ok(None);
};
let Ok(image) = crate::cmd_flash::parse_image(
&bytes,
args.format,
&args.file,
bin_offset,
CODE_FLASH_START,
) else {
return Ok(None);
};
let in_system = |s: &Segment| SYSTEM_SPAN.contains(&s.addr);
let n = image.segments.iter().filter(|s| in_system(s)).count();
if n == 0 {
return Ok(None);
}
if n != image.segments.len() {
return Err(fail(
cli,
CMD,
ErrorKind::Usage,
"the image has segments both in the BOOT area (system memory) and elsewhere",
Some("write the bootloader and the application as two images, one `flash` each"),
));
}
Ok(Some(image))
}
fn refusals(args: &FlashArgs) -> Vec<String> {
let mut out = Vec::new();
match args.erase {
EraseMode::Chip => out.push("--erase chip".to_owned()),
EraseMode::None => out.push("--erase none".to_owned()),
EraseMode::Sector | EraseMode::KeepStore => {}
}
for (on, name) in [
(args.unprotect, "--unprotect"),
(args.preverify, "--preverify"),
(args.sdi.is_some(), "--sdi"),
(args.monitor.is_some(), "--monitor"),
(args.repeat, "--repeat"),
] {
if on {
out.push(name.to_owned());
}
}
out
}
pub(crate) fn flash(cli: &Cli, args: &FlashArgs, image: Image) -> ExitCode {
if let Some(c) = refuse_flags(cli, "writing the BOOT area", &refusals(args)) {
return c;
}
crate::cmd_target::on_target(cli, CMD, |t, family, db_family| {
let areas = ch32rv_flash::boot_areas(db_family);
if areas.is_empty() {
return fail(
cli,
CMD,
ErrorKind::CapabilityUnsupported,
format!("ch32rv does not write the BOOT area of {family}"),
Some(
"it writes those of CH32V003, CH32V00x, CH32X035, CH32L103 and CH32V103; on CH32V20x / V30x / V407 / X315 / H417 the FLASH controller leaves the BOOT area as it is",
),
);
}
let inside = |s: &Segment| {
areas
.iter()
.any(|a| s.addr >= a.base && s.addr + s.data.len() as u32 <= a.end())
};
if let Some(s) = image.segments.iter().find(|s| !inside(s)) {
let list: Vec<String> = areas
.iter()
.map(|a| format!("0x{:08x}+{}", a.base, a.size))
.collect();
return fail(
cli,
CMD,
ErrorKind::Usage,
format!(
"0x{:08x}+{} lies outside the BOOT area of {family} ({})",
s.addr,
s.data.len(),
list.join(", ")
),
None,
);
}
let first = image.base_addr().unwrap_or(0);
let area = areas
.iter()
.copied()
.find(|a| (a.base..a.end()).contains(&first))
.unwrap_or(areas[0]);
let Some(profile) = ch32rv_flash::flash_controller_profile_for(db_family) else {
return fail(
cli,
CMD,
ErrorKind::CapabilityUnsupported,
format!("no FLASH-controller profile for {family}"),
None,
);
};
let to = To {
family,
db_family,
area,
profile,
};
write(cli, args, t, &to, &image)
})
}
struct To<'a> {
family: &'a str,
db_family: &'a str,
area: BootArea,
profile: ch32rv_flash::FlashCtrlProfile,
}
fn write(
cli: &Cli,
args: &FlashArgs,
t: &mut OnTarget<'_, '_>,
to: &To<'_>,
image: &Image,
) -> ExitCode {
let (family, db_family, area, profile) = (to.family, to.db_family, to.area, to.profile);
let started = std::time::Instant::now();
if let Err(e) = t.halt() {
return fail(
cli,
CMD,
ErrorKind::AttachFailed,
format!("halt failed: {e}"),
None,
);
}
let page = profile.page_size;
let pages = covered_pages(
image.segments.iter().map(|s| (s.addr, s.data.len() as u32)),
page,
);
let loader = match t {
OnTarget::Oep(_) if profile.mode != ch32rv_dmi::FlashProgMode::V103 => {
ch32rv_flash::loader::plan_for_family(db_family)
}
_ => None,
};
if let (Some(plan), OnTarget::Oep(x)) = (loader, &mut *t) {
use ch32rv_dmi::TargetAccess;
let keys = [
(0x4002_2004, 0x4567_0123),
(0x4002_2004, 0xCDEF_89AB),
(0x4002_2028, 0x4567_0123),
(0x4002_2028, 0xCDEF_89AB),
(0x4002_2024, 0x4567_0123),
(0x4002_2024, 0xCDEF_89AB),
];
let r = keys
.iter()
.try_for_each(|&(reg, key)| x.t.write_words(reg, &[key]).map_err(|e| e.to_string()))
.and_then(|()| {
ch32rv_flash::loader::program(&mut x.t, plan, &image.segments, &mut |_, _| {})
.map(|_| ())
.map_err(|e| e.to_string())
});
if let Err(e) = r {
if args.reset == ResetPolicy::Run {
t.system_reset();
}
return fail(
cli,
CMD,
ErrorKind::TransferFailed,
format!("BOOT area: {e}"),
Some(
"the BOOT area may now hold a part of the image: write it again (the debug probe reaches the chip whatever the BOOT area holds)",
),
);
}
}
for &pg in pages.iter().filter(|_| loader.is_none()) {
let mut buf = match t.read_mem(pg, page) {
Ok(b) => b,
Err(e) => {
return fail(
cli,
CMD,
ErrorKind::TransferFailed,
format!("read 0x{pg:08x}: {e}"),
None,
);
}
};
buf.resize(page as usize, 0xff);
overlay_page(pg, &mut buf, &image.segments);
let r = t.with_flash_dm(|dm| {
dm.set_boot_area(true);
dm.flash_page_erase(pg, profile.mode)?;
if profile.mode == ch32rv_dmi::FlashProgMode::V103 {
dm.flash_program_page_v103_fast(pg, &buf)
} else {
dm.flash_program_page(pg, &buf, profile.mode)
}
});
if let Err(e) = r {
if args.reset == ResetPolicy::Run {
t.system_reset();
}
return fail(
cli,
CMD,
ErrorKind::TransferFailed,
format!("BOOT area page 0x{pg:08x}: {e}"),
Some(
"the BOOT area may now hold a part of the image: write it again (the debug probe reaches the chip whatever the BOOT area holds)",
),
);
}
}
let verified = args.verify == VerifyMode::Readback;
if verified {
for s in &image.segments {
let got = match t.read_mem(s.addr & !3, (s.addr % 4) + s.data.len() as u32) {
Ok(b) => b,
Err(e) => {
return fail(
cli,
CMD,
ErrorKind::TransferFailed,
format!("verify read 0x{:08x}: {e}", s.addr),
None,
);
}
};
let off = (s.addr % 4) as usize;
if got.get(off..off + s.data.len()) != Some(&s.data[..]) {
let at = s
.data
.iter()
.enumerate()
.position(|(i, b)| got.get(off + i) != Some(b));
return fail(
cli,
CMD,
ErrorKind::VerifyMismatch,
format!(
"the BOOT area differs from the image at 0x{:08x}",
s.addr + at.unwrap_or(0) as u32
),
Some("write it again"),
);
}
}
}
let running = match args.reset {
ResetPolicy::Run => {
t.clear_reset_flags(db_family);
t.system_reset();
true
}
ResetPolicy::Halt => false,
ResetPolicy::None => t.resume().is_ok(),
};
let bytes = image.total_len();
let warnings = vec![Warning {
code: "boot-area-rewritten".to_owned(),
msg: format!(
"the BOOT area of {family} was rewritten: unless this image is the factory bootloader, that is gone - keep a copy (`ch32rv read --range 0x{:08x}+{}` before writing) to write back the same way",
area.base, area.size
),
}];
let secs = started.elapsed().as_secs_f64();
if cli.json {
let mut env = ResultEnvelope::success(CMD);
env.result = Some(serde_json::json!({
"region": "boot",
"family": family,
"flash": {
"bytes": bytes,
"pages": pages.len(),
"base": format!("0x{:08x}", area.base),
"verified": verified,
},
"running": running,
}));
env.warnings = warnings;
crate::print_envelope(&env)
} else {
println!(
"flashed {bytes} bytes to the BOOT area of {family} (0x{:08x}, {} bytes) in {secs:.2} s: {} page(s){}",
area.base,
area.size,
pages.len(),
if verified { ", verified" } else { "" }
);
for w in &warnings {
eprintln!("warning[{}]: {}", w.code, w.msg);
}
ExitCode::SUCCESS
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used)]
use super::*;
#[test]
fn every_boot_area_lies_in_the_system_span() {
for f in ["CH32V003", "CH32V006", "CH32X035", "CH32L103", "CH32V103"] {
let areas = ch32rv_flash::boot_areas(f);
assert!(!areas.is_empty(), "{f}");
for a in areas {
assert!(
SYSTEM_SPAN.contains(&a.base) && a.end() <= SYSTEM_SPAN.end,
"{f}"
);
}
}
for f in [
"CH32V20x", "CH32V205", "CH32V307", "CH32V407", "CH32X315", "CH32H417", "CH32M030",
] {
assert!(ch32rv_flash::boot_areas(f).is_empty(), "{f}");
}
}
}