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", ] 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/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/xtask/src/main.rs b/xtask/src/main.rs index 98a21c7e3..a80f74edc 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> {