ch32rv 0.49.0

Flashing and debugging tool for WCH CH32 RISC-V microcontrollers
//! en: `flash` of an image that lies in the BOOT area (system memory): a bootloader of one's own in
//! place of the factory one (rv003usb, the UIAPduino's, WCH's USART_IAP generation A). It goes
//! through the Debug Module's FLASH-controller page erase / program with FLASH_BOOT_MODEKEYR
//! unlocked as well, on a WCH-Link and an OEP probe alike; the bytes of a covered page outside the
//! image are kept. Where the BOOT area is: [`ch32rv_flash::boot_areas`].
//! ja: BOOT 領域(system memory)に入る image の `flash`。工場の bootloader の代わりに自作のものを置く。
//! DM の FLASH controller の page 消去と書き込みを、BOOT_MODEKEYR も外して行う(WCH-Link と OEP の
//! どちらでも)。覆う page の image の外の byte は残す。

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";

/// en: Where every BOOT area of the CH32 families lies (0x1FFF0000 .. 0x1FFFF780): an image with a
/// segment here is meant for a BOOT area, whatever the family turns out to be.
/// ja: どの family の BOOT 領域もこの範囲に入る。ここに segment があれば BOOT 領域向けの image。
const SYSTEM_SPAN: std::ops::Range<u32> = 0x1FF0_0000..0x2000_0000;

/// en: The image when it is for a BOOT area: every segment in the system span. None for an image
/// for code flash (the ordinary path, which reads the file again); an image with both is refused
/// (exit 2) - the two are written by separate commands.
/// ja: BOOT 領域向けの image なら返す。code flash 向けなら None。両方を持つ image は断る。
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),
            // The ordinary path reports a bad --at the same way.
            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))
}

/// en: The flags this path cannot honour. It always erases the pages it writes and keeps their
/// bytes outside the image (so `--erase sector|keep-store` and `--restore-unwritten` are what it
/// does anyway). `--confirm-run` is not checked but not refused either, as on the WCH-Link loader
/// path (the Arduino recipes always pass it).
/// ja: この道で守れないフラグ。書く page は必ず消し、image の外の byte は残す。
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
}

/// en: Write `image` into the BOOT area of the target the command line names.
/// ja: `image` を BOOT 領域に書く。
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)
    })
}

/// Where a write goes: the family (shown and looked up), its BOOT area and FLASH controller.
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,
    );
    // en: On an OEP probe, the RAM loader with the BOOT area unlocked first: one run writes the
    // pages back to back (about 1 s for a V003's 1,920 B, against 21 s page by page over a slow
    // probe link). Not on a CH32V103, whose loader programs halfwords, which the BOOT area ignores.
    // ja: OEP では、BOOT の鍵を外してから RAM loader で書く(page ごとの DMI より速い)。V103 は除く。
    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()) {
        // en: The page as it is, with the image laid over it: the bytes outside the image stay.
        // ja: 今の page に image を重ねる(image の外の byte は残す)。
        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 {
            // en: Do not leave the hart halted with a program / erase mode bit set: a system reset
            // puts the FLASH controller back (locked, no mode), when the user asked for a run.
            // ja: 止めたまま FLASH の mode を残さない(run のときは system reset で戻す)。
            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}");
        }
    }
}