diff --git a/Cargo.lock b/Cargo.lock index 23ab3f80b..ee5ccbe3d 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]] @@ -1668,6 +1715,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 = "spinor" version = "0.1.0" @@ -1756,9 +1809,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", @@ -1773,7 +1826,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", ] @@ -1879,6 +1932,8 @@ dependencies = [ "csv", "env_logger 0.7.1", "log", + "pem", + "ring", "svd2utra", "xmas-elf", ] @@ -1936,6 +1991,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" @@ -1998,6 +2059,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" @@ -2068,6 +2183,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" @@ -2215,7 +2340,7 @@ dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", "rand 0.7.3", - "syn 1.0.60", + "syn 1.0.67", ] [[package]] @@ -2261,6 +2386,6 @@ checksum = "a2c1e130bebaeab2f23886bf9acbaca14b092408c452543c857f66399cd6dab1" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.8", - "syn 1.0.60", + "syn 1.0.67", "synstructure", ] diff --git a/docs/flash.md b/docs/flash.md index 052d2a6d9..9154a5105 100644 --- a/docs/flash.md +++ b/docs/flash.md @@ -128,7 +128,7 @@ This documents their location in FLASH. The samples are shorter than the allocat + 2608_0000 | 44.1khz short sample (WAV/<2,816kiB) | + 2633_FFFF | 16-bit stereo PCM ~16s long | +-----------+----------------------------------------+ -+ 2634_0000 | 8khz short sample (WAV/<28,928kiB) | ++ 2634_0000 | 8khz long sample (WAV/<28,928kiB) | + 27F7_FFFF | 16-bit stereo PCM ~330s long | +-----------+----------------------------------------+ + 27F8_0000 | Start of EC region (do not use) | diff --git a/emulation/peripherals/engine.cs b/emulation/peripherals/engine.cs new file mode 100644 index 000000000..e3911eb5e --- /dev/null +++ b/emulation/peripherals/engine.cs @@ -0,0 +1,652 @@ +// +// 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.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; + +namespace Antmicro.Renode.Peripherals.Miscellaneous +{ + public class EngineRam : IDoubleWordPeripheral, IKnownSize + { + public EngineRam(Machine machine, Engine engine, long size) + { + this.machine = machine; + this.engine = engine; + this.size = size; + this.data = new UInt32[size / 4]; + this.FIELD_MAX = BigInteger.Pow(2, 255) - 19; + this.UINT_MAX = BigInteger.Pow(2, 256) - 1; + this.ZERO = new BigInteger(0); + this.ONE = new BigInteger(1); + + this.AM24 = new BigInteger(121665); // (A-2)/4 + this.AP24 = new BigInteger(121666); // (A+2)/4 + this.FIVE = new BigInteger(5); + this.TEN = new BigInteger(10); + this.TWENTY = new BigInteger(20); + this.FIFTY = new BigInteger(50); + this.ONE_HUNDRED = new BigInteger(100); + this.registers = new BigInteger[32]; + for (var i = 0; i < this.registers.Length; i++) + { + this.registers[i] = this.ZERO; + } + } + + public void SyncRegistersFromRam(ulong rf) + { + for (var i = 0; i < this.registers.Length; i++) + { + this.registers[i] = ReadRegisterFromRam(rf, (ulong)i); + } + } + + public void SyncRegistersToRam(ulong rf) + { + for (var i = 0; i < this.registers.Length; i++) + { + WriteRegisterToRam(rf, (ulong)i, this.registers[i]); + } + } + + public BigInteger UINT_MAX; + public BigInteger ZERO; + public BigInteger ONE; + public BigInteger AM24; + public BigInteger FIELD_MAX; + public BigInteger AP24; + public BigInteger FIVE; + public BigInteger TEN; + public BigInteger TWENTY; + public BigInteger FIFTY; + public BigInteger ONE_HUNDRED; + + private Machine machine; + private Engine engine; + private long size; + public UInt32[] data; + public BigInteger[] registers; + 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 BigInteger ReadRegister(ulong register, bool constant) + { + // this.Log(LogLevel.Error, "Reading register {0} (const? {1}) from rf {2}", register, constant, rf); + if (constant) + { + switch (register) + { + case 0: return this.ZERO; + case 1: return this.ONE; + case 2: return this.AM24; + case 3: return this.FIELD_MAX; + case 4: return this.AP24; + case 5: return this.FIVE; + case 6: return this.TEN; + case 7: return this.TWENTY; + case 8: return this.FIFTY; + case 9: return this.ONE_HUNDRED; + default: return this.ZERO; + } + } + return this.registers[register]; + } + public BigInteger ReadRegisterFromRam(ulong rf, ulong register) + { + 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 < 32; i += 4) + { + var offset = 0x10000 + (rf * 1024) + (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 BigInteger(src_bytes); + } + + public void WriteRegisterToRam(ulong rf, ulong 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 bytes = value.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 void WriteRegister(ulong register, BigInteger value) + { + this.registers[register] = value & this.UINT_MAX; + } + + 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() + { + 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"; + } + } + + 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(); + Reset(); + DefineRegisters(); + } + + ~Engine() + { + if ((this.engineExecution != null) && (this.engineExecution.IsAlive)) + { + this.engineExecution.Abort(); + } + } + + private void EngineThread() + { + // this.Log(LogLevel.Error, "ENGINE: Beginning execution. Current MPC: 0x{0:X}", this.mpstart); + try + { + // Interlocked.Exchange(ref this.mpc, this.mpstart); + this.mpc = this.mpstart; + var window = this.window; + this.engineRam.SyncRegistersFromRam(window); + + 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(op.Wd, this.engineRam.ReadRegister(op.Ra, op.Ca)); + this.engineRam.WriteRegister(op.Wd, this.engineRam.ReadRegister(op.Ra, op.Ca)); + break; + + case 1: // PSB + this.engineRam.WriteRegister(op.Wd, this.engineRam.ReadRegister(op.Rb, op.Cb)); + break; + + case 2: // MSK + if ((this.engineRam.ReadRegister(op.Ra, op.Ca) & 1) != 0) + { + this.engineRam.WriteRegister(op.Wd, this.engineRam.ReadRegister(op.Rb, op.Cb)); + } + else + { + this.engineRam.WriteRegister(op.Wd, this.engineRam.ZERO); + } + break; + + case 3: // XOR + this.engineRam.WriteRegister(op.Wd, + (BigInteger.Pow(2, 256) | this.engineRam.ReadRegister(op.Ra, op.Ca)) ^ this.engineRam.ReadRegister(op.Rb, op.Cb)); + break; + + case 4: // NOT + this.engineRam.WriteRegister(op.Wd, + ~(this.engineRam.ReadRegister(op.Ra, op.Ca) | BigInteger.Pow(2, 256))); + break; + + case 5: // ADD + this.engineRam.WriteRegister(op.Wd, + this.engineRam.ReadRegister(op.Ra, op.Ca) + this.engineRam.ReadRegister(op.Rb, op.Cb)); + break; + + case 6: // SUB + { + var left = this.engineRam.ReadRegister(op.Ra, op.Ca); + var right = this.engineRam.ReadRegister(op.Rb, op.Cb); + var result = left - right; + // Wrap integer + if (result < 0) + { + result = BigInteger.Pow(2, 256) - result; + } + this.engineRam.WriteRegister(op.Wd, result); + } + break; + + case 7: // MUL + this.engineRam.WriteRegister(op.Wd, + (this.engineRam.ReadRegister(op.Ra, op.Ca) + * this.engineRam.ReadRegister(op.Rb, op.Cb)) + % this.engineRam.FIELD_MAX + ); + break; + + case 8: // TRD + if (this.engineRam.ReadRegister(op.Ra, op.Ca) >= this.engineRam.FIELD_MAX) + { + this.engineRam.WriteRegister(op.Wd, this.engineRam.FIELD_MAX); + } + else + { + this.engineRam.WriteRegister(op.Wd, this.engineRam.ZERO); + } + break; + + case 9: // BRZ + if (this.engineRam.ReadRegister(op.Ra, op.Ca) == 0) + { + this.mpc = (ushort)((int)this.mpc + op.Immediate); + } + break; + + case 10: // FIN + break; + + case 11: // SHL + this.engineRam.WriteRegister(op.Wd, this.engineRam.ReadRegister(op.Ra, op.Ca) << 1); + break; + + case 12: // XBT + if ((this.engineRam.ReadRegister(op.Ra, op.Ca) & (this.engineRam.ONE << 254)) != 0) + { + this.engineRam.WriteRegister(op.Wd, this.engineRam.ONE); + } + else + { + this.engineRam.WriteRegister(op.Wd, this.engineRam.ZERO); + } + break; + + default: + this.illegalOpcodeStatus = true; + throw new Exception("Unhandled opcode"); + } + // Interlocked.Increment(ref this.mpc); + this.mpc += 1; + if (op.Op == 10) + { + break; + } + // this.Log(LogLevel.Error, " (Result) {0}", this.engineRam.FormatValue(this.engineRam.ReadRegister(op.Wd, false))); + } + } + catch (Exception e) + { + this.Log(LogLevel.Error, "ENGINE execution exception {0}", e); + } + this.finishedStatus = true; + // this.engineExecution = null; + this.engineRam.SyncRegistersToRam(window); + this.UpdateInterrupts(); + this.finishedStatus = false; + this.illegalOpcodeStatus = false; + // this.Log(LogLevel.Error, "ENGINE finished execution"); + } + + private void DefineRegisters() + { + Registers.WINDOW.Define(this) + .WithValueField(0, 4, name: "WINDOW", valueProviderCallback: (_) => this.window, writeCallback: (_, value) => this.window = (byte)(value & 0xf)) + ; + + Registers.MPSTART.Define(this) + .WithValueField(0, 11, name: "MPSTART", valueProviderCallback: (_) => this.mpstart, writeCallback: (_, value) => this.mpstart = (UInt16)(value & 0x7ff)) + ; + + Registers.MPLEN.Define(this) + .WithValueField(0, 11, name: "MPLEN", valueProviderCallback: _ => this.mplen, writeCallback: (_, value) => this.mplen = (UInt16)(value & 0x7ff)) + ; + + Registers.CONTROL.Define(this) + .WithFlag(0, FieldMode.Write, name: "GO", writeCallback: (_, value) => + { + if (value) + { + if ((this.engineExecution != null) && (this.engineExecution.IsAlive)) + { + this.Log(LogLevel.Error, "ENGINE already executing -- not re-running"); + } + else + { + this.engineExecution = new Thread(this.EngineThread) { Name = "Engine Execution", IsBackground = true }; + this.engineExecution.Start(); + } + } + }) + ; + + Registers.MPRESUME.Define(this) + .WithValueField(0, 11, name: "MPRESUME", valueProviderCallback: _ => this.mpresume, writeCallback: (_, value) => { this.mpresume = (UInt16)(value & 0x7ff); }) + ; + + 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: (_) => this.engineExecution.IsAlive) + .WithValueField(1, 10, name: "MPC", valueProviderCallback: (_) => (uint)this.mpc) + .WithFlag(11, name: "PAUSE_GNT", valueProviderCallback: (_) => false) + ; + + Registers.EV_STATUS.Define32(this) + .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 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 finishedEnabled, name: "FINISHED", changeCallback: (_, __) => UpdateInterrupts()) + .WithFlag(1, out illegalOpcodeEnabled, name: "ILLEGAL_OPCODE", changeCallback: (_, __) => UpdateInterrupts()) + ; + + Registers.INSTRUCTION.Define(this) + .WithValueField(0, 32, valueProviderCallback: _ => this.engineRam.data[this.mpc]) + ; + } + + private void UpdateInterrupts() + { + if (this.illegalOpcodeStatus) + { + this.illegalOpcodePending.Value = true; + } + if (this.finishedStatus) + { + 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.engineExecution != null) { + if (this.engineExecution.IsAlive) { + this.engineExecution.Abort(); + } + this.engineExecution = null; + } + 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 int mpc; + private IFlagRegisterField powerIsOn; + private IFlagRegisterField pauseRequest; + + private IFlagRegisterField illegalOpcodeEnabled; + private IFlagRegisterField illegalOpcodePending; + private bool illegalOpcodeStatus; + + private IFlagRegisterField finishedEnabled; + private IFlagRegisterField finishedPending; + private bool finishedStatus; + + private Thread engineExecution; + + private EngineRam engineRam; + + 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 + } + } + + 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; + } + } +} diff --git a/emulation/peripherals/keyrom.cs b/emulation/peripherals/keyrom.cs new file mode 100644 index 000000000..ae7cfc898 --- /dev/null +++ b/emulation/peripherals/keyrom.cs @@ -0,0 +1,106 @@ +// +// 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 Keyrom : IDoubleWordPeripheral, IProvidesRegisterCollection, IKnownSize + { + public Keyrom(Machine machine) + { + RegistersCollection = new DoubleWordRegisterCollection(this); + this.address = 0; + this.data = new UInt32[256]; + this.locked = new bool[256]; + Reset(); + DefineRegisters(); + } + + private void DefineRegisters() + { + Registers.ADDRESS.Define(this) + .WithValueField(0, 8, writeCallback: (_, value) => { this.address = value; }, valueProviderCallback: _ => { return this.address; }) + ; + + Registers.DATA.Define(this) + .WithValueField(0, 32, valueProviderCallback: _ => { if (this.locked[this.address]) { return 0xaa; } return this.data[this.address]; }) + ; + + Registers.LOCKADDR.Define(this) + .WithValueField(0, 8, name: "LOCKADDR", changeCallback: (_, address) => + { + this.locked[address] = true; + }) + ; + Registers.LOCKSTAT.Define(this) + .WithFlag(0, name: "LOCKSTAT", valueProviderCallback: _ => { return this.locked[this.address]; }) + ; + } + + 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.address = 0; + for (var i = 0; i < this.locked.Length; i++) + { + this.locked[i] = false; + } + + this.data[0x18] = 0x1c9beae3; + this.data[0x19] = 0x2aeac875; + this.data[0x1a] = 0x07c18094; + this.data[0x1b] = 0x387eff1c; + this.data[0x1c] = 0x74614282; + this.data[0x1d] = 0xaffd8152; + this.data[0x1e] = 0xd871352e; + this.data[0x1f] = 0xdf3f58bb; + // Words are swapped on this little-endian system. + // this.data[0x18] = 0xe3ea9b1c; + // this.data[0x19] = 0x75c8ea2a; + // this.data[0x1a] = 0x9480c107; + // this.data[0x1b] = 0x1cff7e38; + // this.data[0x1c] = 0x82426174; + // this.data[0x1d] = 0x5281fdaf; + // this.data[0x1e] = 0x2e3571d8; + // this.data[0x1f] = 0xbb583fdf; + this.lockAddress = 0; + } + + private uint address; + private UInt32[] data; + private bool[] locked; + private uint lockAddress; + + private enum Registers + { + ADDRESS = 0x00, + DATA = 0x04, + LOCKADDR = 0x08, + LOCKSTAT = 0x0C, + } + } +} 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; diff --git a/emulation/peripherals/sha512.cs b/emulation/peripherals/sha512.cs index f967a6556..5cc84d8f5 100644 --- a/emulation/peripherals/sha512.cs +++ b/emulation/peripherals/sha512.cs @@ -7,92 +7,150 @@ // 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 { - public class Sha512 : IDoubleWordPeripheral, IProvidesRegisterCollection, IKnownSize + 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 Sha512(Machine machine) + public Sha512Writer(Machine machine, Sha512 sha512) { this.machine = machine; - machine.SystemBus.AddWatchpointHook(this.bufferAddress, SysbusAccessWidth.DoubleWord, Access.Write, (cpu, encounteredAddress, width, encounteredValue) => + this.sha512 = sha512; + } + + private Machine machine; + private Sha512 sha512; + public long Size { get { return 4096; } } + + public void WriteDoubleWord(long offset, uint value) + { + if (offset != 0) { - this.Log(LogLevel.Error, "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; - }); + this.Log(LogLevel.Error, "Adding word 0x{0:X} (at address 0x{1:X}) to hash", value, offset); + } + this.sha512.add32ToHash(value, (uint)offset); + } + + public uint ReadDoubleWord(long offset) + { + return RegistersCollection.Read(offset); + } + + public byte ReadByte(long offset) + { + this.Log(LogLevel.Error, "Reading byte from 0x{0:X}", offset); + return 0; + } + + 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; } + + public void Reset() + { + } + + } + public class Sha512 : IDoubleWordPeripheral, IProvidesRegisterCollection, IKnownSize + { + public Sha512(Machine machine, uint memAddr, uint memSize) + { + this.machine = machine; + var sha512Writer = new Sha512Writer(machine, this); + machine.SystemBus.Register(sha512Writer, new BusRangeRegistration(memAddr, memSize)); + RegistersCollection = new DoubleWordRegisterCollection(this); this.IRQ = new GPIO(); this.sha512 = new SHA512Managed(); - this.sha256 = new SHA256Managed(); - this.hash = new byte[64]; Reset(); DefineRegisters(); } - private uint ResultAtOffset(int offset) + public void add32ToHash(UInt32 encounteredValue, uint address) { - if (usingSha256.Value && offset >= 32) + var inputBuffer = new byte[4]; + if (!this.inputIsSwapped.Value) { - 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 - 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); + inputBuffer[3] = (byte)(encounteredValue >> 0); + inputBuffer[2] = (byte)(encounteredValue >> 8); + inputBuffer[1] = (byte)(encounteredValue >> 16); + inputBuffer[0] = (byte)(encounteredValue >> 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); + inputBuffer[0] = (byte)(encounteredValue >> 0); + inputBuffer[1] = (byte)(encounteredValue >> 8); + inputBuffer[2] = (byte)(encounteredValue >> 16); + inputBuffer[3] = (byte)(encounteredValue >> 24); + } + if (this.usingSha256.Value) + { + foreach (byte b in inputBuffer) + { + this.Sha512_256Backing.Add(b); + } + } + 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) + { + // this.Log(LogLevel.Error, "Hash is: {0} Offset[{1}]: 0x{2:X}", this.sha512, offset, this.sha512.Hash[offset + 0]); + if (usingSha256.Value && offset >= 32) + { + offset -= 32; + } + + // 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)arr[offset + 0] << 0) + | ((uint)arr[offset + 1] << 8) + | ((uint)arr[offset + 2] << 16) + | ((uint)arr[offset + 3] << 24); + } + else + { + return ((uint)arr[offset + 3] << 0) + | ((uint)arr[offset + 2] << 8) + | ((uint)arr[offset + 1] << 16) + | ((uint)arr[offset + 0] << 24); } } @@ -106,39 +164,42 @@ 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(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.sha256.Hash.CopyTo(this.hash, 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); - this.sha512.Hash.CopyTo(this.hash, 0); } sha512DoneStatus = true; @@ -148,59 +209,59 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous }) ; - Registers.DIGEST01.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(4); }) - ; Registers.DIGEST00.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(0); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(0)) ; - Registers.DIGEST11.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(12); }) + Registers.DIGEST01.Define(this) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(4)) ; Registers.DIGEST10.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(8); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(8)) ; - Registers.DIGEST21.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(20); }) + Registers.DIGEST11.Define(this) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(12)) ; Registers.DIGEST20.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(16); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(16)) ; - Registers.DIGEST31.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(28); }) + Registers.DIGEST21.Define(this) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(20)) ; Registers.DIGEST30.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(24); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(24)) ; - Registers.DIGEST41.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(36); }) + Registers.DIGEST31.Define(this) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(28)) ; Registers.DIGEST40.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(32); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(32)) ; - Registers.DIGEST51.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(44); }) + Registers.DIGEST41.Define(this) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(36)) ; Registers.DIGEST50.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(40); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(40)) ; - Registers.DIGEST61.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(52); }) + Registers.DIGEST51.Define(this) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(44)) ; Registers.DIGEST60.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(48); }) + .WithValueField(0, 32, valueProviderCallback: _ => ResultAtOffset(48)) ; - Registers.DIGEST71.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return ResultAtOffset(60); }) + Registers.DIGEST61.Define(this) + .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: _ => 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) @@ -222,21 +283,21 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous ; Registers.FIFO.Define(this) - .WithValueField(0, 32, valueProviderCallback: _ => { return 0; }) + .WithValueField(0, 32, valueProviderCallback: _ => 0) ; } private void UpdateInterrupts() { - if (this.errValidStatus && this.errValidEnabled.Value) + if (this.errValidStatus) { this.errValidPending.Value = true; } - if (this.fifoFullStatus && this.fifoFullEnabled.Value) + if (this.fifoFullStatus) { this.fifoFullPending.Value = true; } - if (this.sha512DoneStatus && this.sha512DoneEnabled.Value) + if (this.sha512DoneStatus) { this.sha512DonePending.Value = true; } @@ -260,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; @@ -290,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 { @@ -322,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(); + } + + } +} diff --git a/emulation/peripherals/trng_kernel.cs b/emulation/peripherals/trng_kernel.cs index 28abc4d2b..348a467b8 100644 --- a/emulation/peripherals/trng_kernel.cs +++ b/emulation/peripherals/trng_kernel.cs @@ -23,10 +23,9 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous private void DefineRegisters() { Registers.STATUS.Define(this) // RDY is set on reset - .WithValueField(0, 32, FieldMode.Read, valueProviderCallback: _ => - { - return 3; - }, name: "STATUS"); + .WithFlag(0, name: "ready", valueProviderCallback: _ => true) + .WithFlag(1, name: "avail", valueProviderCallback: _ => true) + ; Registers.DATA.Define(this) .WithValueField(0, 32, FieldMode.Read, valueProviderCallback: _ => @@ -40,7 +39,7 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous return (uint)rng.Next(); }, name: "URANDOM"); Registers.URANDOM_VALID.Define(this) - .WithFlag(0, FieldMode.Read, valueProviderCallback: _ => { return true; }, name: "URANDOM_VALID"); + .WithFlag(0, FieldMode.Read, valueProviderCallback: _ => true, name: "URANDOM_VALID"); } private readonly PseudorandomNumberGenerator rng = EmulationManager.Instance.CurrentEmulation.RandomGenerator; diff --git a/emulation/peripherals/trng_server.cs b/emulation/peripherals/trng_server.cs index 459d6bebd..decda0eb1 100644 --- a/emulation/peripherals/trng_server.cs +++ b/emulation/peripherals/trng_server.cs @@ -53,12 +53,12 @@ namespace Antmicro.Renode.Peripherals.Miscellaneous AV_CONFIG = 0xc, RO_CONFIG = 0x10, - READY = 0xd8, - EV_STATUS = 0xdc, - EV_PENDING = 0xe0, - EV_ENABLE = 0xe4, - URANDOM = 0xf0, - URANDOM_VALID = 0xf4, + READY = 0xc4, + EV_STATUS = 0xc8, + EV_PENDING = 0xcc, + EV_ENABLE = 0xd0, + URANDOM = 0xdc, + URANDOM_VALID = 0xe0, TEST = 0xf8, } } 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 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 """ diff --git a/svd2repl/src/generate.rs b/svd2repl/src/generate.rs index 82923fbaf..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,9 +521,15 @@ fn print_memory_regions(regions: &[MemoryRegion], out: &mut U) -> std: continue; } + // 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)?; @@ -529,23 +541,13 @@ 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 known_peripherals = HashMap::new(); - known_peripherals.insert("console", "UART.LiteX_UART"); - known_peripherals.insert("uart", "UART.LiteX_UART"); - known_peripherals.insert("app_uart", "UART.LiteX_UART"); - known_peripherals.insert("timer0", "Timers.LiteX_Timer_32"); - known_peripherals.insert("i2c", "I2C.BetrustedI2C"); - known_peripherals.insert("keyboard", "Input.BetrustedKbd"); - known_peripherals.insert("memlcd", "Video.BetrustedLCD"); - known_peripherals.insert("sha512", "Miscellaneous.Sha512"); - known_peripherals.insert("trng_kernel", "Miscellaneous.BetrustedRNGKernel"); - known_peripherals.insert("trng_server", "Miscellaneous.BetrustedRNGServer"); - known_peripherals.insert("ticktimer", "Timers.TickTimer"); writeln!(out, "// Platform Peripherals")?; + for peripheral in peripherals { let lc_name = peripheral.name.to_lowercase(); // let peripheral_size = if peripheral.size < 4096 { @@ -553,7 +555,7 @@ fn print_peripherals( // } else { // peripheral.size // }; - if let Some(renode_device) = known_peripherals.get(lc_name.as_str()) { + if let Some(renode_device) = cs_peripherals.get(lc_name.as_str()) { writeln!( out, "{}: {} @ sysbus 0x{:08x}", @@ -574,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. @@ -618,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(()) diff --git a/tools/Cargo.toml b/tools/Cargo.toml index a88707b40..49e3b89e2 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -1,9 +1,9 @@ [package] +authors = ["Sean Cross "] +default-run = "create-image" +edition = "2018" name = "tools" version = "0.1.0" -authors = ["Sean Cross "] -edition = "2018" -default-run = "create-image" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -12,10 +12,12 @@ bitflags = "1.2.1" clap = "2.33" crc = "1.8.1" csv = "1.1" +ring = "0.16.20" env_logger = "0.7" log = "0.4" +pem = "0.8" +svd2utra = {path = "../svd2utra"} xmas-elf = "0.7.0" -svd2utra = { path = "../svd2utra" } [[bin]] name = "copy-object" @@ -28,3 +30,6 @@ name = "make-tags" [[bin]] name = "read-tags" + +[[bin]] +name = "sign-image" diff --git a/tools/src/bin/sign-image.rs b/tools/src/bin/sign-image.rs new file mode 100644 index 000000000..a20dd5407 --- /dev/null +++ b/tools/src/bin/sign-image.rs @@ -0,0 +1,176 @@ +use clap::{crate_version, App, Arg}; +use std::io::{Read, Write}; +use std::path::Path; + +use ring::signature::Ed25519KeyPair; + +const DEVKEY_PATH: &str = "devkey/dev.key"; +const LOADER_VERSION: u32 = 1; + +fn image_sign( + input: &S, + output: &T, + private_key: &pem::Pem, + defile: bool, +) -> Result<(), Box> +where + S: AsRef, + T: AsRef, +{ + let mut source = vec![]; + let mut source_file = std::fs::File::open(input)?; + let mut dest_file = std::fs::File::create(output)?; + source_file.read_to_end(&mut source)?; + for b in LOADER_VERSION.to_le_bytes() { + source.push(b); + } + for b in (source.len() as u32).to_le_bytes() { + source.push(b); + } + + // NOTE NOTE NOTE + // can't find a good ASN.1 ED25519 key decoder, just relying on the fact that the last + // 32 bytes are "always" the private key. always? the private key? + let signing_key = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&private_key.contents) + .map_err(|e| format!("{}", e))?; + let signature = signing_key.sign(&source); + + dest_file.write_all(&LOADER_VERSION.to_le_bytes())?; + dest_file.write_all(&(source.len() as u32).to_le_bytes())?; + + // Write the signature data + let signature_u8 = &signature.as_ref(); + dest_file.write_all(signature_u8)?; + + // Pad the first sector to 4096 bytes. + let mut v = vec![]; + v.resize(4096 - 4 - 4 - signature_u8.len(), 0); + dest_file.write_all(&v)?; + + // Fill the remainder of the source data + + if defile { + println!("WARNING: defiling the loader image. This corrupts the binary and should cause it to fail the signature check."); + source[16778] ^= 0x1 // flip one bit at some random offset + } + + dest_file.write_all(&source)?; + + Ok(()) +} + +fn load_pem(src: &str) -> Result> { + let mut input = vec![]; + let mut pemfile = std::fs::File::open(src)?; + pemfile.read_to_end(&mut input)?; + + Ok(pem::parse(input)?) +} + +fn main() -> Result<(), Box> { + let matches = App::new("sign-image") + .version(crate_version!()) + .author("Sean Cross ") + .about("Sign binary images for Precursor") + .arg( + Arg::with_name("loader-image") + .long("loader-image") + .help("loader image") + .value_name("loader image") + .takes_value(true) + .required(true) + .default_value("target/riscv32imac-unknown-none-elf/release/loader_presign.bin"), + ) + .arg( + Arg::with_name("kernel-image") + .long("kernel-image") + .help("kernel image") + .value_name("kernel image") + .takes_value(true) + .default_value("target/riscv32imac-unknown-none-elf/release/xous_presign.img") + .required(true), + ) + .arg( + Arg::with_name("loader-key") + .long("loader-key") + .help("loader signing key") + .takes_value(true) + .value_name("loader signing key") + .default_value(DEVKEY_PATH), + ) + .arg( + Arg::with_name("kernel-key") + .long("kernel-key") + .takes_value(true) + .required(true) + .help("kernel signing key") + .value_name("kernel signing key") + .default_value(DEVKEY_PATH), + ) + .arg( + Arg::with_name("loader-output") + .long("loader-output") + .takes_value(true) + .value_name("loader output image") + .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( + "patch the resulting image, to create a test file to catch signature failure", + ), + ) + .get_matches(); + + // 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 loader private key type")?; + } + println!("Signing loader"); + image_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(()) +} diff --git a/xous-rs/bin/riscv32i-unknown-none-elf.a b/xous-rs/bin/riscv32i-unknown-none-elf.a index 4eb32a794..504112be5 100644 Binary files a/xous-rs/bin/riscv32i-unknown-none-elf.a and b/xous-rs/bin/riscv32i-unknown-none-elf.a differ diff --git a/xous-rs/bin/riscv32imac-unknown-none-elf.a b/xous-rs/bin/riscv32imac-unknown-none-elf.a index 44d65f411..2b1c8c573 100644 Binary files a/xous-rs/bin/riscv32imac-unknown-none-elf.a and b/xous-rs/bin/riscv32imac-unknown-none-elf.a differ diff --git a/xous-rs/bin/riscv32imc-unknown-none-elf.a b/xous-rs/bin/riscv32imc-unknown-none-elf.a index 44d65f411..2b1c8c573 100644 Binary files a/xous-rs/bin/riscv32imc-unknown-none-elf.a and b/xous-rs/bin/riscv32imc-unknown-none-elf.a differ diff --git a/xous-rs/bin/riscv64gc-unknown-none-elf.a b/xous-rs/bin/riscv64gc-unknown-none-elf.a index e9d7fb9f3..8b8a03a7d 100644 Binary files a/xous-rs/bin/riscv64gc-unknown-none-elf.a and b/xous-rs/bin/riscv64gc-unknown-none-elf.a differ diff --git a/xous-rs/bin/riscv64imac-unknown-none-elf.a b/xous-rs/bin/riscv64imac-unknown-none-elf.a index e9d7fb9f3..8b8a03a7d 100644 Binary files a/xous-rs/bin/riscv64imac-unknown-none-elf.a and b/xous-rs/bin/riscv64imac-unknown-none-elf.a differ diff --git a/xous-rs/src/arch/native.rs b/xous-rs/src/arch/native.rs index 3dc1f1d1c..d97ee8971 100644 --- a/xous-rs/src/arch/native.rs +++ b/xous-rs/src/arch/native.rs @@ -379,3 +379,11 @@ pub fn wait_process(_joiner: ProcessHandle) -> crate::SysCallResult { crate::wait_event(); } } + +extern "C" { + fn riscv_cache_flush(); +} + +pub fn cache_flush() { + unsafe { riscv_cache_flush() }; +} diff --git a/xous-rs/src/asm.S b/xous-rs/src/asm.S index 75e434c87..1114e244c 100644 --- a/xous-rs/src/asm.S +++ b/xous-rs/src/asm.S @@ -98,3 +98,8 @@ vex_aes_dec_id_last_2: vex_aes_dec_id_last_3: .word 0x36b5050b // vex_aes_dec_id_last a0, a1, a0, #3 ret + +.global riscv_cache_flush +riscv_cache_flush: + fence + ret diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 536a5768e..bba80c7a9 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,5 +1,4 @@ use std::{ - convert::TryInto, env, io::{Read, Write}, path::{Path, PathBuf, MAIN_SEPARATOR}, @@ -75,8 +74,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 +113,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 +276,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 +329,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 +366,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 +407,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 +424,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"], + build_hw_image( debug, - Some(TARGET), - Some("loader".into()), + 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> {