Example #1
0
        public void Execute(string[] args)
        {
            try
            {
                string fmtString = args[1];

                if (fmtString.Contains("\""))
                {
                    fmtString = fmtString.Replace("\"", string.Empty);
                }

                fmtString = fmtString.Trim();

                if (IntExtensions.TryParseEx(args[0], out int iValue))
                {
                    int readData = m_Proc.ReadMemory(iValue);
                    m_Terminal.PrintString("\t" + args[0] + " = " + readData.ToString(fmtString) + '\n');
                }
                else
                {
                    m_Terminal.PrintString(args[0] + " was not a valid 32 bit integer.\n");
                }
            }
            catch (Exception ex)
            {
                m_Terminal.PrintString(ex.Message + '\n');
            }
        }
        /// <summary>
        /// Parses an instruction and generates the binary code for it.
        /// </summary>
        /// <param name="address">The address of the instruction being parsed in the .text segment.</param>
        /// <param name="args">An array containing the arguments of the instruction.</param>
        /// <returns>One or more 32-bit integers representing this instruction. If this interface is implemented
        /// for a pseudo-instruction, this may return more than one instruction value.</returns>
        public override IEnumerable <int> GenerateCodeForInstruction(int address, string[] args)
        {
            // we expect two arguments. if not, throw an ArgumentException
            if (args.Length != 2)
            {
                throw new ArgumentException("Invalid number of arguments provided. Expected 2, received " + args.Length + '.');
            }

            string rs1          = args[0].Trim();
            string immediateStr = args[1].Trim();

            int immediate = 0;

            if (!IntExtensions.TryParseEx(immediateStr, out immediate))
            {
                throw new ArgumentException("auipc - argument 2 was non-integer immediate value.");
            }

            int rs1Reg = RegisterMap.GetNumericRegisterValue(rs1);

            // shift this such that
            int bitShiftedImm = immediate << 12;

            int instruction = 0;

            instruction |= bitShiftedImm;
            instruction |= (rs1Reg << 7);
            instruction |= 0x17;
            var inList = new List <int>();

            inList.Add(instruction);
            return(inList);
        }
Example #3
0
        public static byte[] FrameData(byte[] payload, FrameType frameType)
        {
            var  memoryStream = new MemoryStream();
            byte op           = (byte)((byte)frameType + 128);

            memoryStream.WriteByte(op);

            if (payload.Length > UInt16.MaxValue)
            {
                memoryStream.WriteByte(127);
                var lengthBytes = IntExtensions.ToBigEndianBytes <ulong>(payload.Length);
                memoryStream.Write(lengthBytes, 0, lengthBytes.Length);
            }
            else if (payload.Length > 125)
            {
                memoryStream.WriteByte(126);
                var lengthBytes = IntExtensions.ToBigEndianBytes <ushort>(payload.Length);
                memoryStream.Write(lengthBytes, 0, lengthBytes.Length);
            }
            else
            {
                memoryStream.WriteByte((byte)payload.Length);
            }

            memoryStream.Write(payload, 0, payload.Length);

            return(memoryStream.ToArray());
        }
Example #4
0
            /// <summary>
            /// Takes an argument (e.g. 4(x9)) and parameterizes it into the offset component
            /// and its numeric register ID.
            /// </summary>
            /// <param name="trimmedArgToken">The token to parameterize, with whitespace trimmed on both left/right sides.</param>
            /// <returns>A parameterized register/offset structure.</returns>
            public static ParameterizedInstructionArg ParameterizeArgument(string trimmedArgToken)
            {
                string[] parameterizedArgs = trimmedArgToken.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries).Apply((str) => str.Trim()).ToArray();

                // we should expect one or two arguments.
                if (parameterizedArgs.Length != 1 && parameterizedArgs.Length != 2)
                {
                    throw new ArgumentException(trimmedArgToken + " was not in a valid format.");
                }

                ParameterizedInstructionArg retVal = default(ParameterizedInstructionArg);

                // if we have one argument, assume its the register name, and that the offset is 0.
                if (parameterizedArgs.Length == 1)
                {
                    int registerId = RegisterMap.GetNumericRegisterValue(parameterizedArgs[0]);
                    retVal = new ParameterizedInstructionArg(0, registerId);
                }
                else
                {
                    bool isValidOffset = IntExtensions.TryParseEx(parameterizedArgs[0], out short offsetVal) && ((offsetVal & 0xF000) == 0);
                    if (!isValidOffset)
                    {
                        throw new ArgumentException(parameterizedArgs[0] + " is not a valid 12-bit offset.");
                    }

                    int registerId = RegisterMap.GetNumericRegisterValue(parameterizedArgs[1]);
                    retVal = new ParameterizedInstructionArg(offsetVal, registerId);
                }

                return(retVal);
            }
Example #5
0
        private void SwapIndex(int indexFrom, int indexTo)
        {
            if (indexFrom == indexTo)
            {
                return;
            }

            if (indexFrom < 0)
            {
                indexFrom = 0;
            }

            if (indexTo < 0)
            {
                indexTo = 0;
            }

            if (indexFrom > indexTo)
            {
                IntExtensions.Swap(ref indexFrom, ref indexTo);
            }

            var itemA = _points[indexFrom];
            var itemB = _points[indexTo];

            // note: these are mutable, so if we store the values in local scope
            var posA = itemA.Position.Top + itemB.Position.Height;
            var posB = itemA.Position.Top;

            itemA.Reposition(new Point(0, posA));
            itemB.Reposition(new Point(0, posB));

            _points[indexFrom] = itemB;
            _points[indexTo]   = itemA;
        }
Example #6
0
        public void ToReturnsEnumerable()
        {
            var expected = new[] { 2, 3, 4, 5 };
            var range    = IntExtensions.To(2, 5).ToArray();

            CollectionAssert.AreEqual(expected, range);
        }
Example #7
0
        public static SimpleList <TResult> SimpleOfType <TSource, TResult>(this IList <TSource> source)
        {
            if (source == null)
            {
                throw new InvalidOperationException("Invalid null object");
            }
            var sourceCount = source.Count;

            var result = new TResult[8];
            var length = 8;
            var count  = 0;
            int log    = IntExtensions.Log2((uint)sourceCount) - 3;

            log = log > 2 ? (log - (log % 2)) : 2;

            for (int i = 0; i < sourceCount; i++)
            {
                if (!(source[i] is TResult retyped))
                {
                    continue;
                }
                if (count >= length)
                {
                    EnlargeExtensions.LogEnlargeArray(2, sourceCount, ref result, ref log, out length);
                }
                result[count] = retyped;
                count++;
            }
            var final = new SimpleList <TResult>();

            final.Items = result;
            final.Count = count;
            return(final);
        }
 public void Execute(string[] args)
 {
     try
     {
         if (IntExtensions.TryParseEx(args[0], out int address))
         {
             if (IntExtensions.TryParseEx(args[1], out int value))
             {
                 m_Proc.WriteMemory(address, value);
                 m_Terminal.PrintString("\t" + args[0] + " = " + args[1] + '\n');
             }
             else if (FloatExtensions.TryParseEx(args[1], out float fVal))
             {
                 m_Proc.WriteFloatToMemory(address, fVal);
                 m_Terminal.PrintString("\t" + args[0] + " = " + args[1] + '\n');
             }
             else
             {
                 m_Terminal.PrintString(args[1] + " was not a valid 32 bit value.\n");
             }
         }
         else
         {
             m_Terminal.PrintString(args[0] + " was not a valid 32 bit integer.\n");
         }
     }
     catch (Exception ex)
     {
         m_Terminal.PrintString(ex.Message + '\n');
     }
 }
Example #9
0
        public static SimpleList <T> SimpleTakeWhile <T>(this T[] source, Func <T, bool> predicate)
        {
            if (source == null)
            {
                throw new InvalidOperationException("Invalid null object");
            }

            var result = new T[8];
            var length = 8;
            var count  = 0;
            int log    = IntExtensions.Log2((uint)source.Length) - 3;

            log = log > 2 ? (log - (log % 2)) : 2;

            for (int i = 0; i < source.Length; i++)
            {
                if (!predicate(source[i]))
                {
                    break;
                }
                if (count >= length)
                {
                    EnlargeExtensions.LogEnlargeArray(2, source.Length, ref result, ref log, out length);
                }
                result[count] = source[i];
                count++;
            }
            var final = new SimpleList <T>();

            final.Items = result;
            final.Count = count;
            return(final);
        }
Example #10
0
        public static void ProcessFrame(FrameType frameType, byte[] data, Action <string> onMessage, Action onClose, Action <byte[]> onBinary, Action <byte[]> onPing, Action <byte[]> onPong)
        {
            switch (frameType)
            {
            case FrameType.Close:
                if (data.Length == 1 || data.Length > 125)
                {
                    throw new WebSocketException(WebSocketStatusCodes.ProtocolError);
                }

                if (data.Length >= 2)
                {
                    //var closeCode = (ushort)data.Take(2).ToArray().ToLittleEndianInt();
                    byte[] _codeAry = new byte[] {
                        data[0],
                        data[1]
                    };
                    var closeCode = (ushort)IntExtensions.ToLittleEndianInt(_codeAry);

                    if (                            //!WebSocketStatusCodes.ValidCloseCodes.Contains(closeCode)
                        -1 == Array.IndexOf(WebSocketStatusCodes.ValidCloseCodes, closeCode) &&
                        (closeCode < 3000 || closeCode > 4999))
                    {
                        throw new WebSocketException(WebSocketStatusCodes.ProtocolError);
                    }
                }
                if (data.Length > 2)
                {
                    //ReadUTF8PayloadData(data.Skip(2).ToArray());
                    var _dataAry = LinqExtensions.SkipTakeToArray(data, 2);
                    ReadUTF8PayloadData(_dataAry);
                }

                onClose();
                break;

            case FrameType.Binary:
                onBinary(data);
                break;

            case FrameType.Ping:
                onPing(data);
                break;

            case FrameType.Pong:
                onPong(data);
                break;

            case FrameType.Text:
                onMessage(ReadUTF8PayloadData(data));
                break;

            default:
                FleckLog.Debug("Received unhandled " + frameType);
                break;
            }
        }
Example #11
0
        public void TimesRepeatsActionWithIndex()
        {
            var expected = new[] { 0, 1, 2, 3, 4 };
            var times    = 5;
            var items    = new List <int>();

            IntExtensions.Times(times, items.Add);

            Assert.AreEqual(times, items.Count);
            CollectionAssert.AreEqual(expected, items);
        }
        /// <summary>
        /// Adds a half element to the object file.
        /// </summary>
        /// <param name="objFile">The object file to add to.</param>
        /// <param name="fullText">The full text of the assembly line.</param>
        /// <param name="declarationToken">The token specifying the declaration of the size parameter.</param>
        private void AddShortElementToFile(BasicObjectFile objFile, string fullText, string declarationToken)
        {
            // find the token directly after the size directive
            int    substrBeginIdx = fullText.IndexOf(declarationToken) + declarationToken.Length;
            string arguments      = fullText.Substring(substrBeginIdx);

            // split by commas.
            string[] tokenizedArgs = arguments.Split(new[] { ',' });
            tokenizedArgs = tokenizedArgs.Apply((str) => str.Trim()).ToArray();

            // iterate through each element in the "array".
            foreach (string token in tokenizedArgs)
            {
                // if it contains a ':' character, then this itself is an array of the initialized token.
                if (token.Contains(':'))
                {
                    string[] subtokens = token.Split(new[] { ':' }).Apply((str) => str.Trim()).ToArray();
                    if (subtokens.Length == 2)
                    {
                        int numElems = int.Parse(subtokens[1]);

                        // this syntax is wonky; we're trying to parse literal char elements
                        // as well as normal bytes here.
                        if (!IntExtensions.TryParseEx(subtokens[0], out short elemToAdd))
                        {
                            // see if we can resolve the string as a symbol.
                            Symbol sym = m_SymTbl.GetSymbol(subtokens[0]);
                            elemToAdd = (short)sym.Address;
                        }
                        for (int i = 0; i < numElems; ++i)
                        {
                            objFile.AddDataElement(elemToAdd);
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Expected size parameter after ':' token.");
                    }
                }
                else
                {
                    // otherwise, it should just be an element (without any size modifiers).
                    // just parse it and add it.
                    if (!IntExtensions.TryParseEx(token, out short elemToAdd))
                    {
                        // see if we can resolve the string as a symbol.
                        Symbol sym = m_SymTbl.GetSymbol(token);
                        elemToAdd = (short)sym.Address;
                    }

                    objFile.AddDataElement(elemToAdd);
                }
            }
        }
        public void ToAndFromHexTest()
        {
            for (int i = -100000; i <= 1000000; i += 37)
            {
                var hex = i.ToHex();
                var i2  = IntExtensions.FromHex(hex);
                Assert.AreEqual(i, i2, hex);
            }

            Assert.AreEqual(int.MinValue, IntExtensions.FromHex(int.MinValue.ToHex()));
            Assert.AreEqual(int.MaxValue, IntExtensions.FromHex(int.MaxValue.ToHex()));
        }
Example #14
0
        public void TimesRepeatsAction()
        {
            var times   = 5;
            var counter = 0;

            IntExtensions.Times(times, () =>
            {
                counter++;
            });

            Assert.AreEqual(times, counter);
        }
        public bool ValidateUsername(string username)
        {
            if (!IntExtensions.IsBetween(username.Length, 1, 40))
            {
                return(false);
            }

            if (!Regex.IsMatch(username, @"^[a-zA-Z0-9\s]"))
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Parses an instruction and generates the binary code for it.
        /// </summary>
        /// <param name="address">The address of the instruction being parsed in the .text segment.</param>
        /// <param name="args">An array containing the arguments of the instruction.</param>
        /// <returns>One or more 32-bit integers representing this instruction. If this interface is implemented
        /// for a pseudo-instruction, this may return more than one instruction value.</returns>
        public override IEnumerable <int> GenerateCodeForInstruction(int address, string[] args)
        {
            // we expect three arguments. if not, throw an ArgumentException
            if (args.Length != 3)
            {
                throw new ArgumentException("Invalid number of arguments provided. Expected 3, received " + args.Length + '.');
            }

            string rd  = args[0].Trim();
            string rs1 = args[1].Trim();
            string rs2 = args[2].Trim();

            IEnumerable <int> returnVal = null;
            int instruction             = 0;
            int rdReg  = RegisterMap.GetNumericRegisterValue(rd);
            int rs1Reg = RegisterMap.GetNumericRegisterValue(rs1);
            int rs2Reg = 0;

            try
            {
                rs2Reg = RegisterMap.GetNumericRegisterValue(rs2);

                List <int> instructionList = new List <int>();
                instruction |= (rs2Reg << 20);
                instruction |= (rs1Reg << 15);
                instruction |= (0x7 << 12);
                instruction |= (rdReg << 7);
                instruction |= 0x33;
                instructionList.Add(instruction);
                returnVal = instructionList;
            }
            catch (ArgumentException)
            {
                // try to parse the string as a number; maybe the user meant andi?
                short immediate = 0;
                bool  isShort   = IntExtensions.TryParseEx(rs2, out immediate);
                if (isShort)
                {
                    var immediateParser = new AndiProcessor();
                    returnVal = immediateParser.GenerateCodeForInstruction(address, args);
                }
                else
                {
                    // otherwise, this is garbage; rethrow the value.
                    throw;
                }
            }

            return(returnVal);
        }
Example #17
0
        public static IHandler Create(WebSocketHttpRequest request, Action <string> onMessage, Action onClose, Action <byte[]> onBinary, Action <byte[]> onPing, Action <byte[]> onPong)
        {
            var readState = new ReadState();

            return(new ComposableHandler
            {
                Handshake = sub => Hybi13Handler.BuildHandshake(request, sub),
                TextFrame = s => Hybi13Handler.FrameData(Encoding.UTF8.GetBytes(s), FrameType.Text),
                BinaryFrame = s => Hybi13Handler.FrameData(s, FrameType.Binary),
                PingFrame = s => Hybi13Handler.FrameData(s, FrameType.Ping),
                PongFrame = s => Hybi13Handler.FrameData(s, FrameType.Pong),
                CloseFrame = i => Hybi13Handler.FrameData(IntExtensions.ToBigEndianBytes <ushort>(i), FrameType.Close),
                ReceiveData = d => Hybi13Handler.ReceiveData(d, readState, (op, data) => Hybi13Handler.ProcessFrame(op, data, onMessage, onClose, onBinary, onPing, onPong))
            });
        }
Example #18
0
        public void TestMax()
        {
            var first    = this.GetInput();
            var second   = this.GetInput();
            var expected = new int[first.Length];

            for (int i = 0; i < first.Length; i++)
            {
                expected[i] = first[i] > second[i] ? first[i] : second[i];
            }

            var result = IntExtensions.Max(first, second);

            Assert.Equal(expected, result);
        }
Example #19
0
        public PasswordLengthAttribute(string passwordRequiredPropertyName, string encryptedPasswordPropertyName, string saltPropertyName, int minLength = 0, int maxLength = 255) : base("Error PasswordLengthAttribute")
        {
            _passwordRequiredPropertyName  = passwordRequiredPropertyName;
            _encryptedPasswordPropertyName = encryptedPasswordPropertyName;
            _saltPropertyName = saltPropertyName;

            //If for some reason someone entered a minimum length smaller than the max length, swap the 2 values
            if (minLength > maxLength)
            {
                IntExtensions.SwapTwoIntegers(minLength, maxLength, out minLength, out maxLength);
            }

            _minimumLength = minLength;
            _maximumLength = maxLength;
        }
Example #20
0
    void CheckID(int id)
    {
        if (id >= items.Length)
        {
            var prevSize = items.Length;
            var newSize  = IntExtensions.GetPowerOfTwoSize(id + 1);

            Array.Resize(ref items, newSize);
            Array.Resize(ref hasItem, newSize);

            for (int i = prevSize; i < newSize; i++)
            {
                CreateNewItemAtIndex(i);
            }
        }
    }
Example #21
0
        /// <summary>
        /// Parses an instruction and generates the binary code for it.
        /// </summary>
        /// <param name="address">The address of the instruction being parsed in the .text segment.</param>
        /// <param name="args">An array containing the arguments of the instruction.</param>
        /// <returns>One or more 32-bit integers representing this instruction. If this interface is implemented
        /// for a pseudo-instruction, this may return more than one instruction value.</returns>
        public override IEnumerable <int> GenerateCodeForInstruction(int address, string[] args)
        {
            // we expect three arguments. if not, throw an ArgumentException
            if (args.Length != 3)
            {
                throw new ArgumentException("Invalid number of arguments provided. Expected 3, received " + args.Length + '.');
            }

            IEnumerable <int> returnVal = null;
            int  rdReg            = RegisterMap.GetNumericRegisterValue(args[0]);
            int  rs1Reg           = RegisterMap.GetNumericRegisterValue(args[1]);
            int  shiftAmt         = 0;
            bool isValidImmediate = IntExtensions.TryParseEx(args[2], out shiftAmt);

            // ensure our shift amount is 5 bits or less.
            isValidImmediate = isValidImmediate && ((shiftAmt & 0xFFFFFFE0) == 0);
            var instructionList = new List <int>();

            if (isValidImmediate)
            {
                int instruction = 0;
                instruction |= (0x1 << 30);
                instruction |= (shiftAmt << 20);
                instruction |= (rs1Reg << 15);
                instruction |= (0x5 << 12);
                instruction |= (rdReg << 7);
                instruction |= 0x13;
                instructionList.Add(instruction);
                returnVal = instructionList;
            }
            else
            {
                // otherwise, emit three instructions. load the upper 20 bits of the immediate into the destination register,
                // bitwise-or it with the remaining 12 bits, and then shift the target register by the destination register.
                var luiProc = new LuiProcessor();
                instructionList.AddRange(luiProc.GenerateCodeForInstruction(address, new string[] { args[0], (shiftAmt >> 12).ToString() }));

                int orImmVal = shiftAmt & 0xFFF;
                var oriProc  = new OriProcessor();
                instructionList.AddRange(oriProc.GenerateCodeForInstruction(address, new string[] { args[0], orImmVal.ToString() }));

                var sraProc = new SraProcessor();
                instructionList.AddRange(sraProc.GenerateCodeForInstruction(address, new string[] { args[0], args[1], args[0] }));
            }

            return(returnVal);
        }
Example #22
0
        /// <summary>
        /// Parses an instruction and generates the binary code for it.
        /// </summary>
        /// <param name="address">The address of the instruction being parsed in the .text segment.</param>
        /// <param name="args">An array containing the arguments of the instruction.</param>
        /// <returns>One or more 32-bit integers representing this instruction. If this interface is implemented
        /// for a pseudo-instruction, this may return more than one instruction value.</returns>
        public override IEnumerable <int> GenerateCodeForInstruction(int address, string[] args)
        {
            if (args.Length != 3)
            {
                throw new ArgumentException("Invalid number of arguments provided. Expected 3, received " + args.Length + '.');
            }

            IEnumerable <int> returnVal = null;
            int instruction             = 0;
            int rdReg  = RegisterMap.GetNumericRegisterValue(args[0]);
            int rs1Reg = RegisterMap.GetNumericRegisterValue(args[1]);
            int rs2Reg = 0;

            try
            {
                rs2Reg = RegisterMap.GetNumericRegisterValue(args[2]);

                List <int> instructionList = new List <int>();
                instruction |= (rs2Reg << 20);
                instruction |= (rs1Reg << 15);

                // or opcode/funt3/funct7 = 0x33/0x6/0x0
                instruction |= (0x6 << 12);
                instruction |= (rdReg << 7);
                instruction |= 0x33;
                instructionList.Add(instruction);
                returnVal = instructionList;
            }
            catch (ArgumentException)
            {
                // try parsing as ori instruction
                int  immediate = 0;
                bool isShort   = IntExtensions.TryParseEx(args[2], out immediate);
                if (isShort)
                {
                    var immediateParser = new OriProcessor();
                    returnVal = immediateParser.GenerateCodeForInstruction(address, args);
                }
                else
                {
                    throw;
                }
            }

            return(returnVal);
        }
Example #23
0
        public void TestMultiplySimd()
        {
            var first    = this.GetInput();
            var second   = this.GetInput();
            var expected = new int[first.Length];

            for (int i = 0; i < first.Length; i++)
            {
                expected[i] = first[i] * second[i];
            }

            var result = new int[first.Length];

            IntExtensions.MultiplySimd(first, second, result);

            Assert.Equal(expected, result);
        }
        public void Execute(string[] args)
        {
            if (!IntExtensions.TryParseEx(args[0], out int pgmCounter))
            {
                // if the argument was not a program counter arg, try to find the source line.
                string srcData = args[0];

                string[] splitData = srcData.Split(':');
                if (splitData.Length == 2)
                {
                    for (int i = 0; i < 2; ++i)
                    {
                        splitData[i] = splitData[i].Trim();
                    }

                    int srcLineNum = int.Parse(splitData[1]);

                    bool found = false;
                    foreach (var srcLine in m_SrcData.Values)
                    {
                        if (srcLine.SourceFilePath == splitData[0] && srcLine.SourceLineNumber == srcLineNum)
                        {
                            pgmCounter = srcLine.ProgramCounterLocation;
                            found      = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        m_Terminal.PrintString("Could not attach breakpoint to line " + srcLineNum + " of file " + splitData[0] + '\n');
                    }
                }
            }

            if (m_SrcData.ContainsKey(pgmCounter))
            {
                m_Exec.SetBreakpoint(pgmCounter);
                m_Terminal.PrintString("Successfully attached breakpoint to source address 0x" + pgmCounter.ToString("x8") + '\n');
            }
            else
            {
                m_Terminal.PrintString("Could not attach breakpoint to given source address.\n");
            }
        }
Example #25
0
            private void EnforceMinUpdateInterval()
            {
                if (!(this.MinUpdateInterval != TimeSpan.Zero))
                {
                    return;
                }
                TimeSpan timeSpan = DateTime.Now - LastCommand;

                if (timeSpan < this.MinUpdateInterval)
                {
                    int millisecondsTimeout = IntExtensions.Limit((int)(this.MinUpdateInterval - timeSpan).TotalMilliseconds, 0, 1000);
                    if (millisecondsTimeout > 0)
                    {
                        Thread.Sleep(millisecondsTimeout);
                    }
                }
                LastCommand = DateTime.Now;
            }
 public void Execute(string[] args)
 {
     try
     {
         if (IntExtensions.TryParseEx(args[0], out int iValue))
         {
             int readData = m_Proc.ReadMemory(iValue);
             m_Terminal.PrintString("\t" + args[0] + " = " + readData + '\n');
         }
         else
         {
             m_Terminal.PrintString(args[0] + " was not a valid 32 bit integer.\n");
         }
     }
     catch (Exception ex)
     {
         m_Terminal.PrintString(ex.Message + '\n');
     }
 }
Example #27
0
        /// <summary>
        /// Parses an instruction and generates the binary code for it.
        /// </summary>
        /// <param name="address">The address of the instruction being parsed in the .text segment.</param>
        /// <param name="args">An array containing the arguments of the instruction.</param>
        /// <returns>One or more 32-bit integers representing this instruction. If this interface is implemented
        /// for a pseudo-instruction, this may return more than one instruction value.</returns>
        public override IEnumerable <int> GenerateCodeForInstruction(int address, string[] args)
        {
            // we expect three arguments. if not, throw an ArgumentException
            if (args.Length != 3)
            {
                throw new ArgumentException("Invalid number of arguments provided. Expected 3, received " + args.Length + '.');
            }


            int rdReg  = RegisterMap.GetNumericRegisterValue(args[0]);
            int rs1Reg = RegisterMap.GetNumericRegisterValue(args[1]);

            uint immVal           = 0;
            bool isValidImmediate = IntExtensions.TryParseEx(args[2], out immVal);

            // this is okay, as we expect an unsigned value.
            isValidImmediate = isValidImmediate && ((immVal & 0xFFFFF000) == 0);

            var instructionList = new List <int>();

            if (isValidImmediate)
            {
                int instruction = GenerateUnexpandedInstruction(immVal, rs1Reg, rdReg);
                instructionList.Add(instruction);
            }
            else
            {
                // otherwise, emit three instructions. load the upper 20 bits of the immediate into the destination register,
                // bitwise-or it with the remaining 12 bits, and then use sltu (the s-type).
                var luiProc = new LuiProcessor();
                instructionList.AddRange(luiProc.GenerateCodeForInstruction(address, new string[] { args[0], (immVal >> 12).ToString() }));

                uint orImmVal = immVal & 0xFFF;
                var  oriProc  = new OriProcessor();
                instructionList.AddRange(oriProc.GenerateCodeForInstruction(address, new string[] { args[0], orImmVal.ToString() }));

                var sltuProc = new SltuProcessor();
                instructionList.AddRange(sltuProc.GenerateCodeForInstruction(address, new string[] { args[0], args[1], args[0] }));
            }

            return(instructionList);
        }
Example #28
0
 public void Execute(string[] args)
 {
     try
     {
         string regName = args[0];
         if (IntExtensions.TryParseEx(args[1], out int iValue))
         {
             if (RegisterMap.IsNamedIntegerRegister(regName))
             {
                 int regIdx = RegisterMap.GetNumericRegisterValue(regName);
                 m_Registers.UserIntRegisters[regIdx].Value = iValue;
                 m_Terminal.PrintString("\t" + regName + " = " + iValue + '\n');
             }
             else
             {
                 throw new ParseException(regName + " was not a valid register name.");
             }
         }
         else if (FloatExtensions.TryParseEx(args[1], out float fValue))
         {
             if (RegisterMap.IsNamedFloatingPointRegister(regName))
             {
                 int regIdx = RegisterMap.GetNumericFloatingPointRegisterValue(regName);
                 m_Registers.UserFloatingPointRegisters[regIdx].Value = fValue;
                 m_Terminal.PrintString("\t" + regName + " = " + fValue + '\n');
             }
             else
             {
                 throw new ParseException(regName + " was not a valid register name.");
             }
         }
         else
         {
             throw new ParseException(args[1] + " was not a valid 32-bit value");
         }
     }
     catch (Exception ex)
     {
         m_Terminal.PrintString(ex.Message + '\n');
     }
 }
Example #29
0
        /// <summary>
        /// Parses an instruction and generates the binary code for it.
        /// </summary>
        /// <param name="address">The address of the instruction being parsed in the .text segment.</param>
        /// <param name="args">An array containing the arguments of the instruction.</param>
        /// <returns>One or more 32-bit integers representing this instruction. If this interface is implemented
        /// for a pseudo-instruction, this may return more than one instruction value.</returns>
        public override IEnumerable <int> GenerateCodeForInstruction(int address, string[] args)
        {
            // we expect three arguments. if not, throw an ArgumentException
            if (args.Length != 3)
            {
                throw new ArgumentException("Invalid number of arguments provided. Expected 3, received " + args.Length + '.');
            }

            int  rdReg            = RegisterMap.GetNumericRegisterValue(args[0]);
            int  rs1Reg           = RegisterMap.GetNumericRegisterValue(args[1]);
            int  immVal           = 0;
            bool isValidImmediate = IntExtensions.TryParseEx(args[2], out immVal);

            if (isValidImmediate)
            {
                var instructionList = new List <int>();

                // if the immediate is greater than 12 bits, use
                // an auipc instruction.
                if (!IsValidTwelveBitSignedImmediate(immVal))
                {
                    var auipcHelper = new AuipcProcessor();
                    IEnumerable <int> auipcInstructions =
                        auipcHelper.GenerateCodeForInstruction(address, new string[] { args[1], (immVal >> 12).ToString() });
                    instructionList.AddRange(auipcInstructions);
                }

                int instruction = 0;
                instruction |= (immVal << 20);
                instruction |= (rs1Reg << 15);
                instruction |= (rdReg << 7);
                instruction |= 0x67;
                instructionList.Add(instruction);

                return(instructionList);
            }
            else
            {
                throw new ArgumentException("Immediate was not a valid 32-bit integer.");
            }
        }
Example #30
0
        /// <summary>
        /// Parses an instruction and generates the binary code for it.
        /// </summary>
        /// <param name="address">The address of the instruction being parsed in the .text segment.</param>
        /// <param name="args">An array containing the arguments of the instruction.</param>
        /// <returns>One or more 32-bit integers representing this instruction. If this interface is implemented
        /// for a pseudo-instruction, this may return more than one instruction value.</returns>
        public override IEnumerable <int> GenerateCodeForInstruction(int address, string[] args)
        {
            // we expect three arguments. if not, throw an ArgumentException
            if (args.Length != 3)
            {
                throw new ArgumentException("Invalid number of arguments provided. Expected 3, received " + args.Length + '.');
            }

            int rdReg  = RegisterMap.GetNumericRegisterValue(args[0]);
            int rs1Reg = RegisterMap.GetNumericRegisterValue(args[1]);

            int  immVal           = 0;
            bool isValidImmediate = IntExtensions.TryParseEx(args[2], out immVal);

            if (isValidImmediate)
            {
                var instructionList = default(List <int>);

                // if the mask is greater not zero, this would indicate that there are bits beyond the 11th bit offset.
                // help the user by generating equivalent s-type instructions
                if (!IsValidTwelveBitSignedImmediate(immVal))
                {
                    instructionList = GenerateExpandedInstruction(address, immVal, args);
                }
                else
                {
                    instructionList = new List <int>();
                    int instruction = GenerateUnexpandedInstruction(immVal, rs1Reg, rdReg);
                    instructionList.Add(instruction);
                }

                return(instructionList);
            }
            else
            {
                throw new ArgumentException(args[2] + " is not a valid immediate value.");
            }
        }