use std::ffi::OsString;
fn starts_openocd(first: &str) -> bool {
matches!(
first,
"-f" | "--file" | "-s" | "--search" | "-c" | "--command" | "-l" | "--log_output"
) || (first.starts_with("-d") && first[2..].chars().all(|c| c.is_ascii_digit()))
}
pub(crate) fn translate(argv: &[OsString]) -> Option<Vec<OsString>> {
let args: Vec<String> = argv
.iter()
.skip(1)
.map(|a| a.to_string_lossy().into_owned())
.collect();
let named_openocd = argv.first().is_some_and(|a| {
std::path::Path::new(a)
.file_stem()
.is_some_and(|s| s.to_string_lossy().eq_ignore_ascii_case("openocd"))
});
if !named_openocd && !args.first().is_some_and(|a| starts_openocd(a)) {
return None;
}
let mut commands = Vec::new();
let mut files = Vec::new();
let mut it = args.into_iter();
while let Some(a) = it.next() {
match a.as_str() {
"-c" | "--command" => commands.extend(it.next()),
"-f" | "--file" => files.extend(it.next()),
"-s" | "--search" | "-l" | "--log_output" => {
it.next();
}
_ => {} }
}
let mut port = String::from("3333");
let mut host = String::from("127.0.0.1");
let mut init = false;
let mut reset_halt = false;
for c in commands.iter().flat_map(|c| c.split([';', '\n'])) {
let words: Vec<&str> = c.split_whitespace().collect();
match words.as_slice() {
["gdb_port", p] => port = (*p).to_owned(),
["bindto", h] => host = (*h).to_owned(),
["init"] => init = true,
["reset", "halt" | "init"] if init => reset_halt = true,
_ => {}
}
}
let mut out: Vec<OsString> = vec![
argv.first().cloned().unwrap_or_else(|| "ch32rv".into()),
"--non-interactive".into(),
];
for f in &files {
let Some(kv) = f.strip_prefix("ch32rv:") else {
continue;
};
let Some((k, v)) = kv.split_once('=') else {
continue;
};
let v = v.trim();
if v.is_empty() || (v.starts_with('{') && v.ends_with('}')) {
continue;
}
match k.trim() {
"chip" => out.extend(["--chip".into(), v.into()]),
"probe" => out.extend(["--probe".into(), v.into()]),
"speed" => out.extend(["--speed".into(), v.into()]),
_ => {}
}
}
out.extend(["gdb".into(), "--openocd".into()]);
if reset_halt {
out.push("--reset-halt".into());
}
if port == "pipe" {
out.push("--pipe".into());
} else {
let addr = if host.contains(':') {
format!("[{host}]:{port}")
} else {
format!("{host}:{port}")
};
out.extend(["--listen".into(), addr.into()]);
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn t(args: &[&str]) -> Option<Vec<String>> {
let argv: Vec<OsString> = args.iter().map(OsString::from).collect();
translate(&argv).map(|v| {
v.into_iter()
.map(|a| a.to_string_lossy().into_owned())
.collect()
})
}
#[test]
fn arduino_cli_pipe() {
let v = t(&[
"/x/ch32rv",
"-s",
"/core/debug",
"--file",
"/core/debug/ch32rv.cfg",
"--file",
"ch32rv:chip=CH32V203C8T6",
"--file",
"ch32rv:probe=",
"-c",
"gdb_port pipe",
"-c",
"telnet_port 0",
])
.unwrap_or_default();
assert_eq!(
v,
[
"/x/ch32rv",
"--non-interactive",
"--chip",
"CH32V203C8T6",
"gdb",
"--openocd",
"--pipe"
]
);
}
#[test]
fn cortex_debug_tcp() {
let v = t(&[
"ch32rv.exe",
"-f",
"C:/ext/support/openocd-helpers.tcl",
"-c",
"gdb_port 50000",
"-c",
"tcl_port 50001",
"-c",
"telnet_port 50002",
"-s",
"C:/core/debug",
"-f",
"C:/core/debug/ch32rv.cfg",
"-f",
"ch32rv:chip=CH32X035G8U6",
"-f",
"ch32rv:probe=oep://0070070d9394/weact",
"-c",
"CDLiveWatchSetup",
])
.unwrap_or_default();
assert_eq!(
v,
[
"ch32rv.exe",
"--non-interactive",
"--chip",
"CH32X035G8U6",
"--probe",
"oep://0070070d9394/weact",
"gdb",
"--openocd",
"--listen",
"127.0.0.1:50000"
]
);
}
#[test]
fn not_openocd() {
assert_eq!(t(&["ch32rv", "flash", "a.elf"]), None);
assert_eq!(t(&["ch32rv", "-v", "probe", "list"]), None);
assert_eq!(t(&["ch32rv"]), None);
let v = t(&["/usr/bin/openocd"]).unwrap_or_default();
assert_eq!(v[2..], ["gdb", "--openocd", "--listen", "127.0.0.1:3333"]);
let v = t(&["ch32rv", "-d3", "-c", "gdb_port 4444; bindto 0.0.0.0"]).unwrap_or_default();
assert!(
v.ends_with(&["--listen".to_owned(), "0.0.0.0:4444".to_owned()]),
"{v:?}"
);
let v = t(&[
"ch32rv",
"-f",
"ch32rv:probe={debug.port}",
"-c",
"gdb_port pipe",
])
.unwrap_or_default();
assert!(!v.iter().any(|a| a == "--probe"), "{v:?}");
}
#[test]
fn init_then_reset_halt_resets_before_gdb() {
let v = t(&[
"/x/ch32rv",
"-f",
"ch32rv:chip=CH32V203C8T6",
"-c",
"gdb_port pipe",
"-c",
"init",
"-c",
"reset halt",
])
.unwrap_or_default();
assert_eq!(
v,
[
"/x/ch32rv",
"--non-interactive",
"--chip",
"CH32V203C8T6",
"gdb",
"--openocd",
"--reset-halt",
"--pipe"
]
);
for args in [
&["/x/ch32rv", "-c", "gdb_port 50000"][..],
&["/x/ch32rv", "-c", "reset halt", "-c", "init"][..],
] {
let v = t(args).unwrap_or_default();
assert!(!v.iter().any(|a| a == "--reset-halt"), "{v:?}");
}
}
}