From c50314d4a864bda49dd14b3dd6c5fb21a22c857d Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 26 Oct 2022 22:20:33 +0800 Subject: [PATCH 1/4] tools: sign-image: break image signing into a library Move the code used to sign images into its own library file. This will enable us to use the image signing functions from other code. Signed-off-by: Sean Cross --- tools/src/bin/make-renode-boot.rs | 234 ++++++++++++++++++++++++++++++ tools/src/bin/sign-image.rs | 97 ++----------- tools/src/sign_image.rs | 110 ++++++++++++++ 3 files changed, 354 insertions(+), 87 deletions(-) create mode 100644 tools/src/bin/make-renode-boot.rs create mode 100644 tools/src/sign_image.rs diff --git a/tools/src/bin/make-renode-boot.rs b/tools/src/bin/make-renode-boot.rs new file mode 100644 index 000000000..95b5ff9e5 --- /dev/null +++ b/tools/src/bin/make-renode-boot.rs @@ -0,0 +1,234 @@ +#[macro_use] +extern crate clap; + +extern crate crc; + +use std::convert::TryInto; +use std::fs::File; + +use tools::elf::{read_minielf, read_program}; +use tools::tags::bflg::Bflg; +use tools::tags::inie::IniE; +use tools::tags::memory::{MemoryRegion, MemoryRegions}; +use tools::tags::pnam::ProcessNames; +use tools::tags::xkrn::XousKernel; +use tools::utils::{parse_csr_csv, parse_u32}; +use tools::xous_arguments::XousArguments; + +use clap::{App, Arg}; + +struct RamConfig { + offset: u32, + size: u32, + name: u32, + regions: MemoryRegions, + memory_required: u32, +} + +fn csr_to_config(hv: tools::utils::CsrConfig, ram_config: &mut RamConfig) { + let mut found_ram_name = None; + fn round_mem(src: u32) -> u32 { + (src + 4095) & !4095 + } + // Look for the largest "ram" block, which we'll treat as main memory + for (k, v) in &hv.regions { + if k.find("ram").is_some() && v.length > ram_config.size { + ram_config.size = round_mem(v.length); + ram_config.offset = v.start; + found_ram_name = Some(k.clone()); + } + } + + if found_ram_name.is_none() { + eprintln!("Error: Couldn't find a memory region named \"ram\" in config file"); + return; + } + + // Now that we know which block is ram, add the other regions. + let found_ram_name = MemoryRegion::make_name(&found_ram_name.unwrap()); + for (k, v) in &hv.regions { + ram_config.memory_required += round_mem(v.length) / 4096; + let region_name = MemoryRegion::make_name(k); + // Don't add the RAM section to the extra regions block. + if region_name == found_ram_name { + ram_config.name = region_name; + continue; + } + // Don't add empty sections. + if round_mem(v.length) == 0 { + continue; + } + ram_config + .regions + .add(MemoryRegion::new(v.start, round_mem(v.length), region_name)); + } +} +fn main() { + env_logger::init(); + let matches = App::new("Xous Image Creator") + .version(crate_version!()) + .author("Sean Cross ") + .about("Create a boot image for Xous") + .arg( + Arg::with_name("kernel") + .short("k") + .long("kernel") + .value_name("KERNEL_ELF") + .takes_value(true) + .required(true) + .help("Kernel ELF image to bundle into the image"), + ) + .arg( + Arg::with_name("init") + .short("i") + .long("init") + .takes_value(true) + .multiple(true) + .number_of_values(1) + .help("Initial program to load"), + ) + .arg( + Arg::with_name("svd") + .short("s") + .long("svd") + .value_name("SOC_SVD") + .help("soc.csv file from litex") + .takes_value(true) + .required_unless_one(&["ram", "svd", "csv"]), + ) + .arg( + Arg::with_name("debug") + .short("d") + .long("debug") + .takes_value(false) + .help("Reduce kernel-userspace security and enable debugging programs"), + ) + .arg( + Arg::with_name("output") + .value_name("OUTPUT") + .required(true) + .help("Output file to store tag and init information"), + ) + .get_matches(); + + let mut ram_config = RamConfig { + offset: Default::default(), + size: Default::default(), + name: MemoryRegion::make_name("sram"), + regions: MemoryRegions::new(), + memory_required: 0, + }; + + let mut process_names = ProcessNames::new(); + + if let Some(soc_svd) = matches.value_of("svd") { + let soc_svd_file = std::fs::File::open(soc_svd).unwrap(); + let desc = svd2utra::parse_svd(soc_svd_file).unwrap(); + let mut map = std::collections::BTreeMap::new(); + + let mut csr_top = 0; + for peripheral in desc.peripherals { + if peripheral.base > csr_top { + csr_top = peripheral.base; + } + } + for region in desc.memory_regions { + // Ignore the "CSR" region and manually reconstruct it, because this + // region is largely empty and we want to avoid allocating too much space. + if region.name == "CSR" { + const PAGE_SIZE: usize = 4096; + // round to the nearest page, then add one page as the last entry in the csr_top + // is an alloatable page, and not an end-stop. + let length = if csr_top - region.base & (PAGE_SIZE - 1) == 0 { + csr_top - region.base + } else { + ((csr_top - region.base) & !(PAGE_SIZE - 1)) + PAGE_SIZE + } + PAGE_SIZE; + map.insert( + region.name.to_lowercase(), + tools::utils::CsrMemoryRegion { + start: region.base.try_into().unwrap(), + length: length.try_into().unwrap(), + }, + ); + } else { + map.insert( + region.name.to_lowercase(), + tools::utils::CsrMemoryRegion { + start: region.base.try_into().unwrap(), + length: region.size.try_into().unwrap(), + }, + ); + } + } + csr_to_config(tools::utils::CsrConfig { regions: map }, &mut ram_config); + } + + let mut args = XousArguments::new(ram_config.offset, ram_config.size, ram_config.name); + + if !ram_config.regions.is_empty() { + args.add(ram_config.regions); + } + + if matches.is_present("debug") { + args.add(Bflg::new().debug()); + } + + let kernel = read_program( + matches + .value_of("kernel") + .expect("kernel was somehow missing"), + ) + .expect("unable to read kernel"); + + process_names.set(1, "kernel"); + if let Some(init_paths) = matches.values_of("init") { + let mut pid = 2; + for init_path in init_paths { + let program_name = std::path::Path::new(init_path); + process_names.set( + pid, + program_name + .file_stem() + .expect("program had no name") + .to_str() + .expect("program name is not valid utf-8"), + ); + pid += 1; + let init = read_minielf(init_path).expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + } + } + + let xkrn = XousKernel::new( + kernel.text_offset, + kernel.text_size, + kernel.data_offset, + kernel.data_size, + kernel.bss_size, + kernel.entry_point, + kernel.program, + ); + args.add(xkrn); + + args.add(process_names); + + // Add tags for init and kernel. These point to the actual data, which should + // immediately follow the tags. Therefore, we must know the length of the tags + // before we create them. + + let output_filename = matches + .value_of("output") + .expect("output filename not present"); + let f = File::create(output_filename) + .unwrap_or_else(|_| panic!("Couldn't create output file {}", output_filename)); + args.write(&f).expect("Couldn't write to args"); + + println!("Arguments: {}", args); + + println!( + "Runtime will require {} bytes to track memory allocations", + ram_config.memory_required + ); + println!("Image created in file {}", output_filename); +} diff --git a/tools/src/bin/sign-image.rs b/tools/src/bin/sign-image.rs index f625e0a9a..3d5fe2574 100644 --- a/tools/src/bin/sign-image.rs +++ b/tools/src/bin/sign-image.rs @@ -1,6 +1,7 @@ use clap::{crate_version, App, Arg}; -use std::io::{Read, Write, ErrorKind, Error}; +use std::io::{Error, ErrorKind, Read, Write}; use std::path::Path; +use tools::sign_image::{load_pem, sign_file}; use ring::signature::Ed25519KeyPair; @@ -9,86 +10,6 @@ const LOADER_VERSION: u32 = 1; use xous_semver::SemVer; -fn image_sign( - input: &S, - output: &T, - private_key: &pem::Pem, - defile: bool, - minver: &Option, -) -> Result<(), Box> -where - S: AsRef, - T: AsRef, -{ - let mut source = vec![]; - let mut source_file = std::fs::File::open(input)?; - let mut dest_file = std::fs::File::create(output)?; - source_file.read_to_end(&mut source)?; - - // Append version information to the binary. Appending it here means it is part - // of the signed bundle. - let minver_bytes = if let Some(mv) = minver {mv.into()} else {[0u8; 16]}; - let semver: [u8; 16] = SemVer::from_git() - .map_err(|_| Error::new(ErrorKind::Other, "error parsing current Git rev"))? - .into(); - // extra data appended here needs to be reflected in two places in Xous: - // 1. root-keys/src/implementation.rs @ sign-loader() - // 2. graphics-server/src/main.rs @ Some(Opcode::BulkReadfonts) - // This is because memory ownership is split between two crates for performance reasons: - // the direct memory page of fonts belongs to the graphics server, to avoid having to send - // a message on every font lookup. However, the keys reside in root-keys, so therefore, - // a bulk read operation has to shuttle font data back to the root-keys crate. Of course, - // the appended metadata is in the font region, so, this data has to be shuttled back. - // The graphics server is also entirely naive to how much cryptographic data is in the font - // region, and I think it's probably better for it to stay that way. - source.append(&mut minver_bytes.to_vec()); - source.append(&mut semver.to_vec()); - for &b in LOADER_VERSION.to_le_bytes().iter() { - source.push(b); - } - for &b in (source.len() as u32).to_le_bytes().iter() { - source.push(b); - } - - // NOTE NOTE NOTE - // can't find a good ASN.1 ED25519 key decoder, just relying on the fact that the last - // 32 bytes are "always" the private key. always? the private key? - let signing_key = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&private_key.contents) - .map_err(|e| format!("{}", e))?; - let signature = signing_key.sign(&source); - - dest_file.write_all(&LOADER_VERSION.to_le_bytes())?; - dest_file.write_all(&(source.len() as u32).to_le_bytes())?; - - // Write the signature data - let signature_u8 = &signature.as_ref(); - dest_file.write_all(signature_u8)?; - - // Pad the first sector to 4096 bytes. - let mut v = vec![]; - v.resize(4096 - 4 - 4 - signature_u8.len(), 0); - dest_file.write_all(&v)?; - - // Fill the remainder of the source data - - if defile { - println!("WARNING: defiling the loader image. This corrupts the binary and should cause it to fail the signature check."); - source[16778] ^= 0x1 // flip one bit at some random offset - } - - dest_file.write_all(&source)?; - - Ok(()) -} - -fn load_pem(src: &str) -> Result> { - let mut input = vec![]; - let mut pemfile = std::fs::File::open(src)?; - pemfile.read_to_end(&mut input)?; - - Ok(pem::parse(input)?) -} - fn main() -> Result<(), Box> { let matches = App::new("sign-image") .version(crate_version!()) @@ -160,10 +81,12 @@ fn main() -> Result<(), Box> { .get_matches(); let minver = if let Some(minver_str) = matches.value_of("min-xous-ver") { - Some( - SemVer::from_str(minver_str) - .map_err(|_| Error::new(ErrorKind::InvalidInput, "Minimum version semver format incorrect"))? - ) + Some(SemVer::from_str(minver_str).map_err(|_| { + Error::new( + ErrorKind::InvalidInput, + "Minimum version semver format incorrect", + ) + })?) } else { None }; @@ -183,7 +106,7 @@ fn main() -> Result<(), Box> { Err("invalid loader private key type")?; } println!("Signing loader"); - image_sign( + sign_file( &loader_image, &loader_output, &loader_pkey, @@ -206,7 +129,7 @@ fn main() -> Result<(), Box> { Err("invalid kernel private key type")?; } println!("Signing kernel"); - image_sign( + sign_file( &kernel_image, &kernel_output, &kernel_pkey, diff --git a/tools/src/sign_image.rs b/tools/src/sign_image.rs new file mode 100644 index 000000000..25107ef42 --- /dev/null +++ b/tools/src/sign_image.rs @@ -0,0 +1,110 @@ +use std::io::{Error, ErrorKind, Read, Write}; +use std::path::Path; + +use ring::signature::Ed25519KeyPair; + +const LOADER_VERSION: u32 = 1; + +use xous_semver::SemVer; + +pub fn load_pem(src: &str) -> Result> { + let mut input = vec![]; + let mut pemfile = std::fs::File::open(src)?; + pemfile.read_to_end(&mut input)?; + + Ok(pem::parse(input)?) +} + +fn semver_to_u8() -> Result<[u8; 16], &'static str> { + let a = SemVer::from_git()?; + Ok(a.into()) +} + +pub fn sign_image( + source: &[u8], + private_key: &pem::Pem, + defile: bool, + minver: &Option, + semver: Option<[u8; 16]>, +) -> Result, Box> { + let mut source = source.to_owned(); + let mut dest_file = vec![]; + + // Append version information to the binary. Appending it here means it is part + // of the signed bundle. + let minver_bytes = if let Some(mv) = minver { + mv.into() + } else { + [0u8; 16] + }; + let semver: [u8; 16] = semver + .ok_or_else(|| semver_to_u8()) + .map_err(|_| Error::new(ErrorKind::Other, "error parsing current Git rev"))?; + // extra data appended here needs to be reflected in two places in Xous: + // 1. root-keys/src/implementation.rs @ sign-loader() + // 2. graphics-server/src/main.rs @ Some(Opcode::BulkReadfonts) + // This is because memory ownership is split between two crates for performance reasons: + // the direct memory page of fonts belongs to the graphics server, to avoid having to send + // a message on every font lookup. However, the keys reside in root-keys, so therefore, + // a bulk read operation has to shuttle font data back to the root-keys crate. Of course, + // the appended metadata is in the font region, so, this data has to be shuttled back. + // The graphics server is also entirely naive to how much cryptographic data is in the font + // region, and I think it's probably better for it to stay that way. + source.append(&mut minver_bytes.to_vec()); + source.append(&mut semver.to_vec()); + for &b in LOADER_VERSION.to_le_bytes().iter() { + source.push(b); + } + for &b in (source.len() as u32).to_le_bytes().iter() { + source.push(b); + } + + // NOTE NOTE NOTE + // can't find a good ASN.1 ED25519 key decoder, just relying on the fact that the last + // 32 bytes are "always" the private key. always? the private key? + let signing_key = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&private_key.contents) + .map_err(|e| format!("{}", e))?; + let signature = signing_key.sign(&source); + + dest_file.write_all(&LOADER_VERSION.to_le_bytes())?; + dest_file.write_all(&(source.len() as u32).to_le_bytes())?; + + // Write the signature data + let signature_u8 = &signature.as_ref(); + dest_file.write_all(signature_u8)?; + + // Pad the first sector to 4096 bytes. + let mut v = vec![]; + v.resize(4096 - 4 - 4 - signature_u8.len(), 0); + dest_file.write_all(&v)?; + + // Fill the remainder of the source data + + if defile { + println!("WARNING: defiling the loader image. This corrupts the binary and should cause it to fail the signature check."); + source[16778] ^= 0x1 // flip one bit at some random offset + } + + Ok(dest_file) +} + +pub fn sign_file( + input: &S, + output: &T, + private_key: &pem::Pem, + defile: bool, + minver: &Option, +) -> Result<(), Box> +where + S: AsRef, + T: AsRef, +{ + let mut source = vec![]; + let mut source_file = std::fs::File::open(input)?; + let mut dest_file = std::fs::File::create(output)?; + source_file.read_to_end(&mut source)?; + + let result = sign_image(&source, private_key, defile, minver, None)?; + dest_file.write_all(&result)?; + Ok(()) +} From 46cd5e709877e127deafa0b44e397c579ac2ec5b Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 26 Oct 2022 22:21:24 +0800 Subject: [PATCH 2/4] tools: elf: allow loading files from &[u8] Instead of assuming everything is a file or a path, allow loading ELF files from u8 slices. This will enable us to create images with `include_bytes!()`. Signed-off-by: Sean Cross --- tools/src/elf.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tools/src/elf.rs b/tools/src/elf.rs index 8c4a88b53..b9dd01320 100644 --- a/tools/src/elf.rs +++ b/tools/src/elf.rs @@ -56,7 +56,11 @@ impl fmt::Display for MiniElfSection { write!( f, "Section {:13} {:6} bytes loading into {:08x}..{:08x} flags: {:?}", - self.name, self.size, self.virt, self.virt + self.size, self.flags + self.name, + self.size, + self.virt, + self.virt + self.size, + self.flags ) } } @@ -133,6 +137,10 @@ pub fn read_program>(filename: P) -> Result Result { let elf = ElfFile::new(&b).map_err(|x| ElfReadError::ParseElfError(x))?; let entry_point = elf.header.pt2.entry_point() as u32; let mut program_data = Cursor::new(Vec::new()); @@ -276,6 +284,10 @@ pub fn read_minielf>(filename: P) -> Result Result { let elf = ElfFile::new(&b).map_err(|x| ElfReadError::ParseElfError(x))?; let entry_point = elf.header.pt2.entry_point() as u32; let mut program_data = Cursor::new(Vec::new()); From 2382d57dd6f8da7cb887bd577b6d240b28121e2e Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 26 Oct 2022 22:22:18 +0800 Subject: [PATCH 3/4] tools: add sign_image.rs Signed-off-by: Sean Cross --- tools/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/src/lib.rs b/tools/src/lib.rs index 8196bd896..87f18cc2b 100644 --- a/tools/src/lib.rs +++ b/tools/src/lib.rs @@ -3,5 +3,6 @@ extern crate log; #[macro_use] pub mod xous_arguments; pub mod elf; +pub mod sign_image; pub mod tags; pub mod utils; From 2cf8ff12a66307e4f5d674bf2899dbfd9983a50c Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 26 Oct 2022 22:22:31 +0800 Subject: [PATCH 4/4] tools: add make-renode-boot This experimental tool can be used to create all-in-one images based on precomputed file lists. It generates "test images" using just the bare minimum number of processes. This program includes all the keys, kernel, and initial images required to support a simple program. Signed-off-by: Sean Cross --- tools/Cargo.toml | 3 + tools/src/bin/make-renode-boot.rs | 258 +++++++++++++++--------------- 2 files changed, 134 insertions(+), 127 deletions(-) diff --git a/tools/Cargo.toml b/tools/Cargo.toml index a9e7681d0..547431a32 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -27,6 +27,9 @@ name = "copy-object" [[bin]] name = "create-image" +[[bin]] +name = "make-renode-boot" + [[bin]] name = "make-tags" diff --git a/tools/src/bin/make-renode-boot.rs b/tools/src/bin/make-renode-boot.rs index 95b5ff9e5..f312ef2c2 100644 --- a/tools/src/bin/make-renode-boot.rs +++ b/tools/src/bin/make-renode-boot.rs @@ -1,22 +1,18 @@ -#[macro_use] -extern crate clap; - extern crate crc; +use std::collections::VecDeque; use std::convert::TryInto; use std::fs::File; +use std::io::Write; -use tools::elf::{read_minielf, read_program}; -use tools::tags::bflg::Bflg; +use tools::elf::{process_minielf, process_program, read_minielf}; +use tools::sign_image::sign_image; use tools::tags::inie::IniE; use tools::tags::memory::{MemoryRegion, MemoryRegions}; use tools::tags::pnam::ProcessNames; use tools::tags::xkrn::XousKernel; -use tools::utils::{parse_csr_csv, parse_u32}; use tools::xous_arguments::XousArguments; -use clap::{App, Arg}; - struct RamConfig { offset: u32, size: u32, @@ -63,53 +59,8 @@ fn csr_to_config(hv: tools::utils::CsrConfig, ram_config: &mut RamConfig) { .add(MemoryRegion::new(v.start, round_mem(v.length), region_name)); } } -fn main() { +fn create_image(init_programs: &[String]) -> std::io::Result> { env_logger::init(); - let matches = App::new("Xous Image Creator") - .version(crate_version!()) - .author("Sean Cross ") - .about("Create a boot image for Xous") - .arg( - Arg::with_name("kernel") - .short("k") - .long("kernel") - .value_name("KERNEL_ELF") - .takes_value(true) - .required(true) - .help("Kernel ELF image to bundle into the image"), - ) - .arg( - Arg::with_name("init") - .short("i") - .long("init") - .takes_value(true) - .multiple(true) - .number_of_values(1) - .help("Initial program to load"), - ) - .arg( - Arg::with_name("svd") - .short("s") - .long("svd") - .value_name("SOC_SVD") - .help("soc.csv file from litex") - .takes_value(true) - .required_unless_one(&["ram", "svd", "csv"]), - ) - .arg( - Arg::with_name("debug") - .short("d") - .long("debug") - .takes_value(false) - .help("Reduce kernel-userspace security and enable debugging programs"), - ) - .arg( - Arg::with_name("output") - .value_name("OUTPUT") - .required(true) - .help("Output file to store tag and init information"), - ) - .get_matches(); let mut ram_config = RamConfig { offset: Default::default(), @@ -121,48 +72,46 @@ fn main() { let mut process_names = ProcessNames::new(); - if let Some(soc_svd) = matches.value_of("svd") { - let soc_svd_file = std::fs::File::open(soc_svd).unwrap(); - let desc = svd2utra::parse_svd(soc_svd_file).unwrap(); - let mut map = std::collections::BTreeMap::new(); + let soc_svd_file = include_bytes!("../../../utralib/renode/renode.svd"); + let desc = svd2utra::parse_svd(soc_svd_file.as_slice()).unwrap(); + let mut map = std::collections::BTreeMap::new(); - let mut csr_top = 0; - for peripheral in desc.peripherals { - if peripheral.base > csr_top { - csr_top = peripheral.base; - } + let mut csr_top = 0; + for peripheral in desc.peripherals { + if peripheral.base > csr_top { + csr_top = peripheral.base; } - for region in desc.memory_regions { - // Ignore the "CSR" region and manually reconstruct it, because this - // region is largely empty and we want to avoid allocating too much space. - if region.name == "CSR" { - const PAGE_SIZE: usize = 4096; - // round to the nearest page, then add one page as the last entry in the csr_top - // is an alloatable page, and not an end-stop. - let length = if csr_top - region.base & (PAGE_SIZE - 1) == 0 { - csr_top - region.base - } else { - ((csr_top - region.base) & !(PAGE_SIZE - 1)) + PAGE_SIZE - } + PAGE_SIZE; - map.insert( - region.name.to_lowercase(), - tools::utils::CsrMemoryRegion { - start: region.base.try_into().unwrap(), - length: length.try_into().unwrap(), - }, - ); - } else { - map.insert( - region.name.to_lowercase(), - tools::utils::CsrMemoryRegion { - start: region.base.try_into().unwrap(), - length: region.size.try_into().unwrap(), - }, - ); - } - } - csr_to_config(tools::utils::CsrConfig { regions: map }, &mut ram_config); } + for region in desc.memory_regions { + // Ignore the "CSR" region and manually reconstruct it, because this + // region is largely empty and we want to avoid allocating too much space. + if region.name == "CSR" { + const PAGE_SIZE: usize = 4096; + // round to the nearest page, then add one page as the last entry in the csr_top + // is an alloatable page, and not an end-stop. + let length = if csr_top - region.base & (PAGE_SIZE - 1) == 0 { + csr_top - region.base + } else { + ((csr_top - region.base) & !(PAGE_SIZE - 1)) + PAGE_SIZE + } + PAGE_SIZE; + map.insert( + region.name.to_lowercase(), + tools::utils::CsrMemoryRegion { + start: region.base.try_into().unwrap(), + length: length.try_into().unwrap(), + }, + ); + } else { + map.insert( + region.name.to_lowercase(), + tools::utils::CsrMemoryRegion { + start: region.base.try_into().unwrap(), + length: region.size.try_into().unwrap(), + }, + ); + } + } + csr_to_config(tools::utils::CsrConfig { regions: map }, &mut ram_config); let mut args = XousArguments::new(ram_config.offset, ram_config.size, ram_config.name); @@ -170,34 +119,59 @@ fn main() { args.add(ram_config.regions); } - if matches.is_present("debug") { - args.add(Bflg::new().debug()); - } - - let kernel = read_program( - matches - .value_of("kernel") - .expect("kernel was somehow missing"), - ) + let kernel = process_program(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-kernel" + )) .expect("unable to read kernel"); - process_names.set(1, "kernel"); - if let Some(init_paths) = matches.values_of("init") { - let mut pid = 2; - for init_path in init_paths { - let program_name = std::path::Path::new(init_path); - process_names.set( - pid, - program_name - .file_stem() - .expect("program had no name") - .to_str() - .expect("program name is not valid utf-8"), - ); - pid += 1; - let init = read_minielf(init_path).expect("couldn't parse init file"); - args.add(IniE::new(init.entry_point, init.sections, init.program)); - } + + let pid = 2; + let init = process_minielf(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-ticktimer" + )) + .expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + process_names.set(pid, "xous-ticktimer"); + + let pid = pid + 1; + let init = process_minielf(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-log" + )) + .expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + process_names.set(pid, "xous-log"); + + let pid = pid + 1; + let init = process_minielf(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-names" + )) + .expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + process_names.set(pid, "xous-names"); + + let pid = pid + 1; + let init = process_minielf(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-susres" + )) + .expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + process_names.set(pid, "xous-susres"); + + let mut pid = pid + 1; + for init_path in init_programs { + let program_name = std::path::Path::new(&init_path); + println!("Adding {} to output", program_name.display()); + process_names.set( + pid, + program_name + .file_stem() + .expect("program had no name") + .to_str() + .expect("program name is not valid utf-8"), + ); + let init = read_minielf(init_path).expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + pid += 1; } let xkrn = XousKernel::new( @@ -216,13 +190,8 @@ fn main() { // Add tags for init and kernel. These point to the actual data, which should // immediately follow the tags. Therefore, we must know the length of the tags // before we create them. - - let output_filename = matches - .value_of("output") - .expect("output filename not present"); - let f = File::create(output_filename) - .unwrap_or_else(|_| panic!("Couldn't create output file {}", output_filename)); - args.write(&f).expect("Couldn't write to args"); + let mut f = vec![]; + args.write(&mut f).expect("Couldn't write to args"); println!("Arguments: {}", args); @@ -230,5 +199,40 @@ fn main() { "Runtime will require {} bytes to track memory allocations", ram_config.memory_required ); - println!("Image created in file {}", output_filename); + Ok(f) +} + +fn main() -> Result<(), Box> { + let mut args: VecDeque = std::env::args().collect(); + println!("Args: {:?}", args); + let program = args.pop_front().ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::Other, "program name not present") + })?; + let output_filename = args.pop_front().ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::Other, "output filename not present") + })?; + args.make_contiguous(); + + if args.len() == 0 { + return Err("no init programs specified".into()); + } + println!("Program: {}", program); + println!("Output file: {}", output_filename); + println!("Init args: {:?}", args); + let xous_presign_img = create_image(args.as_slices().0)?; + + let xous_pkey = pem::parse(include_bytes!("../../../devkey/dev.key"))?; + if xous_pkey.tag != "PRIVATE KEY" { + println!("Xous image key was a {}, not a PRIVATE KEY", xous_pkey.tag); + return Err("invalid xous image private key type".into()); + } + println!("Signing output image"); + let xous_img = sign_image(&xous_presign_img, &xous_pkey, false, &None, Some([0u8; 16]))?; + + let mut output_file = File::create(&output_filename)?; + output_file.write_all(&xous_img)?; + + println!("Successfully wrote {}", output_filename); + + Ok(()) }