From fd5e07b983e5fd36f272873dd20e1213029dd65a Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 13 Jul 2021 22:25:46 +0800 Subject: [PATCH 01/12] emulation: add broken engine implementation Signed-off-by: Sean Cross --- emulation/peripherals/engine.cs | 193 ++++++++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 emulation/peripherals/engine.cs diff --git a/emulation/peripherals/engine.cs b/emulation/peripherals/engine.cs new file mode 100644 index 000000000..119839804 --- /dev/null +++ b/emulation/peripherals/engine.cs @@ -0,0 +1,193 @@ +// +// Copyright (c) 2010-2018 Antmicro +// Copyright (c) 2011-2015 Realtime Embedded +// +// This file is licensed under the MIT License. +// Full license text is available in 'licenses/MIT.txt'. +// +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using Antmicro.Renode.Core; +using Antmicro.Renode.Core.Structure.Registers; +using Antmicro.Renode.Logging; +using Antmicro.Renode.Peripherals.Bus; +using Antmicro.Renode.Peripherals.CPU; + +namespace Antmicro.Renode.Peripherals.Miscellaneous +{ + public class Engine : IDoubleWordPeripheral, IProvidesRegisterCollection, IKnownSize + { + public Engine(Machine machine) + { + this.machine = machine; + machine.SystemBus.AddWatchpointHook(this.bufferAddress, SysbusAccessWidth.DoubleWord, Access.Write, (cpu, encounteredAddress, width, encounteredValue) => + { + this.Log(LogLevel.Error, "ENGINE: Adding word 0x{0:X} (at address 0x{1:X}) to hash", encounteredValue, encounteredAddress); + // var inputBuffer = new byte[4]; + // if (this.inputIsSwapped.Value) + // { + // inputBuffer[3] = (byte)(encounteredValue >> 0); + // inputBuffer[2] = (byte)(encounteredValue >> 8); + // inputBuffer[1] = (byte)(encounteredValue >> 16); + // inputBuffer[0] = (byte)(encounteredValue >> 24); + // } + // else + // { + // inputBuffer[0] = (byte)(encounteredValue >> 0); + // inputBuffer[1] = (byte)(encounteredValue >> 8); + // inputBuffer[2] = (byte)(encounteredValue >> 16); + // inputBuffer[3] = (byte)(encounteredValue >> 24); + // if (this.usingSha256.Value) + // { + // this.sha256.TransformBlock(inputBuffer, 0, 4, this.hash, 0); + // } + // else + // { + // this.sha512.TransformBlock(inputBuffer, 0, 4, this.hash, 0); + // } + // } + // this.digestedLength += 8; + }); + RegistersCollection = new DoubleWordRegisterCollection(this); + this.IRQ = new GPIO(); + Reset(); + DefineRegisters(); + } + + private void DefineRegisters() + { + Registers.WINDOW.Define(this) + .WithValueField(0, 4, name: "WINDOW", valueProviderCallback: (_) => { return this.window; }, changeCallback: (_, value) => { this.window = (byte)(value & 0xf); }) + ; + + Registers.MPSTART.Define(this) + .WithValueField(0, 10, name: "MPSTART", valueProviderCallback: (_) => { return this.mpstart; }, changeCallback: (_, value) => { this.mpstart = (UInt16)(value & 0x3ff); }) + ; + + Registers.MPLEN.Define(this) + .WithValueField(0, 10, name: "MPLEN", valueProviderCallback: (_) => { return this.mplen; }, changeCallback: (_, value) => { this.mplen = (UInt16)(value & 0x3ff); }) + ; + + Registers.CONTROL.Define(this) + .WithFlag(0, name: "GO", changeCallback: (_, value) => + { + if (value) + { + this.Log(LogLevel.Error, "Beginning ENGINE execution from 0x{0:X} (program length {1}) using register bank {2}", this.mpstart, this.mplen, this.window); + + } + }) + ; + + Registers.MPRESUME.Define(this) + .WithValueField(0, 10, name: "MPRESUME", valueProviderCallback: (_) => { return this.mpresume; }, changeCallback: (_, value) => { this.mpresume = (UInt16)(value & 0x3ff); }) + ; + + Registers.POWER.Define(this) + .WithFlag(0, out powerIsOn, FieldMode.Read | FieldMode.Write, name: "ON") + .WithFlag(1, out pauseRequest, FieldMode.Read | FieldMode.Write, name: "PAUSE_REQ") + ; + + Registers.STATUS.Define(this) + .WithFlag(0, name: "RUNNING", valueProviderCallback: (_) => false) + .WithValueField(1, 10, name: "MPC", valueProviderCallback: (_) => 0) + .WithFlag(11, name: "PAUSE_GNT", valueProviderCallback: (_) => false) + ; + + Registers.EV_STATUS.Define32(this) + .WithFlag(0, FieldMode.Read, name: "FINISHED", valueProviderCallback: _ => illegalOpcodeStatus) + .WithFlag(1, FieldMode.Read, name: "ILLEGAL_OPCODE", valueProviderCallback: _ => finishedStatus) + ; + + Registers.EV_PENDING.Define32(this) + .WithFlag(0, out illegalOpcodePending, FieldMode.Read | FieldMode.WriteOneToClear, name: "FINISHED", changeCallback: (_, __) => UpdateInterrupts()) + .WithFlag(1, out finishedPending, FieldMode.Read | FieldMode.WriteOneToClear, name: "ILLEGAL_OPCODE", changeCallback: (_, __) => UpdateInterrupts()) + ; + + Registers.EV_ENABLE.Define32(this) + .WithFlag(0, out illegalOpcodeEnabled, name: "FINISHED", changeCallback: (_, __) => UpdateInterrupts()) + .WithFlag(1, out finishedEnabled, name: "ILLEGAL_OPCODE", changeCallback: (_, __) => UpdateInterrupts()) + ; + + Registers.INSTRUCTION.Define(this) + .WithValueField(0, 32, valueProviderCallback: _ => { return 11 /* Opcode FIN */; }) + ; + } + + private void UpdateInterrupts() + { + if (this.illegalOpcodeStatus && this.illegalOpcodeEnabled.Value) + { + this.illegalOpcodePending.Value = true; + } + if (this.finishedStatus && this.finishedEnabled.Value) + { + this.finishedPending.Value = true; + } + IRQ.Set((this.illegalOpcodePending.Value && this.illegalOpcodeEnabled.Value) + || (this.finishedPending.Value && this.finishedEnabled.Value)); + } + + public void WriteDoubleWord(long address, uint value) + { + RegistersCollection.Write(address, value); + } + + public uint ReadDoubleWord(long offset) + { + return RegistersCollection.Read(offset); + } + + public long Size { get { return 4096; } } + public DoubleWordRegisterCollection RegistersCollection { get; private set; } + + public void Reset() + { + this.window = 0; + this.mpstart = 0; + this.mplen = 0; + this.mpresume = 0; + this.mpc = 0; + if (this.powerIsOn != null) { + this.powerIsOn.Value = false; + } + } + + private readonly Machine machine; + + public GPIO IRQ { get; private set; } + + private byte window; + private UInt16 mpstart; + private UInt16 mplen; + private UInt16 mpresume; + private UInt16 mpc; + private IFlagRegisterField powerIsOn; + private IFlagRegisterField pauseRequest; + private readonly uint bufferAddress = 0xE0020000; + + private IFlagRegisterField illegalOpcodeEnabled; + private IFlagRegisterField illegalOpcodePending; + private bool illegalOpcodeStatus; + + private IFlagRegisterField finishedEnabled; + private IFlagRegisterField finishedPending; + private bool finishedStatus; + + private enum Registers + { + WINDOW = 0x00, + MPSTART = 0x04, + MPLEN = 0x08, + CONTROL = 0x0c, + MPRESUME = 0x10, + POWER = 0x14, + STATUS = 0x18, + EV_STATUS = 0x1c, + EV_PENDING = 0x20, + EV_ENABLE = 0x24, + INSTRUCTION = 0x28 + } + } +} From 080c439b2233cbc5d79b18f0907c2fbddff8b2b8 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 14 Jul 2021 15:27:23 +0800 Subject: [PATCH 02/12] svd2repl: add memAddr and memSize to peripherals with memory For peripherals that bring their own memory, avoid generating a memory region and instead generate a peripheral with the appropriate size pointers. Signed-off-by: Sean Cross --- svd2repl/src/generate.rs | 67 +++++++++++++++++++++++++++------------- 1 file changed, 46 insertions(+), 21 deletions(-) diff --git a/svd2repl/src/generate.rs b/svd2repl/src/generate.rs index 96fceff8d..4146b186a 100644 --- a/svd2repl/src/generate.rs +++ b/svd2repl/src/generate.rs @@ -1,6 +1,8 @@ use quick_xml::events::Event; use quick_xml::Reader; +use std::collections::HashMap; use std::io::{BufRead, BufReader, Read, Write}; + #[derive(Debug)] pub enum ParseError { UnexpectedTag, @@ -496,7 +498,11 @@ sysbus: out.write_all(s.as_bytes()) } -fn print_memory_regions(regions: &[MemoryRegion], out: &mut U) -> std::io::Result<()> { +fn print_memory_regions( + regions: &[MemoryRegion], + cs_peripherals: &HashMap<&str, &str>, + out: &mut U, +) -> std::io::Result<()> { writeln!(out, "// Physical base addresses of memory regions")?; for region in regions { let region_name = region.name.to_lowercase(); @@ -515,14 +521,15 @@ fn print_memory_regions(regions: &[MemoryRegion], out: &mut U) -> std: continue; } - // Also ignore the sha512 region, since it's handled with the sha512 block - if region_name == "sha512" { + // Ignore any memory region with a name that matches a peripheral, since + // those regions are handled by the peripheral themselves. + if cs_peripherals.contains_key(region_name.as_str()) { continue; } writeln!( out, - "mem_{}: Memory.MappedMemory @ sysbus 0x{:08x}", + "{}: Memory.MappedMemory @ sysbus 0x{:08x}", region_name, region.base )?; writeln!(out, " size: 0x{:08x}", region_size)?; @@ -534,24 +541,11 @@ fn print_memory_regions(regions: &[MemoryRegion], out: &mut U) -> std: fn print_peripherals( peripherals: &[Peripheral], + regions: &[MemoryRegion], + cs_peripherals: &HashMap<&str, &str>, constants: &[Constant], out: &mut U, ) -> std::io::Result<()> { - use std::collections::HashMap; - let mut cs_peripherals = HashMap::new(); - cs_peripherals.insert("app_uart", "UART.LiteX_UART"); - cs_peripherals.insert("console", "UART.LiteX_UART"); - cs_peripherals.insert("engine", "Miscellaneous.Engine"); - cs_peripherals.insert("i2c", "I2C.BetrustedI2C"); - cs_peripherals.insert("keyboard", "Input.BetrustedKbd"); - cs_peripherals.insert("keyrom", "Miscellaneous.Keyrom"); - cs_peripherals.insert("memlcd", "Video.BetrustedLCD"); - cs_peripherals.insert("sha512", "Miscellaneous.Sha512"); - cs_peripherals.insert("timer0", "Timers.LiteX_Timer_32"); - cs_peripherals.insert("trng_kernel", "Miscellaneous.BetrustedRNGKernel"); - cs_peripherals.insert("trng_server", "Miscellaneous.BetrustedRNGServer"); - cs_peripherals.insert("ticktimer", "Timers.TickTimer"); - cs_peripherals.insert("uart", "UART.LiteX_UART"); writeln!(out, "// Platform Peripherals")?; for peripheral in peripherals { @@ -582,6 +576,15 @@ fn print_peripherals( } } + // If there is a corresponding memory region, add it as parameters. + for region in regions.iter() { + if region.name.to_lowercase() == lc_name.as_str() { + writeln!(out, " memAddr: 0x{:x}", region.base)?; + writeln!(out, " memSize: 0x{:x}", region.size)?; + break; + } + } + // Note: we skip the `size` value here, since peripherals don't have a known size. // Add the interrupt, if one exists. @@ -626,10 +629,32 @@ pub fn parse_svd(src: T) -> Result { pub fn generate(src: T, dest: &mut U) -> Result<(), ParseError> { let description = parse_svd(src)?; + let mut cs_peripherals = HashMap::new(); + cs_peripherals.insert("app_uart", "UART.LiteX_UART"); + cs_peripherals.insert("console", "UART.LiteX_UART"); + cs_peripherals.insert("engine", "Miscellaneous.Engine"); + cs_peripherals.insert("i2c", "I2C.BetrustedI2C"); + cs_peripherals.insert("keyboard", "Input.BetrustedKbd"); + cs_peripherals.insert("keyrom", "Miscellaneous.Keyrom"); + cs_peripherals.insert("memlcd", "Video.BetrustedLCD"); + cs_peripherals.insert("sha512", "Miscellaneous.Sha512"); + cs_peripherals.insert("timer0", "Timers.LiteX_Timer_32"); + cs_peripherals.insert("trng_kernel", "Miscellaneous.BetrustedRNGKernel"); + cs_peripherals.insert("trng_server", "Miscellaneous.BetrustedRNGServer"); + cs_peripherals.insert("ticktimer", "Timers.TickTimer"); + cs_peripherals.insert("uart", "UART.LiteX_UART"); + print_header(dest).or(Err(ParseError::WriteError))?; - print_peripherals(&description.peripherals, &description.constants, dest) + print_peripherals( + &description.peripherals, + &description.memory_regions, + &cs_peripherals, + &description.constants, + dest, + ) + .or(Err(ParseError::WriteError))?; + print_memory_regions(&description.memory_regions, &cs_peripherals, dest) .or(Err(ParseError::WriteError))?; - print_memory_regions(&description.memory_regions, dest).or(Err(ParseError::WriteError))?; print_footer(dest).or(Err(ParseError::WriteError))?; Ok(()) From acc981638efbd22f233967a36494c1bf5dc46062 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 09:24:19 +0800 Subject: [PATCH 03/12] engine: only 4 tests are failing Signed-off-by: Sean Cross --- emulation/peripherals/engine.cs | 956 ++++++++++++++++++++++++++++++-- 1 file changed, 906 insertions(+), 50 deletions(-) diff --git a/emulation/peripherals/engine.cs b/emulation/peripherals/engine.cs index 119839804..00825d1b2 100644 --- a/emulation/peripherals/engine.cs +++ b/emulation/peripherals/engine.cs @@ -6,55 +6,415 @@ // Full license text is available in 'licenses/MIT.txt'. // using System; -using System.Collections.Generic; -using System.Security.Cryptography; +using System.Threading; +using System.Text; +using System.Linq; +using System.Globalization; +using System.Numerics; using Antmicro.Renode.Core; using Antmicro.Renode.Core.Structure.Registers; using Antmicro.Renode.Logging; using Antmicro.Renode.Peripherals.Bus; -using Antmicro.Renode.Peripherals.CPU; namespace Antmicro.Renode.Peripherals.Miscellaneous { - public class Engine : IDoubleWordPeripheral, IProvidesRegisterCollection, IKnownSize + public class EngineRam : IDoubleWordPeripheral, IKnownSize { - public Engine(Machine machine) + public EngineRam(Machine machine, Engine engine, long size) { this.machine = machine; - machine.SystemBus.AddWatchpointHook(this.bufferAddress, SysbusAccessWidth.DoubleWord, Access.Write, (cpu, encounteredAddress, width, encounteredValue) => + this.engine = engine; + this.size = size; + this.data = new UInt32[size / 4]; + this.FIELD_MAX = new UInt256(BigInteger.Pow(2, 255) - 19); + this.c0 = new UInt256(0); + this.c1 = new UInt256(1); + + // (A-2)/4 + this.c2 = new UInt256(121665); + this.c3 = this.FIELD_MAX; + // (A+2)/4 + this.c4 = new UInt256(121666); + this.c5 = new UInt256(5); + this.c6 = new UInt256(10); + this.c7 = new UInt256(20); + this.c8 = new UInt256(50); + this.c9 = new UInt256(100); + } + + public UInt256 FIELD_MAX; + // private UInt256 UINT_MAX; + private UInt256 c0; + private UInt256 c1; + private UInt256 c2; + private UInt256 c3; + private UInt256 c4; + private UInt256 c5; + private UInt256 c6; + private UInt256 c7; + private UInt256 c8; + private UInt256 c9; + private Machine machine; + private Engine engine; + private long size; + public UInt32[] data; + public long Size { get { return size; } } + + public void WriteDoubleWord(long address, uint value) + { + this.data[address / 4] = value; + } + + public uint ReadDoubleWord(long offset) + { + return this.data[offset / 4]; + } + + public UInt256 ReadRegister(ulong rf, ulong register, bool constant) + { + // this.Log(LogLevel.Error, "Reading register {0} (const? {1}) from rf {2}", register, constant, rf); + if (constant) { - this.Log(LogLevel.Error, "ENGINE: Adding word 0x{0:X} (at address 0x{1:X}) to hash", encounteredValue, encounteredAddress); - // var inputBuffer = new byte[4]; - // if (this.inputIsSwapped.Value) - // { - // inputBuffer[3] = (byte)(encounteredValue >> 0); - // inputBuffer[2] = (byte)(encounteredValue >> 8); - // inputBuffer[1] = (byte)(encounteredValue >> 16); - // inputBuffer[0] = (byte)(encounteredValue >> 24); - // } - // else - // { - // inputBuffer[0] = (byte)(encounteredValue >> 0); - // inputBuffer[1] = (byte)(encounteredValue >> 8); - // inputBuffer[2] = (byte)(encounteredValue >> 16); - // inputBuffer[3] = (byte)(encounteredValue >> 24); - // if (this.usingSha256.Value) - // { - // this.sha256.TransformBlock(inputBuffer, 0, 4, this.hash, 0); - // } - // else - // { - // this.sha512.TransformBlock(inputBuffer, 0, 4, this.hash, 0); - // } - // } - // this.digestedLength += 8; - }); - RegistersCollection = new DoubleWordRegisterCollection(this); + switch (register) + { + case 0: return this.c0; + case 1: return this.c1; + case 2: return this.c2; + case 3: return this.c3; + case 4: return this.c4; + case 5: return this.c5; + case 6: return this.c6; + case 7: return this.c7; + case 8: return this.c8; + case 9: return this.c9; + default: return new UInt256(0); + } + } + var src_bytes = new byte[32]; + + if ((rf >= 16) || (register >= 32)) + { + throw new Exception(String.Format("Register #{0} or RegisterFile {1} is out of range", register, rf)); + } + + for (ulong i = 0; i < (ulong)src_bytes.Length; i += 4) + { + var offset = 0x10000 + (rf * 512) + (register * 32) + i; + var bytes = BitConverter.GetBytes(this.data[offset / 4]); + if (bytes.Length != 4) + { + throw new Exception("Bytes was not equal to 4"); + } + for (ulong j = 0; j < (ulong)bytes.Length; j++) + { + if ((i + j) >= 32) + { + throw new Exception("i+j>=32"); + } + src_bytes[i + j] = bytes[j]; + } + } + // this.Log(LogLevel.Error, "Returning read value from {0}-byte array", src_bytes.Length); + return new UInt256(src_bytes); + } + + public void WriteRegister(long rf, long register, UInt256 value) + { + if ((rf >= 16) || (register >= 32)) + { + throw new Exception(String.Format("Register #{0} or RegisterFile {1} is out of range", register, rf)); + } + var offset = 0x10000 + (rf * 512) + (register * 32); + var bytes = value.ToByteArray(); + for (uint i = 0; i < (uint)bytes.Length; i += 4) + { + this.data[(offset + i) / 4] = (((uint)bytes[i + 0]) << 0) | (((uint)bytes[i + 1]) << 8) | (((uint)bytes[i + 2]) << 16) | ((uint)(bytes[i + 3]) << 24); + + } + } + + public void Reset() + { + for (var i = 0; i < this.data.Length; i++) + { + this.data[i] = 0; + } + } + } + + public class Opcode : IFormattable + { + public Opcode(UInt32 op) + { + this.Op = (op >> 0) & 0x3f; + + this.Ra = (op >> 6) & 0x1f; + this.Ca = ((op >> 11) & 1) == 1; + + this.Rb = (op >> 12) & 0x1f; + this.Cb = ((op >> 17) & 1) == 1; + + this.Wd = (op >> 18) & 0x1f; + + this.Immediate = (int)(op >> 23); + if ((this.Immediate & (1 << 8)) != 0) + { + this.Immediate = this.Immediate - (1 << 9); + } + } + + public String ConstantName(uint idx) + { + switch (idx) + { + case 0: return "zero"; + case 1: return "one"; + case 2: return "am24"; + case 3: return "field"; + case 4: return "ap24"; + case 5: return "five"; + case 6: return "ten"; + case 7: return "twenty"; + case 8: return "fifty"; + case 9: return "one hundred"; + default: return "undef"; + } + } + + public String RaName() + { + if (this.Ca) + { + return "#" + this.ConstantName(this.Ra).ToUpper(); + } + return "r" + this.Ra; + } + + public String RbName() + { + if (this.Cb) + { + return "#" + this.ConstantName(this.Rb).ToUpper(); + } + return "r" + this.Rb; + } + + public String WdName() + { + return "r" + this.Wd; + } + + public string Mnemonic() + { + switch (this.Op) + { + case 0: return "PSA"; + case 1: return "PSB"; + case 2: return "MSK"; + case 3: return "XOR"; + case 4: return "NOT"; + case 5: return "ADD"; + case 6: return "SUB"; + case 7: return "MUL"; + case 8: return "TRD"; + case 9: return "BRZ"; + case 10: return "FIN"; + case 11: return "SHL"; + case 12: return "XBT"; + default: return "UDF"; + } + } + + public string ToString(string format, IFormatProvider provider) + { + if ((this.Op == 0) || (this.Op == 4) || (this.Op == 8) || (this.Op == 11) || (this.Op == 12)) + { + return String.Format("{0} {1}, {2}", this.Mnemonic(), this.WdName(), this.RaName()); + } + else if (this.Op == 1) + { + return String.Format("{0} {1}, {2}", this.Mnemonic(), this.WdName(), this.RbName()); + } + else if (this.Op == 9) + { + return String.Format("{0} pc + {1}, {2}", this.Mnemonic(), this.Immediate, this.RaName()); + } + else if (this.Op == 10) + { + return this.Mnemonic(); + } + else if ((this.Op == 2) || (this.Op == 3) || (this.Op == 5) || (this.Op == 6) || (this.Op == 7)) // OK + { + return String.Format("{0} {1}, {2}, {3}", this.Mnemonic(), this.WdName(), this.RaName(), this.RbName()); + } + else + { + return "undef"; + } + // return "unhandled"; + } + + public UInt32 Op; + public UInt32 Ra; + public bool Ca; + public UInt32 Rb; + public bool Cb; + public UInt32 Wd; + public Int32 Immediate; + } + + + public class Engine : IDoubleWordPeripheral, IProvidesRegisterCollection, IKnownSize + { + public Engine(Machine machine, uint memAddr, uint memSize) + { + this.machine = machine; + this.engineRam = new EngineRam(machine, this, memSize); + machine.SystemBus.Register(this.engineRam, new BusRangeRegistration(memAddr, memSize)); + + this.RegistersCollection = new DoubleWordRegisterCollection(this); this.IRQ = new GPIO(); + this.shouldEndExecution = false; + this.startExecution = new SemaphoreSlim(0, 1); Reset(); DefineRegisters(); } + ~Engine() + { + if ((this.engineExecution != null) && (this.engineExecution.IsAlive)) + { + this.engineExecution.Abort(); + } + } + + private void EngineThread() + { + try + { + // this.Log(LogLevel.Error, "ENGINE: Beginning execution. Current MPC: 0x{0:X}", this.mpc); + this.mpc = this.mpstart; + while (true) + { + if (this.mpc >= this.mplen) + { + throw new Exception(String.Format("mpc exceeded program length of {0}", this.mplen)); + } + var op = new Opcode(this.engineRam.data[this.mpc]); + + // this.Log(LogLevel.Error, "RAM[0x{0:X}] {1}", this.mpc, op); + + switch (op.Op) + { + case 0: // PSA + this.engineRam.WriteRegister(this.window, op.Wd, this.engineRam.ReadRegister(this.window, op.Ra, op.Ca)); + break; + + case 1: // PSB + this.engineRam.WriteRegister(this.window, op.Wd, this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)); + break; + + case 2: // MSK + var bit = this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) & 1; + if (bit != 0) + { + this.engineRam.WriteRegister(this.window, op.Wd, this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)); + } + else + { + this.engineRam.WriteRegister(this.window, op.Wd, new UInt256(0)); + } + break; + + case 3: // XOR + this.engineRam.WriteRegister(this.window, op.Wd, + this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) ^ this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)); + break; + + case 4: // NOT + this.engineRam.WriteRegister(this.window, op.Wd, + ~this.engineRam.ReadRegister(this.window, op.Ra, op.Ca)); + break; + + case 5: // ADD + this.engineRam.WriteRegister(this.window, op.Wd, + this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) + this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)); + break; + + case 6: // SUB + this.engineRam.WriteRegister(this.window, op.Wd, + this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) - this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)); + break; + + case 7: // MUL + // this.Log(LogLevel.Error, "Ra: {0} Rb: {1} Wd: {2}", this.engineRam.ReadRegister(this.window, op.Ra, op.Ca), this.engineRam.ReadRegister(this.window, op.Rb, op.Cb), + // (this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) * this.engineRam.ReadRegister(this.window, op.Rb, op.Cb))); + this.engineRam.WriteRegister(this.window, op.Wd, + (this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) * this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)) + ); + break; + + case 8: // TRD + if (this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) >= this.engineRam.FIELD_MAX) + { + this.engineRam.WriteRegister(this.window, op.Wd, this.engineRam.FIELD_MAX); + } + else + { + this.engineRam.WriteRegister(this.window, op.Wd, new UInt256(0)); + } + break; + + case 9: // BRZ + if (this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) == 0) + { + this.mpc = (ushort)((int)this.mpc + op.Immediate); + } + break; + + case 10: // FIN + break; + + case 11: // SHL + this.engineRam.WriteRegister(this.window, op.Wd, + this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) << 1); + break; + + case 12: // XBT + if ((this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) & (new UInt256(1) << 254)) != 0) + { + this.engineRam.WriteRegister(this.window, op.Wd, new UInt256(1)); + } + else + { + this.engineRam.WriteRegister(this.window, op.Wd, new UInt256(0)); + } + break; + + default: + this.illegalOpcodeStatus = true; + throw new Exception("Unhandled opcode"); + } + this.mpc += 1; + if (op.Op == 10) + { + break; + } + // this.Log(LogLevel.Error, " (Result) {0}", this.engineRam.ReadRegister(this.window, op.Wd, false).ToString()); + } + } + catch (Exception e) + { + this.Log(LogLevel.Error, "ENGINE execution exception {0}", e); + } + this.finishedStatus = true; + this.engineExecution = null; + this.UpdateInterrupts(); + this.finishedStatus = false; + this.illegalOpcodeStatus = false; + // this.Log(LogLevel.Error, "ENGINE finished execution"); + } + private void DefineRegisters() { Registers.WINDOW.Define(this) @@ -62,26 +422,34 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous ; Registers.MPSTART.Define(this) - .WithValueField(0, 10, name: "MPSTART", valueProviderCallback: (_) => { return this.mpstart; }, changeCallback: (_, value) => { this.mpstart = (UInt16)(value & 0x3ff); }) + .WithValueField(0, 11, name: "MPSTART", valueProviderCallback: (_) => { return this.mpstart; }, changeCallback: (_, value) => { this.mpstart = (UInt16)(value & 0x7ff); }) ; Registers.MPLEN.Define(this) - .WithValueField(0, 10, name: "MPLEN", valueProviderCallback: (_) => { return this.mplen; }, changeCallback: (_, value) => { this.mplen = (UInt16)(value & 0x3ff); }) + .WithValueField(0, 11, name: "MPLEN", valueProviderCallback: _ => this.mplen, changeCallback: (_, value) => { this.mplen = (UInt16)(value & 0x7ff); }) ; Registers.CONTROL.Define(this) - .WithFlag(0, name: "GO", changeCallback: (_, value) => + .WithFlag(0, FieldMode.Write, name: "GO", writeCallback: (_, value) => { if (value) { - this.Log(LogLevel.Error, "Beginning ENGINE execution from 0x{0:X} (program length {1}) using register bank {2}", this.mpstart, this.mplen, this.window); - + if ((this.engineExecution != null) && (this.engineExecution.IsAlive)) + { + this.Log(LogLevel.Error, "ENGINE already executing -- not re-running"); + } + else + { + this.engineExecution = new Thread(new ThreadStart(this.EngineThread)); + this.engineExecution.IsBackground = true; + this.engineExecution.Start(); + } } }) ; Registers.MPRESUME.Define(this) - .WithValueField(0, 10, name: "MPRESUME", valueProviderCallback: (_) => { return this.mpresume; }, changeCallback: (_, value) => { this.mpresume = (UInt16)(value & 0x3ff); }) + .WithValueField(0, 11, name: "MPRESUME", valueProviderCallback: _ => this.mpresume, changeCallback: (_, value) => { this.mpresume = (UInt16)(value & 0x7ff); }) ; Registers.POWER.Define(this) @@ -90,38 +458,38 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous ; Registers.STATUS.Define(this) - .WithFlag(0, name: "RUNNING", valueProviderCallback: (_) => false) + .WithFlag(0, name: "RUNNING", valueProviderCallback: (_) => this.engineExecution.IsAlive) .WithValueField(1, 10, name: "MPC", valueProviderCallback: (_) => 0) .WithFlag(11, name: "PAUSE_GNT", valueProviderCallback: (_) => false) ; Registers.EV_STATUS.Define32(this) - .WithFlag(0, FieldMode.Read, name: "FINISHED", valueProviderCallback: _ => illegalOpcodeStatus) - .WithFlag(1, FieldMode.Read, name: "ILLEGAL_OPCODE", valueProviderCallback: _ => finishedStatus) + .WithFlag(0, FieldMode.Read, name: "FINISHED", valueProviderCallback: _ => finishedStatus) + .WithFlag(1, FieldMode.Read, name: "ILLEGAL_OPCODE", valueProviderCallback: _ => illegalOpcodeStatus) ; Registers.EV_PENDING.Define32(this) - .WithFlag(0, out illegalOpcodePending, FieldMode.Read | FieldMode.WriteOneToClear, name: "FINISHED", changeCallback: (_, __) => UpdateInterrupts()) - .WithFlag(1, out finishedPending, FieldMode.Read | FieldMode.WriteOneToClear, name: "ILLEGAL_OPCODE", changeCallback: (_, __) => UpdateInterrupts()) + .WithFlag(0, out finishedPending, FieldMode.Read | FieldMode.WriteOneToClear, name: "FINISHED", changeCallback: (_, __) => UpdateInterrupts()) + .WithFlag(1, out illegalOpcodePending, FieldMode.Read | FieldMode.WriteOneToClear, name: "ILLEGAL_OPCODE", changeCallback: (_, __) => UpdateInterrupts()) ; Registers.EV_ENABLE.Define32(this) - .WithFlag(0, out illegalOpcodeEnabled, name: "FINISHED", changeCallback: (_, __) => UpdateInterrupts()) - .WithFlag(1, out finishedEnabled, name: "ILLEGAL_OPCODE", changeCallback: (_, __) => UpdateInterrupts()) + .WithFlag(0, out finishedEnabled, name: "FINISHED", changeCallback: (_, __) => UpdateInterrupts()) + .WithFlag(1, out illegalOpcodeEnabled, name: "ILLEGAL_OPCODE", changeCallback: (_, __) => UpdateInterrupts()) ; Registers.INSTRUCTION.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return 11 /* Opcode FIN */; }) + .WithValueField(0, 32, valueProviderCallback: _ => this.engineRam.data[this.mpc]) ; } private void UpdateInterrupts() { - if (this.illegalOpcodeStatus && this.illegalOpcodeEnabled.Value) + if (this.illegalOpcodeStatus) { this.illegalOpcodePending.Value = true; } - if (this.finishedStatus && this.finishedEnabled.Value) + if (this.finishedStatus) { this.finishedPending.Value = true; } @@ -149,7 +517,8 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous this.mplen = 0; this.mpresume = 0; this.mpc = 0; - if (this.powerIsOn != null) { + if (this.powerIsOn != null) + { this.powerIsOn.Value = false; } } @@ -175,6 +544,12 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous private IFlagRegisterField finishedPending; private bool finishedStatus; + private Thread engineExecution; + private bool shouldEndExecution; + private SemaphoreSlim startExecution; + + private EngineRam engineRam; + private enum Registers { WINDOW = 0x00, @@ -190,4 +565,485 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous INSTRUCTION = 0x28 } } + + + public struct UInt256 : IComparable + { + private static readonly UInt256 _zero = new UInt256(new byte[0]); + + // parts are big-endian + private readonly UInt64 part1; + private readonly UInt64 part2; + private readonly UInt64 part3; + private readonly UInt64 part4; + private readonly int hashCode; + private readonly bool notDefault; + + public UInt256(byte[] value) + { + // if (value.Length > 32 && !(value.Length == 33 && value[32] == 0)) + // { + // throw new Exception(String.Format("value.Length = {0}", value.Length)); + // // throw new ArgumentOutOfRangeException(); + // } + + if (value.Length < 32) + value = value.Concat(new byte[32 - value.Length]); + + // read LE parts in reverse order to store in BE + var part1Bytes = new byte[8]; + var part2Bytes = new byte[8]; + var part3Bytes = new byte[8]; + var part4Bytes = new byte[8]; + Buffer.BlockCopy(value, 0, part4Bytes, 0, 8); + Buffer.BlockCopy(value, 8, part3Bytes, 0, 8); + Buffer.BlockCopy(value, 16, part2Bytes, 0, 8); + Buffer.BlockCopy(value, 24, part1Bytes, 0, 8); + + // convert parts and store + this.part1 = Bits.ToUInt64(part1Bytes); + this.part2 = Bits.ToUInt64(part2Bytes); + this.part3 = Bits.ToUInt64(part3Bytes); + this.part4 = Bits.ToUInt64(part4Bytes); + + this.hashCode = this.part1.GetHashCode() ^ this.part2.GetHashCode() ^ this.part3.GetHashCode() ^ this.part4.GetHashCode(); + + this.notDefault = true; + } + + private UInt256(UInt64 part1, UInt64 part2, UInt64 part3, UInt64 part4) + { + this.part1 = part1; + this.part2 = part2; + this.part3 = part3; + this.part4 = part4; + + this.hashCode = this.part1.GetHashCode() ^ this.part2.GetHashCode() ^ this.part3.GetHashCode() ^ this.part4.GetHashCode(); + + this.notDefault = true; + } + + public UInt256(int value) + : this(Bits.GetBytes(value)) + { + if (value < 0) + throw new ArgumentOutOfRangeException(); + } + + public UInt256(long value) + : this(Bits.GetBytes(value)) + { + if (value < 0) + throw new ArgumentOutOfRangeException(); + } + + public UInt256(uint value) + : this(Bits.GetBytes(value)) + { } + + public UInt256(ulong value) + : this(Bits.GetBytes(value)) + { } + + public UInt256(BigInteger value) + : this(value.ToByteArray()) + { + if (value < 0) + throw new ArgumentOutOfRangeException(); + } + + public bool IsDefault { get { return !this.notDefault; } } + + public byte[] ToByteArray() + { + var buffer = new byte[32]; + Buffer.BlockCopy(Bits.GetBytes(this.part4), 0, buffer, 0, 8); + Buffer.BlockCopy(Bits.GetBytes(this.part3), 0, buffer, 8, 8); + Buffer.BlockCopy(Bits.GetBytes(this.part2), 0, buffer, 16, 8); + Buffer.BlockCopy(Bits.GetBytes(this.part1), 0, buffer, 24, 8); + + return buffer; + } + + public BigInteger ToBigInteger() + { + // add a trailing zero so that value is always positive + return new BigInteger(ToByteArray().Concat(0)); + } + + public int CompareTo(UInt256 other) + { + if (this == other) + return 0; + else if (this < other) + return -1; + else if (this > other) + return +1; + + throw new Exception(); + } + + public static UInt256 Zero + { + get { return _zero; } + } + + public static explicit operator BigInteger(UInt256 value) + { + return value.ToBigInteger(); + } + + public static implicit operator UInt256(byte value) + { + return new UInt256(value); + } + + public static implicit operator UInt256(int value) + { + return new UInt256(value); + } + + public static implicit operator UInt256(long value) + { + return new UInt256(value); + } + + public static implicit operator UInt256(sbyte value) + { + return new UInt256(value); + } + + public static implicit operator UInt256(short value) + { + return new UInt256(value); + } + + public static implicit operator UInt256(uint value) + { + return new UInt256(value); + } + + public static implicit operator UInt256(ulong value) + { + return new UInt256(value); + } + + public static implicit operator UInt256(ushort value) + { + return new UInt256(value); + } + + public static bool operator ==(UInt256 left, UInt256 right) + { + return left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 == right.part4; + } + + public static bool operator !=(UInt256 left, UInt256 right) + { + return !(left == right); + } + + public static bool operator <(UInt256 left, UInt256 right) + { + if (left.part1 < right.part1) + return true; + else if (left.part1 == right.part1 && left.part2 < right.part2) + return true; + else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 < right.part3) + return true; + else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 < right.part4) + return true; + + return false; + } + + public static bool operator <=(UInt256 left, UInt256 right) + { + if (left.part1 < right.part1) + return true; + else if (left.part1 == right.part1 && left.part2 < right.part2) + return true; + else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 < right.part3) + return true; + else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 < right.part4) + return true; + + return left == right; + } + + public static bool operator >(UInt256 left, UInt256 right) + { + if (left.part1 > right.part1) + return true; + else if (left.part1 == right.part1 && left.part2 > right.part2) + return true; + else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 > right.part3) + return true; + else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 > right.part4) + return true; + + return false; + } + + public static bool operator >=(UInt256 left, UInt256 right) + { + if (left.part1 > right.part1) + return true; + else if (left.part1 == right.part1 && left.part2 > right.part2) + return true; + else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 > right.part3) + return true; + else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 > right.part4) + return true; + + return left == right; + } + + // TODO doesn't compare against other numerics + public override bool Equals(object obj) + { + if (!(obj is UInt256)) + return false; + + var other = (UInt256)obj; + return other.part1 == this.part1 && other.part2 == this.part2 && other.part3 == this.part3 && other.part4 == this.part4; + } + + public override int GetHashCode() + { + return this.hashCode; + } + + public override string ToString() + { + var bytes = this.ToByteArray(); + StringBuilder hex = new StringBuilder(bytes.Length * 2); + foreach (byte b in bytes.Reverse()) + hex.AppendFormat("{0:x2}", b); + return hex.ToString(); + } + + public static UInt256 Parse(string value) + { + return new UInt256(BigInteger.Parse("0" + value).ToByteArray()); + } + + public static UInt256 Parse(string value, IFormatProvider provider) + { + return new UInt256(BigInteger.Parse("0" + value, provider).ToByteArray()); + } + + public static UInt256 Parse(string value, NumberStyles style) + { + return new UInt256(BigInteger.Parse("0" + value, style).ToByteArray()); + } + + public static UInt256 Parse(string value, NumberStyles style, IFormatProvider provider) + { + return new UInt256(BigInteger.Parse("0" + value, style, provider).ToByteArray()); + } + + public static double Log(UInt256 value, double baseValue) + { + return BigInteger.Log(value.ToBigInteger(), baseValue); + } + + public static UInt256 operator %(UInt256 dividend, UInt256 divisor) + { + return new UInt256(dividend.ToBigInteger() % divisor.ToBigInteger()); + } + + public static UInt256 Pow(UInt256 value, int exponent) + { + return new UInt256(BigInteger.Pow(value.ToBigInteger(), exponent)); + } + + public static UInt256 operator *(UInt256 left, UInt256 right) + { + return new UInt256((left.ToBigInteger() * right.ToBigInteger()) % ((BigInteger.Pow(2, 255) - 19))); + } + + public static UInt256 operator >>(UInt256 value, int shift) + { + return new UInt256(value.ToBigInteger() >> shift); + } + + public static UInt256 operator |(UInt256 left, UInt256 right) + { + return new UInt256(left.ToBigInteger() | right.ToBigInteger()); + } + + public static UInt256 operator ^(UInt256 left, UInt256 right) + { + return new UInt256(left.ToBigInteger() ^ right.ToBigInteger()); + } + + public static UInt256 operator <<(UInt256 value, int shift) + { + return new UInt256(value.ToBigInteger() << shift); + } + + public static UInt256 operator /(UInt256 dividend, UInt256 divisor) + { + return new UInt256(dividend.ToBigInteger() / divisor.ToBigInteger()); + } + + public static UInt256 operator &(UInt256 dividend, UInt256 divisor) + { + return new UInt256(dividend.ToBigInteger() & divisor.ToBigInteger()); + } + + public static UInt256 operator +(UInt256 dividend, UInt256 divisor) + { + return new UInt256(dividend.ToBigInteger() + divisor.ToBigInteger()); + } + + public static UInt256 operator -(UInt256 dividend, UInt256 divisor) + { + if (dividend < divisor) + { + return new UInt256((BigInteger.Pow(2, 255) - 1) - (divisor.ToBigInteger() - dividend.ToBigInteger())); + } + return new UInt256(dividend.ToBigInteger() - divisor.ToBigInteger()); + } + + public static UInt256 operator ~(UInt256 value) + { + return new UInt256(~value.part1, ~value.part2, ~value.part3, ~value.part4); + } + + public static UInt256 DivRem(UInt256 dividend, UInt256 divisor, out UInt256 remainder) + { + BigInteger remainderBigInt; + var result = new UInt256(BigInteger.DivRem(dividend.ToBigInteger(), divisor.ToBigInteger(), out remainderBigInt)); + remainder = new UInt256(remainderBigInt); + return result; + } + + public static explicit operator double(UInt256 value) + { + return (double)value.ToBigInteger(); + } + } + + public class Bits + { + private static readonly bool isLE = BitConverter.IsLittleEndian; + + public static byte[] GetBytes(Int16 value) + { + return Order(BitConverter.GetBytes(value)); + } + + public static byte[] GetBytes(UInt16 value) + { + return Order(BitConverter.GetBytes(value)); + } + + public static byte[] GetBytesBE(UInt16 value) + { + return OrderBE(BitConverter.GetBytes(value)); + } + + public static byte[] GetBytes(Int32 value) + { + return Order(BitConverter.GetBytes(value)); + } + + public static byte[] GetBytes(UInt32 value) + { + return Order(BitConverter.GetBytes(value)); + } + + public static byte[] GetBytesBE(UInt32 value) + { + return OrderBE(BitConverter.GetBytes(value)); + } + + public static byte[] GetBytes(Int64 value) + { + return Order(BitConverter.GetBytes(value)); + } + + public static byte[] GetBytes(UInt64 value) + { + return Order(BitConverter.GetBytes(value)); + } + + public static byte[] GetBytesBE(UInt64 value) + { + return OrderBE(BitConverter.GetBytes(value)); + } + + public static byte[] GetBytes(UInt256 value) + { + return value.ToByteArray(); + } + + public static string ToString(byte[] value) + { + return BitConverter.ToString(Order(value)); + } + + public static UInt16 ToUInt16(byte[] value) + { + return BitConverter.ToUInt16(Order(value), startIndex: 0); + } + + public static UInt16 ToUInt16BE(byte[] value) + { + return BitConverter.ToUInt16(OrderBE(value), startIndex: 0); + } + + public static UInt32 ToUInt32(byte[] value) + { + return BitConverter.ToUInt32(Order(value), startIndex: 0); + } + + public static UInt64 ToUInt64(byte[] value) + { + return BitConverter.ToUInt64(Order(value), startIndex: 0); + } + + public static UInt64 ToUInt64(byte[] value, int startIndex) + { + return BitConverter.ToUInt64(Order(value), startIndex); + } + + public static UInt256 ToUInt256(byte[] value) + { + return new UInt256(value); + } + + public static byte[] Order(byte[] value) + { + return isLE ? value : value.Reverse().ToArray(); + } + + public static byte[] OrderBE(byte[] value) + { + return isLE ? value.Reverse().ToArray() : value; + } + } + + public static class ExtensionMethods + { + + public static byte[] Concat(this byte[] first, byte[] second) + { + var buffer = new byte[first.Length + second.Length]; + Buffer.BlockCopy(first, 0, buffer, 0, first.Length); + Buffer.BlockCopy(second, 0, buffer, first.Length, second.Length); + return buffer; + } + + public static byte[] Concat(this byte[] first, byte second) + { + var buffer = new byte[first.Length + 1]; + Buffer.BlockCopy(first, 0, buffer, 0, first.Length); + buffer[buffer.Length - 1] = second; + return buffer; + } + + } } From 4790686dd91e12f95eee3718871e7d3e1d6e49e9 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 11:28:53 +0800 Subject: [PATCH 04/12] engine: pass all checks with `engine check` This fixes bugs in SUB, XOR, MUL, NOT, and gets register windows working. Signed-off-by: Sean Cross --- emulation/peripherals/engine.cs | 603 +++++--------------------------- 1 file changed, 86 insertions(+), 517 deletions(-) diff --git a/emulation/peripherals/engine.cs b/emulation/peripherals/engine.cs index 00825d1b2..a0cd3484a 100644 --- a/emulation/peripherals/engine.cs +++ b/emulation/peripherals/engine.cs @@ -26,34 +26,33 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous this.engine = engine; this.size = size; this.data = new UInt32[size / 4]; - this.FIELD_MAX = new UInt256(BigInteger.Pow(2, 255) - 19); - this.c0 = new UInt256(0); - this.c1 = new UInt256(1); + this.FIELD_MAX = BigInteger.Pow(2, 255) - 19; + this.UINT_MAX = BigInteger.Pow(2, 256) - 1; + this.c0 = new BigInteger(0); + this.c1 = new BigInteger(1); - // (A-2)/4 - this.c2 = new UInt256(121665); + this.c2 = new BigInteger(121665); // (A-2)/4 this.c3 = this.FIELD_MAX; - // (A+2)/4 - this.c4 = new UInt256(121666); - this.c5 = new UInt256(5); - this.c6 = new UInt256(10); - this.c7 = new UInt256(20); - this.c8 = new UInt256(50); - this.c9 = new UInt256(100); + this.c4 = new BigInteger(121666); // (A+2)/4 + this.c5 = new BigInteger(5); + this.c6 = new BigInteger(10); + this.c7 = new BigInteger(20); + this.c8 = new BigInteger(50); + this.c9 = new BigInteger(100); } - public UInt256 FIELD_MAX; - // private UInt256 UINT_MAX; - private UInt256 c0; - private UInt256 c1; - private UInt256 c2; - private UInt256 c3; - private UInt256 c4; - private UInt256 c5; - private UInt256 c6; - private UInt256 c7; - private UInt256 c8; - private UInt256 c9; + public BigInteger FIELD_MAX; + private BigInteger UINT_MAX; + private BigInteger c0; + private BigInteger c1; + private BigInteger c2; + private BigInteger c3; + private BigInteger c4; + private BigInteger c5; + private BigInteger c6; + private BigInteger c7; + private BigInteger c8; + private BigInteger c9; private Machine machine; private Engine engine; private long size; @@ -70,7 +69,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous return this.data[offset / 4]; } - public UInt256 ReadRegister(ulong rf, ulong register, bool constant) + public BigInteger ReadRegister(ulong rf, ulong register, bool constant) { // this.Log(LogLevel.Error, "Reading register {0} (const? {1}) from rf {2}", register, constant, rf); if (constant) @@ -87,19 +86,19 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous case 7: return this.c7; case 8: return this.c8; case 9: return this.c9; - default: return new UInt256(0); + default: return new BigInteger(0); } } - var src_bytes = new byte[32]; + var src_bytes = new byte[33]; // Keep leading byte 0 to force unsigned if ((rf >= 16) || (register >= 32)) { throw new Exception(String.Format("Register #{0} or RegisterFile {1} is out of range", register, rf)); } - for (ulong i = 0; i < (ulong)src_bytes.Length; i += 4) + for (ulong i = 0; i < 32; i += 4) { - var offset = 0x10000 + (rf * 512) + (register * 32) + i; + var offset = 0x10000 + (rf * 1024) + (register * 32) + i; var bytes = BitConverter.GetBytes(this.data[offset / 4]); if (bytes.Length != 4) { @@ -115,22 +114,44 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous } } // this.Log(LogLevel.Error, "Returning read value from {0}-byte array", src_bytes.Length); - return new UInt256(src_bytes); + return new BigInteger(src_bytes); } - public void WriteRegister(long rf, long register, UInt256 value) + public void WriteRegister(long rf, long register, BigInteger value) { if ((rf >= 16) || (register >= 32)) { throw new Exception(String.Format("Register #{0} or RegisterFile {1} is out of range", register, rf)); } - var offset = 0x10000 + (rf * 512) + (register * 32); - var bytes = value.ToByteArray(); - for (uint i = 0; i < (uint)bytes.Length; i += 4) - { - this.data[(offset + i) / 4] = (((uint)bytes[i + 0]) << 0) | (((uint)bytes[i + 1]) << 8) | (((uint)bytes[i + 2]) << 16) | ((uint)(bytes[i + 3]) << 24); + var bytes = (value & this.UINT_MAX).ToByteArray(); + if (bytes.Length < 32) + { + bytes = bytes.Concat(new byte[32 - bytes.Length]); } + + var offset = 0x10000 + (rf * 1024) + (register * 32); + for (uint i = 0; i < 32; i += 4) + { + this.data[(offset + i) / 4] = (((uint)bytes[i + 0]) << 0) + | (((uint)bytes[i + 1]) << 8) + | (((uint)bytes[i + 2]) << 16) + | ((uint)(bytes[i + 3]) << 24); + } + } + + public String FormatValue(BigInteger value) + { + var trimmed_value = value & this.UINT_MAX; + var bytes = trimmed_value.ToByteArray(); + if (bytes.Length < 32) + { + bytes = bytes.Concat(new byte[32 - bytes.Length]); + } + StringBuilder hex = new StringBuilder(bytes.Length * 2); + foreach (byte b in bytes.Reverse()) + hex.AppendFormat("{0:x2}", b); + return hex.ToString(); } public void Reset() @@ -176,7 +197,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous case 6: return "ten"; case 7: return "twenty"; case 8: return "fifty"; - case 9: return "one hundred"; + case 9: return "one_hundred"; default: return "undef"; } } @@ -251,7 +272,6 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous { return "undef"; } - // return "unhandled"; } public UInt32 Op; @@ -290,10 +310,12 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous private void EngineThread() { + bool shouldLog = false; try { // this.Log(LogLevel.Error, "ENGINE: Beginning execution. Current MPC: 0x{0:X}", this.mpc); this.mpc = this.mpstart; + while (true) { if (this.mpc >= this.mplen) @@ -315,25 +337,24 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous break; case 2: // MSK - var bit = this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) & 1; - if (bit != 0) + if ((this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) & 1) != 0) { this.engineRam.WriteRegister(this.window, op.Wd, this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)); } else { - this.engineRam.WriteRegister(this.window, op.Wd, new UInt256(0)); + this.engineRam.WriteRegister(this.window, op.Wd, new BigInteger(0)); } break; case 3: // XOR this.engineRam.WriteRegister(this.window, op.Wd, - this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) ^ this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)); + (BigInteger.Pow(2, 256) | this.engineRam.ReadRegister(this.window, op.Ra, op.Ca)) ^ this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)); break; case 4: // NOT this.engineRam.WriteRegister(this.window, op.Wd, - ~this.engineRam.ReadRegister(this.window, op.Ra, op.Ca)); + ~(this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) | BigInteger.Pow(2, 256))); break; case 5: // ADD @@ -342,15 +363,24 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous break; case 6: // SUB - this.engineRam.WriteRegister(this.window, op.Wd, - this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) - this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)); + { + var left = this.engineRam.ReadRegister(this.window, op.Ra, op.Ca); + var right = this.engineRam.ReadRegister(this.window, op.Rb, op.Cb); + var result = left - right; + // Wrap integer + if (result < 0) + { + result = BigInteger.Pow(2, 256) - result; + } + this.engineRam.WriteRegister(this.window, op.Wd, result); + } break; case 7: // MUL - // this.Log(LogLevel.Error, "Ra: {0} Rb: {1} Wd: {2}", this.engineRam.ReadRegister(this.window, op.Ra, op.Ca), this.engineRam.ReadRegister(this.window, op.Rb, op.Cb), - // (this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) * this.engineRam.ReadRegister(this.window, op.Rb, op.Cb))); this.engineRam.WriteRegister(this.window, op.Wd, - (this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) * this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)) + (this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) + * this.engineRam.ReadRegister(this.window, op.Rb, op.Cb)) + % this.engineRam.FIELD_MAX ); break; @@ -361,7 +391,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous } else { - this.engineRam.WriteRegister(this.window, op.Wd, new UInt256(0)); + this.engineRam.WriteRegister(this.window, op.Wd, new BigInteger(0)); } break; @@ -381,13 +411,13 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous break; case 12: // XBT - if ((this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) & (new UInt256(1) << 254)) != 0) + if ((this.engineRam.ReadRegister(this.window, op.Ra, op.Ca) & (new BigInteger(1) << 254)) != 0) { - this.engineRam.WriteRegister(this.window, op.Wd, new UInt256(1)); + this.engineRam.WriteRegister(this.window, op.Wd, new BigInteger(1)); } else { - this.engineRam.WriteRegister(this.window, op.Wd, new UInt256(0)); + this.engineRam.WriteRegister(this.window, op.Wd, new BigInteger(0)); } break; @@ -400,7 +430,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous { break; } - // this.Log(LogLevel.Error, " (Result) {0}", this.engineRam.ReadRegister(this.window, op.Wd, false).ToString()); + // this.Log(LogLevel.Error, " (Result) {0}", this.engineRam.FormatValue(this.engineRam.ReadRegister(this.window, op.Wd, false))); } } catch (Exception e) @@ -418,15 +448,15 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous private void DefineRegisters() { Registers.WINDOW.Define(this) - .WithValueField(0, 4, name: "WINDOW", valueProviderCallback: (_) => { return this.window; }, changeCallback: (_, value) => { this.window = (byte)(value & 0xf); }) + .WithValueField(0, 4, name: "WINDOW", valueProviderCallback: (_) => this.window, changeCallback: (_, value) => this.window = (byte)(value & 0xf)) ; Registers.MPSTART.Define(this) - .WithValueField(0, 11, name: "MPSTART", valueProviderCallback: (_) => { return this.mpstart; }, changeCallback: (_, value) => { this.mpstart = (UInt16)(value & 0x7ff); }) + .WithValueField(0, 11, name: "MPSTART", valueProviderCallback: (_) => this.mpstart, changeCallback: (_, value) => this.mpstart = (UInt16)(value & 0x7ff)) ; Registers.MPLEN.Define(this) - .WithValueField(0, 11, name: "MPLEN", valueProviderCallback: _ => this.mplen, changeCallback: (_, value) => { this.mplen = (UInt16)(value & 0x7ff); }) + .WithValueField(0, 11, name: "MPLEN", valueProviderCallback: _ => this.mplen, changeCallback: (_, value) => this.mplen = (UInt16)(value & 0x7ff)) ; Registers.CONTROL.Define(this) @@ -566,466 +596,6 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous } } - - public struct UInt256 : IComparable - { - private static readonly UInt256 _zero = new UInt256(new byte[0]); - - // parts are big-endian - private readonly UInt64 part1; - private readonly UInt64 part2; - private readonly UInt64 part3; - private readonly UInt64 part4; - private readonly int hashCode; - private readonly bool notDefault; - - public UInt256(byte[] value) - { - // if (value.Length > 32 && !(value.Length == 33 && value[32] == 0)) - // { - // throw new Exception(String.Format("value.Length = {0}", value.Length)); - // // throw new ArgumentOutOfRangeException(); - // } - - if (value.Length < 32) - value = value.Concat(new byte[32 - value.Length]); - - // read LE parts in reverse order to store in BE - var part1Bytes = new byte[8]; - var part2Bytes = new byte[8]; - var part3Bytes = new byte[8]; - var part4Bytes = new byte[8]; - Buffer.BlockCopy(value, 0, part4Bytes, 0, 8); - Buffer.BlockCopy(value, 8, part3Bytes, 0, 8); - Buffer.BlockCopy(value, 16, part2Bytes, 0, 8); - Buffer.BlockCopy(value, 24, part1Bytes, 0, 8); - - // convert parts and store - this.part1 = Bits.ToUInt64(part1Bytes); - this.part2 = Bits.ToUInt64(part2Bytes); - this.part3 = Bits.ToUInt64(part3Bytes); - this.part4 = Bits.ToUInt64(part4Bytes); - - this.hashCode = this.part1.GetHashCode() ^ this.part2.GetHashCode() ^ this.part3.GetHashCode() ^ this.part4.GetHashCode(); - - this.notDefault = true; - } - - private UInt256(UInt64 part1, UInt64 part2, UInt64 part3, UInt64 part4) - { - this.part1 = part1; - this.part2 = part2; - this.part3 = part3; - this.part4 = part4; - - this.hashCode = this.part1.GetHashCode() ^ this.part2.GetHashCode() ^ this.part3.GetHashCode() ^ this.part4.GetHashCode(); - - this.notDefault = true; - } - - public UInt256(int value) - : this(Bits.GetBytes(value)) - { - if (value < 0) - throw new ArgumentOutOfRangeException(); - } - - public UInt256(long value) - : this(Bits.GetBytes(value)) - { - if (value < 0) - throw new ArgumentOutOfRangeException(); - } - - public UInt256(uint value) - : this(Bits.GetBytes(value)) - { } - - public UInt256(ulong value) - : this(Bits.GetBytes(value)) - { } - - public UInt256(BigInteger value) - : this(value.ToByteArray()) - { - if (value < 0) - throw new ArgumentOutOfRangeException(); - } - - public bool IsDefault { get { return !this.notDefault; } } - - public byte[] ToByteArray() - { - var buffer = new byte[32]; - Buffer.BlockCopy(Bits.GetBytes(this.part4), 0, buffer, 0, 8); - Buffer.BlockCopy(Bits.GetBytes(this.part3), 0, buffer, 8, 8); - Buffer.BlockCopy(Bits.GetBytes(this.part2), 0, buffer, 16, 8); - Buffer.BlockCopy(Bits.GetBytes(this.part1), 0, buffer, 24, 8); - - return buffer; - } - - public BigInteger ToBigInteger() - { - // add a trailing zero so that value is always positive - return new BigInteger(ToByteArray().Concat(0)); - } - - public int CompareTo(UInt256 other) - { - if (this == other) - return 0; - else if (this < other) - return -1; - else if (this > other) - return +1; - - throw new Exception(); - } - - public static UInt256 Zero - { - get { return _zero; } - } - - public static explicit operator BigInteger(UInt256 value) - { - return value.ToBigInteger(); - } - - public static implicit operator UInt256(byte value) - { - return new UInt256(value); - } - - public static implicit operator UInt256(int value) - { - return new UInt256(value); - } - - public static implicit operator UInt256(long value) - { - return new UInt256(value); - } - - public static implicit operator UInt256(sbyte value) - { - return new UInt256(value); - } - - public static implicit operator UInt256(short value) - { - return new UInt256(value); - } - - public static implicit operator UInt256(uint value) - { - return new UInt256(value); - } - - public static implicit operator UInt256(ulong value) - { - return new UInt256(value); - } - - public static implicit operator UInt256(ushort value) - { - return new UInt256(value); - } - - public static bool operator ==(UInt256 left, UInt256 right) - { - return left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 == right.part4; - } - - public static bool operator !=(UInt256 left, UInt256 right) - { - return !(left == right); - } - - public static bool operator <(UInt256 left, UInt256 right) - { - if (left.part1 < right.part1) - return true; - else if (left.part1 == right.part1 && left.part2 < right.part2) - return true; - else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 < right.part3) - return true; - else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 < right.part4) - return true; - - return false; - } - - public static bool operator <=(UInt256 left, UInt256 right) - { - if (left.part1 < right.part1) - return true; - else if (left.part1 == right.part1 && left.part2 < right.part2) - return true; - else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 < right.part3) - return true; - else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 < right.part4) - return true; - - return left == right; - } - - public static bool operator >(UInt256 left, UInt256 right) - { - if (left.part1 > right.part1) - return true; - else if (left.part1 == right.part1 && left.part2 > right.part2) - return true; - else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 > right.part3) - return true; - else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 > right.part4) - return true; - - return false; - } - - public static bool operator >=(UInt256 left, UInt256 right) - { - if (left.part1 > right.part1) - return true; - else if (left.part1 == right.part1 && left.part2 > right.part2) - return true; - else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 > right.part3) - return true; - else if (left.part1 == right.part1 && left.part2 == right.part2 && left.part3 == right.part3 && left.part4 > right.part4) - return true; - - return left == right; - } - - // TODO doesn't compare against other numerics - public override bool Equals(object obj) - { - if (!(obj is UInt256)) - return false; - - var other = (UInt256)obj; - return other.part1 == this.part1 && other.part2 == this.part2 && other.part3 == this.part3 && other.part4 == this.part4; - } - - public override int GetHashCode() - { - return this.hashCode; - } - - public override string ToString() - { - var bytes = this.ToByteArray(); - StringBuilder hex = new StringBuilder(bytes.Length * 2); - foreach (byte b in bytes.Reverse()) - hex.AppendFormat("{0:x2}", b); - return hex.ToString(); - } - - public static UInt256 Parse(string value) - { - return new UInt256(BigInteger.Parse("0" + value).ToByteArray()); - } - - public static UInt256 Parse(string value, IFormatProvider provider) - { - return new UInt256(BigInteger.Parse("0" + value, provider).ToByteArray()); - } - - public static UInt256 Parse(string value, NumberStyles style) - { - return new UInt256(BigInteger.Parse("0" + value, style).ToByteArray()); - } - - public static UInt256 Parse(string value, NumberStyles style, IFormatProvider provider) - { - return new UInt256(BigInteger.Parse("0" + value, style, provider).ToByteArray()); - } - - public static double Log(UInt256 value, double baseValue) - { - return BigInteger.Log(value.ToBigInteger(), baseValue); - } - - public static UInt256 operator %(UInt256 dividend, UInt256 divisor) - { - return new UInt256(dividend.ToBigInteger() % divisor.ToBigInteger()); - } - - public static UInt256 Pow(UInt256 value, int exponent) - { - return new UInt256(BigInteger.Pow(value.ToBigInteger(), exponent)); - } - - public static UInt256 operator *(UInt256 left, UInt256 right) - { - return new UInt256((left.ToBigInteger() * right.ToBigInteger()) % ((BigInteger.Pow(2, 255) - 19))); - } - - public static UInt256 operator >>(UInt256 value, int shift) - { - return new UInt256(value.ToBigInteger() >> shift); - } - - public static UInt256 operator |(UInt256 left, UInt256 right) - { - return new UInt256(left.ToBigInteger() | right.ToBigInteger()); - } - - public static UInt256 operator ^(UInt256 left, UInt256 right) - { - return new UInt256(left.ToBigInteger() ^ right.ToBigInteger()); - } - - public static UInt256 operator <<(UInt256 value, int shift) - { - return new UInt256(value.ToBigInteger() << shift); - } - - public static UInt256 operator /(UInt256 dividend, UInt256 divisor) - { - return new UInt256(dividend.ToBigInteger() / divisor.ToBigInteger()); - } - - public static UInt256 operator &(UInt256 dividend, UInt256 divisor) - { - return new UInt256(dividend.ToBigInteger() & divisor.ToBigInteger()); - } - - public static UInt256 operator +(UInt256 dividend, UInt256 divisor) - { - return new UInt256(dividend.ToBigInteger() + divisor.ToBigInteger()); - } - - public static UInt256 operator -(UInt256 dividend, UInt256 divisor) - { - if (dividend < divisor) - { - return new UInt256((BigInteger.Pow(2, 255) - 1) - (divisor.ToBigInteger() - dividend.ToBigInteger())); - } - return new UInt256(dividend.ToBigInteger() - divisor.ToBigInteger()); - } - - public static UInt256 operator ~(UInt256 value) - { - return new UInt256(~value.part1, ~value.part2, ~value.part3, ~value.part4); - } - - public static UInt256 DivRem(UInt256 dividend, UInt256 divisor, out UInt256 remainder) - { - BigInteger remainderBigInt; - var result = new UInt256(BigInteger.DivRem(dividend.ToBigInteger(), divisor.ToBigInteger(), out remainderBigInt)); - remainder = new UInt256(remainderBigInt); - return result; - } - - public static explicit operator double(UInt256 value) - { - return (double)value.ToBigInteger(); - } - } - - public class Bits - { - private static readonly bool isLE = BitConverter.IsLittleEndian; - - public static byte[] GetBytes(Int16 value) - { - return Order(BitConverter.GetBytes(value)); - } - - public static byte[] GetBytes(UInt16 value) - { - return Order(BitConverter.GetBytes(value)); - } - - public static byte[] GetBytesBE(UInt16 value) - { - return OrderBE(BitConverter.GetBytes(value)); - } - - public static byte[] GetBytes(Int32 value) - { - return Order(BitConverter.GetBytes(value)); - } - - public static byte[] GetBytes(UInt32 value) - { - return Order(BitConverter.GetBytes(value)); - } - - public static byte[] GetBytesBE(UInt32 value) - { - return OrderBE(BitConverter.GetBytes(value)); - } - - public static byte[] GetBytes(Int64 value) - { - return Order(BitConverter.GetBytes(value)); - } - - public static byte[] GetBytes(UInt64 value) - { - return Order(BitConverter.GetBytes(value)); - } - - public static byte[] GetBytesBE(UInt64 value) - { - return OrderBE(BitConverter.GetBytes(value)); - } - - public static byte[] GetBytes(UInt256 value) - { - return value.ToByteArray(); - } - - public static string ToString(byte[] value) - { - return BitConverter.ToString(Order(value)); - } - - public static UInt16 ToUInt16(byte[] value) - { - return BitConverter.ToUInt16(Order(value), startIndex: 0); - } - - public static UInt16 ToUInt16BE(byte[] value) - { - return BitConverter.ToUInt16(OrderBE(value), startIndex: 0); - } - - public static UInt32 ToUInt32(byte[] value) - { - return BitConverter.ToUInt32(Order(value), startIndex: 0); - } - - public static UInt64 ToUInt64(byte[] value) - { - return BitConverter.ToUInt64(Order(value), startIndex: 0); - } - - public static UInt64 ToUInt64(byte[] value, int startIndex) - { - return BitConverter.ToUInt64(Order(value), startIndex); - } - - public static UInt256 ToUInt256(byte[] value) - { - return new UInt256(value); - } - - public static byte[] Order(byte[] value) - { - return isLE ? value : value.Reverse().ToArray(); - } - - public static byte[] OrderBE(byte[] value) - { - return isLE ? value.Reverse().ToArray() : value; - } - } - public static class ExtensionMethods { @@ -1044,6 +614,5 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous buffer[buffer.Length - 1] = second; return buffer; } - } } From 5ae1e437ab96536c214b627d22e1f2375c9cf384 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 15:55:13 +0800 Subject: [PATCH 05/12] sha512: fix length and 512/256 calculation The length is now correctly calculated, and the engine properly completes. Additionally, a bulk 512/256 implementation has been written that works well enough, but will fall over if asked to compute a large amount of data. Signed-off-by: Sean Cross --- emulation/peripherals/sha512.cs | 575 +++++++++++++++++++++++++++----- 1 file changed, 494 insertions(+), 81 deletions(-) diff --git a/emulation/peripherals/sha512.cs b/emulation/peripherals/sha512.cs index c06d48ea2..5cc84d8f5 100644 --- a/emulation/peripherals/sha512.cs +++ b/emulation/peripherals/sha512.cs @@ -7,15 +7,16 @@ // using System; using System.Collections.Generic; -using System.Security.Cryptography; -using Antmicro.Renode.Core; -using Antmicro.Renode.Core.Structure.Registers; -using Antmicro.Renode.Logging; -using Antmicro.Renode.Peripherals.Bus; -using Antmicro.Renode.Peripherals.CPU; +using System.Linq; namespace Antmicro.Renode.Peripherals.Miscellaneous { + using System; + using System.Security.Cryptography; + using Antmicro.Renode.Core; + using Antmicro.Renode.Core.Structure.Registers; + using Antmicro.Renode.Logging; + using Antmicro.Renode.Peripherals.Bus; public class Sha512Writer : IDoubleWordPeripheral, IBytePeripheral, IProvidesRegisterCollection, IKnownSize { public Sha512Writer(Machine machine, Sha512 sha512) @@ -28,16 +29,13 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous private Sha512 sha512; public long Size { get { return 4096; } } - public void WriteDoubleWord(long address, uint value) + public void WriteDoubleWord(long offset, uint value) { - // machine.SystemBus.AddWatchpointHook(this.bufferAddress, SysbusAccessWidth.DoubleWord, Access.Write, (cpu, encounteredAddress, width, encounteredValue) => - // { - if (address != 0) + if (offset != 0) { - this.Log(LogLevel.Error, "Adding word 0x{0:X} (at address 0x{1:X}) to hash", value, address); + this.Log(LogLevel.Error, "Adding word 0x{0:X} (at address 0x{1:X}) to hash", value, offset); } - this.sha512.addToHash(value, (uint)address); - // RegistersCollection.Write(address, value); + this.sha512.add32ToHash(value, (uint)offset); } public uint ReadDoubleWord(long offset) @@ -54,6 +52,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous public void WriteByte(long offset, byte value) { this.Log(LogLevel.Error, "Writing byte value 0x{0:X} to 0x{0:X}", value, offset); + this.sha512.add8ToHash(value, (uint)offset); } public DoubleWordRegisterCollection RegistersCollection { get; private set; } @@ -65,22 +64,20 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous } public class Sha512 : IDoubleWordPeripheral, IProvidesRegisterCollection, IKnownSize { - public Sha512(Machine machine) + public Sha512(Machine machine, uint memAddr, uint memSize) { this.machine = machine; var sha512Writer = new Sha512Writer(machine, this); - // machine.SystemBus.UnmapMemory(this.bufferAddress, 4096); - machine.SystemBus.Register(sha512Writer, new BusRangeRegistration(this.bufferAddress, 4096)); + machine.SystemBus.Register(sha512Writer, new BusRangeRegistration(memAddr, memSize)); RegistersCollection = new DoubleWordRegisterCollection(this); this.IRQ = new GPIO(); this.sha512 = new SHA512Managed(); - this.sha256 = new SHA256Managed(); Reset(); DefineRegisters(); } - public void addToHash(uint encounteredValue, uint address) + public void add32ToHash(UInt32 encounteredValue, uint address) { var inputBuffer = new byte[4]; if (!this.inputIsSwapped.Value) @@ -96,16 +93,34 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous inputBuffer[1] = (byte)(encounteredValue >> 8); inputBuffer[2] = (byte)(encounteredValue >> 16); inputBuffer[3] = (byte)(encounteredValue >> 24); - if (this.usingSha256.Value) + } + if (this.usingSha256.Value) + { + foreach (byte b in inputBuffer) { - this.sha256.TransformBlock(inputBuffer, 0, inputBuffer.Length, null, 0); - } - else - { - this.sha512.TransformBlock(inputBuffer, 0, inputBuffer.Length, null, 0); + this.Sha512_256Backing.Add(b); } } - this.digestedLength += 4; + else + { + this.sha512.TransformBlock(inputBuffer, 0, inputBuffer.Length, null, 0); + } + this.digestedLength += (ulong)inputBuffer.Length * 8; + } + + public void add8ToHash(byte encounteredValue, uint address) + { + var inputBuffer = new byte[1]; + inputBuffer[0] = encounteredValue; + if (this.usingSha256.Value) + { + this.Sha512_256Backing.Add(inputBuffer[0]); + } + else + { + this.sha512.TransformBlock(inputBuffer, 0, inputBuffer.Length, null, 0); + } + this.digestedLength += (ulong)inputBuffer.Length * 8; } private uint ResultAtOffset(int offset) @@ -114,36 +129,28 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous if (usingSha256.Value && offset >= 32) { offset -= 32; - if (outputIsSwapped.Value) - { - return ((uint)this.sha256.Hash[offset + 0] << 0) - | ((uint)this.sha256.Hash[offset + 1] << 8) - | ((uint)this.sha256.Hash[offset + 2] << 16) - | ((uint)this.sha256.Hash[offset + 3] << 24); - } - else - { - return ((uint)this.sha256.Hash[offset + 3] << 0) - | ((uint)this.sha256.Hash[offset + 2] << 8) - | ((uint)this.sha256.Hash[offset + 1] << 16) - | ((uint)this.sha256.Hash[offset + 0] << 24); - } } // Using sha 512 + var arr = this.sha512.Hash; + if (this.usingSha256.Value && (this.Sha512_256Result != null)) + { + arr = this.Sha512_256Result.Hash; + } + if (outputIsSwapped.Value) { - return ((uint)this.sha512.Hash[offset + 0] << 0) - | ((uint)this.sha512.Hash[offset + 1] << 8) - | ((uint)this.sha512.Hash[offset + 2] << 16) - | ((uint)this.sha512.Hash[offset + 3] << 24); + return ((uint)arr[offset + 0] << 0) + | ((uint)arr[offset + 1] << 8) + | ((uint)arr[offset + 2] << 16) + | ((uint)arr[offset + 3] << 24); } else { - return ((uint)this.sha512.Hash[offset + 3] << 0) - | ((uint)this.sha512.Hash[offset + 2] << 8) - | ((uint)this.sha512.Hash[offset + 1] << 16) - | ((uint)this.sha512.Hash[offset + 0] << 24); + return ((uint)arr[offset + 3] << 0) + | ((uint)arr[offset + 2] << 8) + | ((uint)arr[offset + 1] << 16) + | ((uint)arr[offset + 0] << 24); } } @@ -157,37 +164,41 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous .WithFlag(0, out shaIsEnabled, FieldMode.Read | FieldMode.Write, name: "SHA_EN") .WithFlag(1, out inputIsSwapped, FieldMode.Read | FieldMode.Write, name: "ENDIAN_SWAP") .WithFlag(2, out outputIsSwapped, FieldMode.Read | FieldMode.Write, name: "DIGEST_SWAP") - .WithFlag(3, out usingSha256, FieldMode.Read | FieldMode.Write, name: "DIGEST_SWAP") - .WithFlag(4, FieldMode.Write, name: "RESET", writeCallback: (_, doit) => { Reset(); }) + .WithFlag(3, out usingSha256, FieldMode.Read | FieldMode.Write, name: "SELECT_256") + .WithFlag(4, FieldMode.Write, name: "RESET", writeCallback: (_, doit) => { if (doit) Reset(); }) ; Registers.COMMAND.Define(this) - .WithFlag(0, name: "HASH_START", changeCallback: (_, value) => + .WithFlag(0, name: "HASH_START", writeCallback: (_, value) => { if (value) { - if (usingSha256.Value) + if (this.usingSha256.Value) { - sha256.Initialize(); + // this.sha512 = SHA512Managed.Create("SHA512/256"); + this.Sha512_256Backing = new List(); + this.Sha512_256Result = null; } else { - sha512.Initialize(); + this.sha512 = SHA512Managed.Create("SHA512"); + this.sha512.Initialize(); } this.digestedLength = 0; } }) - .WithFlag(1, name: "HASH_PROCESS", changeCallback: (_, value) => + .WithFlag(1, name: "HASH_PROCESS", writeCallback: (_, value) => { if (value) { - var dummy = new byte[0]; - if (usingSha256.Value) + if (this.usingSha256.Value) { - this.sha256.TransformFinalBlock(dummy, 0, 0); + this.Sha512_256Result = new SHA512_256Managed(this.Sha512_256Backing.ToArray()); + this.Sha512_256Backing = null; } else { + var dummy = new byte[0]; this.sha512.TransformFinalBlock(dummy, 0, 0); } @@ -199,58 +210,58 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous ; Registers.DIGEST00.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(0); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(0)) ; Registers.DIGEST01.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(4); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(4)) ; Registers.DIGEST10.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(8); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(8)) ; Registers.DIGEST11.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(12); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(12)) ; Registers.DIGEST20.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(16); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(16)) ; Registers.DIGEST21.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(20); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(20)) ; Registers.DIGEST30.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(24); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(24)) ; Registers.DIGEST31.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(28); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(28)) ; Registers.DIGEST40.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(32); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(32)) ; Registers.DIGEST41.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(36); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(36)) ; Registers.DIGEST50.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(40); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(40)) ; Registers.DIGEST51.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(44); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(44)) ; Registers.DIGEST60.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(48); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(48)) ; Registers.DIGEST61.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(52); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(52)) ; Registers.DIGEST70.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(56); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(56)) ; Registers.DIGEST71.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(60); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(60)) ; Registers.MSG_LENGTH1.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return (uint)(this.digestedLength >> 32); }) + .WithValueField(0, 32, valueProviderCallback: _ => (uint)(this.digestedLength >> 32)) ; Registers.MSG_LENGTH0.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return (uint)this.digestedLength; }) + .WithValueField(0, 32, valueProviderCallback: _ => (uint)this.digestedLength) ; Registers.EV_STATUS.Define32(this) @@ -272,7 +283,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous ; Registers.FIFO.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return 0; }) + .WithValueField(0, 32, valueProviderCallback: _ => 0) ; } @@ -310,18 +321,18 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous public void Reset() { - this.sha256.Initialize(); this.sha512.Initialize(); this.digestedLength = 0; } private readonly Machine machine; - private SHA512Managed sha512; - private SHA256Managed sha256; - // private byte[] hash; + private SHA512 sha512; public GPIO IRQ { get; private set; } + private List Sha512_256Backing; + private SHA512_256Managed Sha512_256Result; + private IFlagRegisterField powerIsOn; private IFlagRegisterField shaIsEnabled; private IFlagRegisterField inputIsSwapped; @@ -340,7 +351,6 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous private IFlagRegisterField sha512DonePending; private bool sha512DoneStatus; - private readonly uint bufferAddress = 0xE0002000; private UInt64 digestedLength; private enum Registers { @@ -372,3 +382,406 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous } } } + +namespace Antmicro.Renode.Peripherals.Miscellaneous +{ + using System.Globalization; + using System.Diagnostics.Contracts; + using System.Security.Cryptography; + using Antmicro.Renode.Core; + using Antmicro.Renode.Core.Structure.Registers; + using Antmicro.Renode.Logging; + using Antmicro.Renode.Peripherals.Bus; +} +public class SHA512_256Managed +{ + UInt64[] H0Sha512_256; + UInt64[] K512; + public byte[] Hash; + + // + // public constructors + // + + public SHA512_256Managed(byte[] plaintext) + { + // These eight 64-bit words are obtained from GenerateInitialHashSha512t(256) + // They are manually added to the array here due to bugs in the Renode C# parser. Attemtping + // to use a normal array will give an error such as: + // (SoC) i @peripherals/sha512.cs + // Errors during compilation or loading: + // Could not compile assembly: D:\Code\Xous\Core\emulation\peripherals\sha512.cs(407,5): + // 14:56:16.2452 [INFO] Including script: D:\Code\Xous\Core\emulation\peripherals\sha512.cs (2) + // (SoC) + this.H0Sha512_256 = new UInt64[8]; + this.H0Sha512_256[0] = 0x22312194fc2bf72c; + this.H0Sha512_256[1] = 0x9f555fa3c84c64c2; + this.H0Sha512_256[2] = 0x2393b86b6f53b151; + this.H0Sha512_256[3] = 0x963877195940eabd; + this.H0Sha512_256[4] = 0x96283ee2a88effe3; + this.H0Sha512_256[5] = 0xbe5e1e2553863992; + this.H0Sha512_256[6] = 0x2b0199fc2c85b8aa; + this.H0Sha512_256[7] = 0x0eb72ddc81c52ca2; + // The eighty 64-bit words in the array K512 are used in Sha-384, Sha-512, Sha-512/224, Sha-512/256. + // They are obtained by taking the first 64 bits of the fractional + // parts of the cube roots of the first eighty primes. + // They are manually added to the array here due to bugs in the Renode C# parser. + this.K512 = new UInt64[80]; + this.K512[0] = 0x428a2f98d728ae22; + this.K512[1] = 0x7137449123ef65cd; + this.K512[2] = 0xb5c0fbcfec4d3b2f; + this.K512[3] = 0xe9b5dba58189dbbc; + this.K512[4] = 0x3956c25bf348b538; + this.K512[5] = 0x59f111f1b605d019; + this.K512[6] = 0x923f82a4af194f9b; + this.K512[7] = 0xab1c5ed5da6d8118; + this.K512[8] = 0xd807aa98a3030242; + this.K512[9] = 0x12835b0145706fbe; + this.K512[10] = 0x243185be4ee4b28c; + this.K512[11] = 0x550c7dc3d5ffb4e2; + this.K512[12] = 0x72be5d74f27b896f; + this.K512[13] = 0x80deb1fe3b1696b1; + this.K512[14] = 0x9bdc06a725c71235; + this.K512[15] = 0xc19bf174cf692694; + this.K512[16] = 0xe49b69c19ef14ad2; + this.K512[17] = 0xefbe4786384f25e3; + this.K512[18] = 0x0fc19dc68b8cd5b5; + this.K512[19] = 0x240ca1cc77ac9c65; + this.K512[20] = 0x2de92c6f592b0275; + this.K512[21] = 0x4a7484aa6ea6e483; + this.K512[22] = 0x5cb0a9dcbd41fbd4; + this.K512[23] = 0x76f988da831153b5; + this.K512[24] = 0x983e5152ee66dfab; + this.K512[25] = 0xa831c66d2db43210; + this.K512[26] = 0xb00327c898fb213f; + this.K512[27] = 0xbf597fc7beef0ee4; + this.K512[28] = 0xc6e00bf33da88fc2; + this.K512[29] = 0xd5a79147930aa725; + this.K512[30] = 0x06ca6351e003826f; + this.K512[31] = 0x142929670a0e6e70; + this.K512[32] = 0x27b70a8546d22ffc; + this.K512[33] = 0x2e1b21385c26c926; + this.K512[34] = 0x4d2c6dfc5ac42aed; + this.K512[35] = 0x53380d139d95b3df; + this.K512[36] = 0x650a73548baf63de; + this.K512[37] = 0x766a0abb3c77b2a8; + this.K512[38] = 0x81c2c92e47edaee6; + this.K512[39] = 0x92722c851482353b; + this.K512[40] = 0xa2bfe8a14cf10364; + this.K512[41] = 0xa81a664bbc423001; + this.K512[42] = 0xc24b8b70d0f89791; + this.K512[43] = 0xc76c51a30654be30; + this.K512[44] = 0xd192e819d6ef5218; + this.K512[45] = 0xd69906245565a910; + this.K512[46] = 0xf40e35855771202a; + this.K512[47] = 0x106aa07032bbd1b8; + this.K512[48] = 0x19a4c116b8d2d0c8; + this.K512[49] = 0x1e376c085141ab53; + this.K512[50] = 0x2748774cdf8eeb99; + this.K512[51] = 0x34b0bcb5e19b48a8; + this.K512[52] = 0x391c0cb3c5c95a63; + this.K512[53] = 0x4ed8aa4ae3418acb; + this.K512[54] = 0x5b9cca4f7763e373; + this.K512[55] = 0x682e6ff3d6b2b8a3; + this.K512[56] = 0x748f82ee5defb2fc; + this.K512[57] = 0x78a5636f43172f60; + this.K512[58] = 0x84c87814a1f0ab72; + this.K512[59] = 0x8cc702081a6439ec; + this.K512[60] = 0x90befffa23631e28; + this.K512[61] = 0xa4506cebde82bde9; + this.K512[62] = 0xbef9a3f7b2c67915; + this.K512[63] = 0xc67178f2e372532b; + this.K512[64] = 0xca273eceea26619c; + this.K512[65] = 0xd186b8c721c0c207; + this.K512[66] = 0xeada7dd6cde0eb1e; + this.K512[67] = 0xf57d4f7fee6ed178; + this.K512[68] = 0x06f067aa72176fba; + this.K512[69] = 0x0a637dc5a2c898a6; + this.K512[70] = 0x113f9804bef90dae; + this.K512[71] = 0x1b710b35131c471b; + this.K512[72] = 0x28db77f523047d84; + this.K512[73] = 0x32caab7b40c72493; + this.K512[74] = 0x3c9ebe0a15c9bebc; + this.K512[75] = 0x431d67c49c100d4c; + this.K512[76] = 0x4cc5d4becb3e42b6; + this.K512[77] = 0x597f299cfc657e2a; + this.K512[78] = 0x5fcb6fab3ad6faec; + this.K512[79] = 0x6c44198c4a475817; + this.Hash = Sha512Algorithm(plaintext, this.H0Sha512_256, 256); + } + + byte[] Sha512Algorithm(byte[] plaintext, UInt64[] H0, int numberBits) + { + Block1024[] blocks = ConvertPaddedMessageToBlock1024Array(PadPlainText1024(plaintext)); + + // Define the hash variable and set its initial values. + UInt64[] H = H0; + + for (int i = 0; i < blocks.Length; i++) + { + UInt64[] W = CreateMessageScheduleSha512(blocks[i]); + + // Set the working variables a,...,h to the current hash values. + UInt64 a = H[0]; + UInt64 b = H[1]; + UInt64 c = H[2]; + UInt64 d = H[3]; + UInt64 e = H[4]; + UInt64 f = H[5]; + UInt64 g = H[6]; + UInt64 h = H[7]; + + for (int t = 0; t < 80; t++) + { + UInt64 T1 = h + Sigma1_512(e) + Ch(e, f, g) + this.K512[t] + W[t]; + UInt64 T2 = Sigma0_512(a) + Maj(a, b, c); + h = g; + g = f; + f = e; + e = d + T1; + d = c; + c = b; + b = a; + a = T1 + T2; + } + + // Update the current value of the hash H after processing block i. + H[0] += a; + H[1] += b; + H[2] += c; + H[3] += d; + H[4] += e; + H[5] += f; + H[6] += g; + H[7] += h; + } + + // Concatenate all the Word64 Hash Values + byte[] hash = ShaUtilities.Word64ArrayToByteArray(H); + + // The number of bytes in the final output hash + int numberBytes = numberBits / 8; + byte[] truncatedHash = new byte[numberBytes]; + Array.Copy(hash, truncatedHash, numberBytes); + + return truncatedHash; + } + + + static UInt32 Maj(UInt32 x, UInt32 y, UInt32 z) + { + return (x & y) ^ (x & z) ^ (y & z); + } + + static UInt64 Maj(UInt64 x, UInt64 y, UInt64 z) + { + return (x & y) ^ (x & z) ^ (y & z); + } + + static UInt32 Ch(UInt32 x, UInt32 y, UInt32 z) + { + return (x & y) ^ (~x & z); + } + + static UInt64 Ch(UInt64 x, UInt64 y, UInt64 z) + { + return (x & y) ^ (~x & z); + } + + static UInt64 Sigma0_512(UInt64 x) + { + return RotR(28, x) ^ RotR(34, x) ^ RotR(39, x); + } + + static UInt64 Sigma1_512(UInt64 x) + { + return RotR(14, x) ^ RotR(18, x) ^ RotR(41, x); + } + + static UInt64 sigma0_512(UInt64 x) + { + return RotR(1, x) ^ RotR(8, x) ^ ShR(7, x); + } + + static UInt64 sigma1_512(UInt64 x) + { + return RotR(19, x) ^ RotR(61, x) ^ ShR(6, x); + } + + + static UInt64 ShR(int n, UInt64 x) + { + // should have 0 <= n < 64 + return (x >> n); + } + static UInt32 RotR(int n, UInt32 x) + { + // should have 0 <= n < 32 + return (x >> n) | (x << 32 - n); + } + + static UInt64 RotR(int n, UInt64 x) + { + // should have 0 <= n < 64 + return (x >> n) | (x << 64 - n); + } + static byte[] PadPlainText1024(byte[] plaintext) + { + // After padding the total bits of the output will be divisible by 1024. + int numberBits = plaintext.Length * 8; + int t = (numberBits + 8 + 128) / 1024; + + // Note that 1024 * (t + 1) is the least multiple of 1024 greater than (numberBits + 8 + 128) + // Therefore the number of zero bits we need to add is + int k = 1024 * (t + 1) - (numberBits + 8 + 128); + + // Since numberBits % 8 = 0, we know k % 8 = 0. So n = k / 8 is the number of zero bytes to add. + int n = k / 8; + + List paddedtext = plaintext.ToList(); + + // Start the padding by concatenating 1000_0000 = 0x80 = 128 + paddedtext.Add(0x80); + + // Next add n zero bytes + for (int i = 0; i < n; i++) + { + paddedtext.Add(0); + } + + // Now add 16 bytes (128 bits) to represent the length of the message in bits. + // C# does not have 128 bit integer. + // For now just add 8 zero bytes and then 8 bytes to represent the int + for (int i = 0; i < 8; i++) + { + paddedtext.Add(0); + } + + byte[] B = BitConverter.GetBytes((ulong)numberBits); + Array.Reverse(B); + + for (int i = 0; i < B.Length; i++) + { + paddedtext.Add(B[i]); + } + + return paddedtext.ToArray(); + } + + static Block1024[] ConvertPaddedMessageToBlock1024Array(byte[] M) + { + // We are assuming M is padded, so the number of bits in M is divisible by 1024 + int numberBlocks = (M.Length * 8) / 1024; // same as: M.Length / 128 + Block1024[] blocks = new Block1024[numberBlocks]; + + for (int i = 0; i < numberBlocks; i++) + { + // First extract the relavant subarray from M + byte[] B = new byte[128]; // 128 * 8 = 1024 + + for (int j = 0; j < 128; j++) + { + B[j] = M[i * 128 + j]; + } + + UInt64[] words = ShaUtilities.ByteArrayToWord64Array(B); + blocks[i] = new Block1024(words); + } + + return blocks; + } + + static UInt64[] CreateMessageScheduleSha512(Block1024 block) + { + // The message schedule. + UInt64[] W = new UInt64[80]; + + // Prepare the message schedule W. + // The first 16 words in W are the same as the words of the block. + // The remaining 80-16 =64 words in W are functions of the previously defined words. + for (int t = 0; t < 80; t++) + { + if (t < 16) + { + W[t] = block.words[t]; + } + else + { + W[t] = sigma1_512(W[t - 2]) + W[t - 7] + sigma0_512(W[t - 15]) + W[t - 16]; + } + } + + return W; + } + + class Block1024 + { + // A Block1024 consists of an array of 16 elements of type Word64. + public UInt64[] words; + + public Block1024(UInt64[] words) + { + if (words.Length == 16) + { + this.words = words; + } + else + { + Console.WriteLine("ERROR: A block must be 16 words"); + this.words = null; + } + } + } + + static class ShaUtilities + { + public static UInt64[] ByteArrayToWord64Array(byte[] B) + { + // We assume B is not null, is not empty and number elements is divisible by 8 + int numberWords = B.Length / 8; // 8 bytes for each Word32 + UInt64[] word64Array = new UInt64[numberWords]; + + for (int i = 0; i < numberWords; i++) + { + word64Array[i] = ByteArrayToWord64(B, 8 * i); + } + + return word64Array; + } + + + public static UInt64 ByteArrayToWord64(byte[] B, int startIndex) + { + // We assume: 0 <= startIndex < B. Length, and startIndex + 8 <= B.Length + UInt64 c = 256; + UInt64 output = 0; + + for (int i = startIndex; i < startIndex + 8; i++) + { + output = output * c + B[i]; + } + + return output; + } + + // Returns an array of 8 bytes. + public static byte[] Word64ToByteArray(UInt64 x) + { + byte[] b = BitConverter.GetBytes(x); + Array.Reverse(b); + return b; + } + public static byte[] Word64ArrayToByteArray(UInt64[] words) + { + List b = new List(); + + for (int i = 0; i < words.Length; i++) + { + b.AddRange(Word64ToByteArray(words[i])); + } + + return b.ToArray(); + } + + } +} From 9b43b7e47509f3cf700a7f960dd418bd2f7c37c9 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 15:56:18 +0800 Subject: [PATCH 06/12] emulation: engine: remove unused properties These properties and variables were unused, and should be removed. Signed-off-by: Sean Cross --- emulation/peripherals/engine.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/emulation/peripherals/engine.cs b/emulation/peripherals/engine.cs index a0cd3484a..d332558a2 100644 --- a/emulation/peripherals/engine.cs +++ b/emulation/peripherals/engine.cs @@ -294,8 +294,6 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous this.RegistersCollection = new DoubleWordRegisterCollection(this); this.IRQ = new GPIO(); - this.shouldEndExecution = false; - this.startExecution = new SemaphoreSlim(0, 1); Reset(); DefineRegisters(); } @@ -310,7 +308,6 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous private void EngineThread() { - bool shouldLog = false; try { // this.Log(LogLevel.Error, "ENGINE: Beginning execution. Current MPC: 0x{0:X}", this.mpc); @@ -564,7 +561,6 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous private UInt16 mpc; private IFlagRegisterField powerIsOn; private IFlagRegisterField pauseRequest; - private readonly uint bufferAddress = 0xE0020000; private IFlagRegisterField illegalOpcodeEnabled; private IFlagRegisterField illegalOpcodePending; @@ -575,8 +571,6 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous private bool finishedStatus; private Thread engineExecution; - private bool shouldEndExecution; - private SemaphoreSlim startExecution; private EngineRam engineRam; From 50c5e1290d0526f7a334b2d849b20f351341c403 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 15:56:49 +0800 Subject: [PATCH 07/12] memlcd: implement vram Now that peripherals handle memory themselves, we need a special block to handle video memory. Signed-off-by: Sean Cross --- emulation/peripherals/memlcd.cs | 82 ++++++++++++++++++++++++++++++--- 1 file changed, 76 insertions(+), 6 deletions(-) diff --git a/emulation/peripherals/memlcd.cs b/emulation/peripherals/memlcd.cs index 431dceef0..ddf2d3401 100644 --- a/emulation/peripherals/memlcd.cs +++ b/emulation/peripherals/memlcd.cs @@ -14,11 +14,80 @@ using Antmicro.Renode.Peripherals.Bus; namespace Antmicro.Renode.Peripherals.Video { - public class BetrustedLCD : AutoRepaintingVideo, IDoubleWordPeripheral, IProvidesRegisterCollection, IKnownSize + + public class VideoRam : IBytePeripheral, IDoubleWordPeripheral, IWordPeripheral, IKnownSize { - public BetrustedLCD(Machine machine) : base(machine) + public VideoRam(Machine machine, BetrustedLCD lcd, long size) { this.machine = machine; + this.lcd = lcd; + this.size = size; + this.data = new byte[size]; + } + + private Machine machine; + private BetrustedLCD lcd; + private long size; + public byte[] data; + public long Size { get { return size; } } + + public void WriteDoubleWord(long address, uint value) + { + var bytes = BitConverter.GetBytes(value); + var i = 0; + for (i = 0; i < bytes.Length; i++) + { + this.data[address + i] = bytes[i]; + } + } + + public uint ReadDoubleWord(long offset) + { + return (((uint)this.data[offset]) << 0) | (((uint)this.data[offset + 1]) << 8) | (((uint)this.data[offset + 2]) << 16) | ((uint)(this.data[offset + 3]) << 24); + } + + public void WriteWord(long address, ushort value) + { + var bytes = BitConverter.GetBytes(value); + var i = 0; + for (i = 0; i < bytes.Length; i++) + { + this.data[address + i] = bytes[i]; + } + } + + public ushort ReadWord(long address) + { + return (ushort)((((ushort)this.data[address]) << 0) | (((ushort)this.data[address + 1]) << 8)); + } + + public byte ReadByte(long offset) + { + return this.data[offset]; + } + + public void WriteByte(long offset, byte value) + { + this.data[offset] = value; + } + + public void Reset() + { + for (var i = 0; i < this.data.Length; i++) + { + this.data[i] = 0; + } + } + } + + public class BetrustedLCD : AutoRepaintingVideo, IDoubleWordPeripheral, IProvidesRegisterCollection, IKnownSize + { + public BetrustedLCD(Machine machine, uint memAddr, uint memSize) : base(machine) + { + this.machine = machine; + this.videoRam = new VideoRam(machine, this, memSize); + this.bufferAddress = memAddr; + machine.SystemBus.Register(this.videoRam, new BusRangeRegistration(memAddr, memSize)); RegistersCollection = new DoubleWordRegisterCollection(this); Reconfigure(336, 536, PixelFormat.RGB565, true); @@ -44,6 +113,7 @@ namespace Antmicro.Renode.Peripherals.Video public override void Reset() { RegistersCollection.Reset(); + this.videoRam.Reset(); } public long Size { get { return 0x1000; } } @@ -52,7 +122,6 @@ namespace Antmicro.Renode.Peripherals.Video protected override void Repaint() { var newbuf = new Byte[44 * Height]; - machine.SystemBus.ReadBytes(bufferAddress, newbuf.Length, newbuf, 0); for (int y = 0; y < Height; y++) { // We should redraw the line if: @@ -65,7 +134,7 @@ namespace Antmicro.Renode.Peripherals.Video { break; } - if (updateDirty && (newbuf[y * 44 + i] != 0)) + if (updateDirty && (this.videoRam.data[y * 44 + i] != 0)) { shouldRedrawLine = true; } @@ -81,7 +150,7 @@ namespace Antmicro.Renode.Peripherals.Video } else { - if (((newbuf[(x + y * 44 * 8) / 8] >> (x % 8)) & 1) > 0) + if (((this.videoRam.data[(x + y * 44 * 8) / 8] >> (x % 8)) & 1) > 0) { buffer[2 * (x + y * Width)] = 0xFF; buffer[2 * (x + y * Width) + 1] = 0xFF; @@ -122,8 +191,9 @@ namespace Antmicro.Renode.Peripherals.Video private bool devBoot = false; private bool updateDirty = false; private bool updateAll = false; + private VideoRam videoRam; - private readonly uint bufferAddress = 0xB0000000; + private uint bufferAddress; private readonly Machine machine; From e15b3e9cc1037aaa4a8a3fbef0a4610cbf47af44 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 15:57:53 +0800 Subject: [PATCH 08/12] emulation: regenerate betrusted-soc.repl Signed-off-by: Sean Cross --- emulation/soc/betrusted-soc.repl | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/emulation/soc/betrusted-soc.repl b/emulation/soc/betrusted-soc.repl index 9c3b7e372..40285d809 100755 --- a/emulation/soc/betrusted-soc.repl +++ b/emulation/soc/betrusted-soc.repl @@ -29,6 +29,8 @@ app_uart: UART.LiteX_UART @ sysbus 0xf0009000 // Unrecognized peripheral: sram_ext memlcd: Video.BetrustedLCD @ sysbus 0xf000c000 + memAddr: 0xb0000000 + memSize: 0x5c20 // Unrecognized peripheral: com @@ -57,7 +59,7 @@ keyboard: Input.BetrustedKbd @ sysbus 0xf0016000 // Unrecognized peripheral: seed -// Unrecognized peripheral: keyrom +keyrom: Miscellaneous.Keyrom @ sysbus 0xf0019000 // Unrecognized peripheral: audio @@ -70,9 +72,14 @@ trng_server: Miscellaneous.BetrustedRNGServer @ sysbus 0xf001c000 // Unrecognized peripheral: trng sha512: Miscellaneous.Sha512 @ sysbus 0xf001e000 + memAddr: 0xe0002000 + memSize: 0x4 -> cpu @ 1015 -// Unrecognized peripheral: engine +engine: Miscellaneous.Engine @ sysbus 0xf001f000 + memAddr: 0xe0020000 + memSize: 0x20000 + -> cpu @ 1016 // Unrecognized peripheral: jtag @@ -86,30 +93,21 @@ sha512: Miscellaneous.Sha512 @ sysbus 0xf001e000 // Physical base addresses of memory regions -mem_rom: Memory.MappedMemory @ sysbus 0x80000000 +rom: Memory.MappedMemory @ sysbus 0x80000000 size: 0x00010000 -mem_vexriscv_debug: Memory.MappedMemory @ sysbus 0xefff0000 +vexriscv_debug: Memory.MappedMemory @ sysbus 0xefff0000 size: 0x00001000 -mem_sram_ext: Memory.MappedMemory @ sysbus 0x40000000 +sram_ext: Memory.MappedMemory @ sysbus 0x40000000 size: 0x01000000 -mem_memlcd: Memory.MappedMemory @ sysbus 0xb0000000 - size: 0x00006000 - -mem_spiflash: Memory.MappedMemory @ sysbus 0x20000000 +spiflash: Memory.MappedMemory @ sysbus 0x20000000 size: 0x08000000 -mem_audio: Memory.MappedMemory @ sysbus 0xe0000000 +audio: Memory.MappedMemory @ sysbus 0xe0000000 size: 0x00001000 -mem_sha512: Memory.MappedMemory @ sysbus 0xe0002000 - size: 0x00001000 - -mem_engine: Memory.MappedMemory @ sysbus 0xe0020000 - size: 0x00020000 - abracom_rtc: Sensors.ABRTCMC @ i2c 0x68 From fcbc901df897d2a543c8234b47026ce2411524d5 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 15:58:13 +0800 Subject: [PATCH 09/12] Cargo: update latest versions of dependencies Signed-off-by: Sean Cross --- Cargo.lock | 145 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 135 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ecd86939f..28ebbf57c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -102,6 +102,12 @@ dependencies = [ "rustc_version", ] +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + [[package]] name = "benchmark" version = "0.1.0" @@ -214,6 +220,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39092a32794787acd8525ee150305ff051b0aa6cc2abaf193924f5ab05425f39" +[[package]] +name = "bumpalo" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631" + [[package]] name = "byteorder" version = "1.4.2" @@ -627,7 +639,7 @@ dependencies = [ "once_cell", "proc-macro2 1.0.24", "quote 1.0.8", - "syn 1.0.60", + "syn 1.0.67", ] [[package]] @@ -943,6 +955,15 @@ version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" +[[package]] +name = "js-sys" +version = "0.3.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83bdfbace3a0e81a4253f73b49e960b053e396a11012cbd49b9b74d6a2b67062" +dependencies = [ + "wasm-bindgen", +] + [[package]] name = "kernel-test" version = "0.1.0" @@ -1146,7 +1167,7 @@ checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", - "syn 1.0.60", + "syn 1.0.67", ] [[package]] @@ -1199,6 +1220,17 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" +[[package]] +name = "pem" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56cbd21fea48d0c440b41cd69c589faacade08c992d9a54e471b79d0fd13eb" +dependencies = [ + "base64", + "once_cell", + "regex", +] + [[package]] name = "pkg-config" version = "0.3.19" @@ -1252,7 +1284,7 @@ checksum = "7bcd6232fa7d7fcd15703da5c07c9f10d203ee4fdf6ecf6d7ac5056db78089a3" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", - "syn 1.0.60", + "syn 1.0.67", ] [[package]] @@ -1428,6 +1460,21 @@ dependencies = [ "winapi", ] +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin", + "untrusted", + "web-sys", + "winapi", +] + [[package]] name = "rkyv" version = "0.3.1" @@ -1487,7 +1534,7 @@ checksum = "ddf04e93b51e6cfcc0eeee3bbf121d978303b83fbf2dc49085cff7855478fd4b" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", - "syn 1.0.60", + "syn 1.0.67", ] [[package]] @@ -1498,7 +1545,7 @@ checksum = "95a169f6bc5a81033e86ed39d0f4150e2608160b73d2b93c6e8e6a3efa873f14" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", - "syn 1.0.60", + "syn 1.0.67", ] [[package]] @@ -1667,6 +1714,12 @@ version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e" +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + [[package]] name = "stable_deref_trait" version = "1.2.0" @@ -1733,9 +1786,9 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.60" +version = "1.0.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c700597eca8a5a762beb35753ef6b94df201c81cca676604f547495a0d7f0081" +checksum = "6498a9efc342871f91cc2d0d694c674368b4ceb40f62b65a7a08c3792935e702" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", @@ -1750,7 +1803,7 @@ checksum = "b834f2d66f734cb897113e34aaff2f1ab4719ca946f9a7358dba8f8064148701" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", - "syn 1.0.60", + "syn 1.0.67", "unicode-xid 0.2.1", ] @@ -1856,6 +1909,8 @@ dependencies = [ "csv", "env_logger 0.7.1", "log", + "pem", + "ring", "svd2utra", "xmas-elf", ] @@ -1913,6 +1968,12 @@ dependencies = [ "regex", ] +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + [[package]] name = "utralib" version = "0.1.0" @@ -1975,6 +2036,60 @@ version = "0.10.2+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" +[[package]] +name = "wasm-bindgen" +version = "0.2.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d54ee1d4ed486f78874278e63e4069fc1ab9f6a18ca492076ffb90c5eb2997fd" +dependencies = [ + "cfg-if 1.0.0", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b33f6a0694ccfea53d94db8b2ed1c3a8a4c86dd936b13b9f0a15ec4a451b900" +dependencies = [ + "bumpalo", + "lazy_static", + "log", + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.67", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "088169ca61430fe1e58b8096c24975251700e7b1f6fd91cc9d59b04fb9b18bd4" +dependencies = [ + "quote 1.0.8", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be2241542ff3d9f241f5e2cb6dd09b37efe786df8851c54957683a49f0987a97" +dependencies = [ + "proc-macro2 1.0.24", + "quote 1.0.8", + "syn 1.0.67", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f" + [[package]] name = "wayland-client" version = "0.28.5" @@ -2045,6 +2160,16 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "web-sys" +version = "0.3.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e828417b379f3df7111d3a2a9e5753706cae29c41f7c4029ee9fd77f3e09e582" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "which" version = "3.1.1" @@ -2192,7 +2317,7 @@ dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", "rand 0.7.3", - "syn 1.0.60", + "syn 1.0.67", ] [[package]] @@ -2238,6 +2363,6 @@ checksum = "a2c1e130bebaeab2f23886bf9acbaca14b092408c452543c857f66399cd6dab1" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", - "syn 1.0.60", + "syn 1.0.67", "synstructure", ] From aaa4407e216e1af8985829fbb5f127bcbfd10f8f Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 16:39:35 +0800 Subject: [PATCH 10/12] sign-image: enable kernel image signing Previously we only supported signing the loader. This also adds the kernel as a thing that can be signed. Signed-off-by: Sean Cross --- tools/src/bin/sign-image.rs | 75 +++++++++++++++++++++++++------------ 1 file changed, 52 insertions(+), 23 deletions(-) diff --git a/tools/src/bin/sign-image.rs b/tools/src/bin/sign-image.rs index d2feab65e..a20dd5407 100644 --- a/tools/src/bin/sign-image.rs +++ b/tools/src/bin/sign-image.rs @@ -7,7 +7,7 @@ use ring::signature::Ed25519KeyPair; const DEVKEY_PATH: &str = "devkey/dev.key"; const LOADER_VERSION: u32 = 1; -fn loader_sign( +fn image_sign( input: &S, output: &T, private_key: &pem::Pem, @@ -100,6 +100,7 @@ fn main() -> Result<(), Box> { ) .arg( Arg::with_name("kernel-key") + .long("kernel-key") .takes_value(true) .required(true) .help("kernel signing key") @@ -108,11 +109,17 @@ fn main() -> Result<(), Box> { ) .arg( Arg::with_name("loader-output") + .long("loader-output") .takes_value(true) - .required(true) .value_name("loader output image") - .help("loader output image") - .default_value("target/riscv32imac-unknown-none-elf/release/loader.bin"), + .help("loader output image"), + ) + .arg( + Arg::with_name("kernel-output") + .long("kernel-output") + .takes_value(true) + .value_name("kernel output image") + .help("kernel output image"), ) .arg( Arg::with_name("defile").help( @@ -121,27 +128,49 @@ fn main() -> Result<(), Box> { ) .get_matches(); - let loader_key = matches - .value_of("loader-key") - .expect("no loader key specified"); - let loader_output = matches - .value_of("loader-output") - .expect("no output specified"); - let loader_image = matches - .value_of("loader-image") - .expect("no loader image specified"); + // Sign the loader, if an output file was specified + if let Some(loader_output) = matches.value_of("loader-output") { + let loader_key = matches + .value_of("loader-key") + .expect("no loader key specified"); + let loader_image = matches + .value_of("loader-image") + .expect("no loader image specified"); - let loader_pkey = load_pem(loader_key)?; - if loader_pkey.tag != "PRIVATE KEY" { - println!("Loader key was a {}, not a PRIVATE KEY", loader_pkey.tag); - Err("invalid pkey type")?; + let loader_pkey = load_pem(loader_key)?; + if loader_pkey.tag != "PRIVATE KEY" { + println!("Loader key was a {}, not a PRIVATE KEY", loader_pkey.tag); + Err("invalid loader private key type")?; + } + println!("Signing loader"); + image_sign( + &loader_image, + &loader_output, + &loader_pkey, + matches.is_present("defile"), + )?; } - loader_sign( - &loader_image, - &loader_output, - &loader_pkey, - matches.is_present("defile"), - )?; + if let Some(kernel_output) = matches.value_of("kernel-output") { + let kernel_key = matches + .value_of("kernel-key") + .expect("no kernel key specified"); + let kernel_image = matches + .value_of("kernel-image") + .expect("no kernel image specified"); + + let kernel_pkey = load_pem(kernel_key)?; + if kernel_pkey.tag != "PRIVATE KEY" { + println!("Kernel key was a {}, not a PRIVATE KEY", kernel_pkey.tag); + Err("invalid kernel private key type")?; + } + println!("Signing kernel"); + image_sign( + &kernel_image, + &kernel_output, + &kernel_pkey, + matches.is_present("defile"), + )?; + } Ok(()) } From 20c91866dd9eb4bf14c88c4d35f952cd8cdd48e5 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 16:41:23 +0800 Subject: [PATCH 11/12] emulation: add keystore and engine to loaded files These blocks are now supported as emulation targets. Signed-off-by: Sean Cross --- emulation/xous-release.resc | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/emulation/xous-release.resc b/emulation/xous-release.resc index 95bbadbfb..6d372ba28 100644 --- a/emulation/xous-release.resc +++ b/emulation/xous-release.resc @@ -10,7 +10,9 @@ using sysbus # if you modify these files. i @peripherals/ABRTCMC.cs i @peripherals/BetrustedI2C.cs +i @peripherals/engine.cs i @peripherals/keyboard.cs +i @peripherals/keyrom.cs i @peripherals/LiteX_Timer_32.cs i @peripherals/memlcd.cs i @peripherals/sha512.cs @@ -28,12 +30,18 @@ showAnalyzer console # showAnalyzer app_uart showAnalyzer memlcd +# sysbus LogPeripheralAccess engine true +# sysbus LogPeripheralAccess sha512 true +# sysbus LogPeripheralAccess trng_kernel true + sysbus Tag <0xB0000000, 0xB0006000> "Framebuffer" # logLevel -1 keyboard # logLevel -1 ticktimer -logLevel -1 i2c -logLevel -1 abracom_rtc +# logLevel -1 engine +# logLevel -1 i2c +# logLevel -1 abracom_rtc +# logLevel -1 sha512 # Silence COM and WDT and WFI sysbus SilenceRange <0xF000D000, 0xF000DFFF> @@ -44,7 +52,7 @@ sysbus SilenceRange <0xF0023000, 0xF0023FFF> macro reset """ sysbus LoadELF @../loader/target/riscv32imac-unknown-none-elf/release/loader - sysbus LoadBinary @../target/riscv32imac-unknown-none-elf/release/args.bin 0x40800000 + sysbus LoadBinary @../target/riscv32imac-unknown-none-elf/release/xous.img 0x40800000 # Set $a0 to point at the args binary cpu SetRegisterUnsafe 10 0x40800000 """ From b78073d7ed8c0dfd7c413a32787595c5d2c51691 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 15 Jul 2021 16:41:56 +0800 Subject: [PATCH 12/12] xtask: use rust to sign binaries, sign Renode images This removes Python as a dependency. Additionally, Renode images are now signed. Signed-off-by: Sean Cross --- xtask/src/main.rs | 178 +++++++++++++++++----------------------------- 1 file changed, 66 insertions(+), 112 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 98a21c7e3..e09971195 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -75,8 +75,8 @@ fn try_main() -> Result<(), DynError> { "xous-names", "trng", "llio", -// "rkyv-test-client", -// "rkyv-test-server", + // "rkyv-test-client", + // "rkyv-test-server", "test-stub", "susres", "com", @@ -114,33 +114,49 @@ fn try_main() -> Result<(), DynError> { match task.as_deref() { Some("renode-image") => renode_image(false, &hw_pkgs)?, Some("renode-test") => renode_image(false, &cbtest_pkgs)?, - Some("libstd-test") => renode_image_extra(false, &base_pkgs, args.collect())?, + Some("libstd-test") => { + let mut pkgs = base_pkgs.to_vec(); + let args: Vec = args.collect(); + for program in &args { + pkgs.push(&program); + } + renode_image(false, &pkgs)?; + } Some("renode-aes-test") => renode_image(false, &aestest_pkgs)?, Some("renode-image-debug") => renode_image(true, &hw_pkgs)?, Some("run") => run(false, &hw_pkgs)?, Some("hw-image") => build_hw_image(false, env::args().nth(2), &hw_pkgs, lkey, kkey, None)?, - Some("benchmark") => build_hw_image(false, env::args().nth(2), &benchmark_pkgs, lkey, kkey, None)?, - Some("minimal") => build_hw_image(false, env::args().nth(2), &minimal_pkgs, lkey, kkey, None)?, - Some("cbtest") => build_hw_image(false, env::args().nth(2), &cbtest_pkgs, lkey, kkey, None)?, + Some("benchmark") => { + build_hw_image(false, env::args().nth(2), &benchmark_pkgs, lkey, kkey, None)? + } + Some("minimal") => { + build_hw_image(false, env::args().nth(2), &minimal_pkgs, lkey, kkey, None)? + } + Some("cbtest") => { + build_hw_image(false, env::args().nth(2), &cbtest_pkgs, lkey, kkey, None)? + } Some("trng-test") => build_hw_image( false, env::args().nth(2), &hw_pkgs, - lkey, kkey, + lkey, + kkey, Some(&["--features", "urandomtest"]), )?, Some("ro-test") => build_hw_image( false, env::args().nth(2), &hw_pkgs, - lkey, kkey, + lkey, + kkey, Some(&["--features", "ringosctest"]), )?, Some("av-test") => build_hw_image( false, env::args().nth(2), &hw_pkgs, - lkey, kkey, + lkey, + kkey, Some(&["--features", "avalanchetest"]), )?, Some("sr-test") => build_hw_image(false, env::args().nth(2), &sr_pkgs, lkey, kkey, None)?, @@ -261,12 +277,12 @@ fn build_hw_image( let loaderkey_file = if let Some(lkf) = lkey { lkf } else { - String::from("../devkey/dev.key") + String::from("devkey/dev.key") }; let kernelkey_file = if let Some(kkf) = kkey { kkf } else { - String::from("../devkey/dev.key") + String::from("devkey/dev.key") }; let kernel = build_kernel(debug)?; @@ -314,26 +330,33 @@ fn build_hw_image( return Err("cargo build failed".into()); } - let status = Command::new("python3") - .current_dir(project_root().join("tools")) + let status = Command::new(cargo()) + .current_dir(project_root()) .args(&[ - "sign_image.py", + "run", + "--package", + "tools", + "--bin", + "sign-image", + "--", "--loader-image", loader_presign.to_str().unwrap(), "--loader-key", loaderkey_file.as_str(), "--loader-output", loader_bin.to_str().unwrap(), - ]).status()?; + ]) + .status()?; if !status.success() { - return Err("loader image sign failed".into()) + return Err("loader image sign failed".into()); } let mut xous_img_path = output_bundle.parent().unwrap().to_owned(); let mut xous_img_presign_path = xous_img_path.clone(); xous_img_path.push("xous.img"); xous_img_presign_path.push("xous_presign.img"); - let mut xous_img = std::fs::File::create(&xous_img_presign_path).expect("couldn't create xous.img"); + let mut xous_img = + std::fs::File::create(&xous_img_presign_path).expect("couldn't create xous.img"); let mut bundle_file = std::fs::File::open(output_bundle).expect("couldn't open output bundle"); let mut buf = vec![]; bundle_file @@ -344,20 +367,26 @@ fn build_hw_image( .expect("couldn't write bundle file to xous.img"); println!("Bundled image file created at {}", xous_img_path.display()); - let status = Command::new("python3") - .current_dir(project_root().join("tools")) - .args(&[ - "sign_image.py", - "--kernel-image", - xous_img_presign_path.to_str().unwrap(), - "--kernel-key", - kernelkey_file.as_str(), - "--kernel-output", - xous_img_path.to_str().unwrap(), - // "--defile", - ]).status()?; + let status = Command::new(cargo()) + .current_dir(project_root()) + .args(&[ + "run", + "--package", + "tools", + "--bin", + "sign-image", + "--", + "--kernel-image", + xous_img_presign_path.to_str().unwrap(), + "--kernel-key", + kernelkey_file.as_str(), + "--kernel-output", + xous_img_path.to_str().unwrap(), + // "--defile", + ]) + .status()?; if !status.success() { - return Err("kernel image sign failed".into()) + return Err("kernel image sign failed".into()); } println!(); @@ -379,31 +408,6 @@ fn sign_loader(in_path: Pathbuf, out_path: Pathbuf) -> Result<(), DynError> { }*/ fn renode_image(debug: bool, packages: &[&str]) -> Result<(), DynError> { - let path = std::path::Path::new("emulation/soc/renode.svd"); - std::env::set_var("XOUS_SVD_FILE", path.canonicalize().unwrap()); - let kernel = build_kernel(debug)?; - let mut init = vec![]; - let base_path = build(packages, debug, Some(TARGET), None, None)?; - for pkg in packages { - let mut pkg_path = base_path.clone(); - pkg_path.push(pkg); - init.push(pkg_path); - } - build( - &["loader"], - debug, - Some(TARGET), - Some("loader".into()), - None, - )?; - - create_image( - &kernel, - &init, - debug, - MemorySpec::SvdFile("emulation/soc/renode.svd".into()), - )?; - // Regenerate the Platform file let status = Command::new(cargo()) .current_dir(project_root()) @@ -421,64 +425,14 @@ fn renode_image(debug: bool, packages: &[&str]) -> Result<(), DynError> { if !status.success() { Err("Unable to regenerate Renode platform file")?; } - - Ok(()) -} - -/// Create a Renode image, and include the extra init programs specified -/// on the command line. -fn renode_image_extra( - debug: bool, - packages: &[&str], - extra_init: Vec, -) -> Result<(), DynError> { - let path = std::path::Path::new("emulation/soc/renode.svd"); - std::env::set_var("XOUS_SVD_FILE", path.canonicalize().unwrap()); - let kernel = build_kernel(debug)?; - let mut init = vec![]; - let base_path = build(packages, debug, Some(TARGET), None, None)?; - for pkg in packages { - let mut pkg_path = base_path.clone(); - pkg_path.push(pkg); - init.push(pkg_path); - } - for pkg in extra_init { - init.push(pkg.try_into().unwrap()); - } - build( - &["loader"], - debug, - Some(TARGET), - Some("loader".into()), + build_hw_image( + false, + Some("emulation/soc/renode.svd".to_owned()), + packages, None, - )?; - - create_image( - &kernel, - &init, - debug, - MemorySpec::SvdFile("emulation/soc/renode.svd".into()), - )?; - - // Regenerate the Platform file - let status = Command::new(cargo()) - .current_dir(project_root()) - .args(&[ - "run", - "-p", - "svd2repl", - "--", - "-i", - "emulation/soc/renode.svd", - "-o", - "emulation/soc/betrusted-soc.repl", - ]) - .status()?; - if !status.success() { - Err("Unable to regenerate Renode platform file")?; - } - - Ok(()) + None, + None, + ) } fn run(debug: bool, init: &[&str]) -> Result<(), DynError> {