Exemplo n.º 1
0
        static private BinaryOp.ArithOp BinaryOpFromCode(InstructionCode code)
        {
            switch (code)
            {
            case InstructionCode.ADD: return(BinaryOp.ArithOp.ADD);

            case InstructionCode.AND: return(BinaryOp.ArithOp.AND);

            case InstructionCode.CEQ: return(BinaryOp.ArithOp.CEQ);

            case InstructionCode.CGT: return(BinaryOp.ArithOp.CGT);

            case InstructionCode.CLT: return(BinaryOp.ArithOp.CLT);

            case InstructionCode.DIV: return(BinaryOp.ArithOp.DIV);

            case InstructionCode.MUL: return(BinaryOp.ArithOp.MUL);

            case InstructionCode.OR:  return(BinaryOp.ArithOp.OR);

            case InstructionCode.REM: return(BinaryOp.ArithOp.REM);

            case InstructionCode.SHL: return(BinaryOp.ArithOp.SHL);

            case InstructionCode.SHR: return(BinaryOp.ArithOp.SHR);

            case InstructionCode.SUB: return(BinaryOp.ArithOp.SUB);

            case InstructionCode.XOR: return(BinaryOp.ArithOp.XOR);
            }
            throw new ConvertionException();
        }
Exemplo n.º 2
0
        private void WriteRCPPayload(BinaryWriter binaryWriter, object[] payload)
        {
            int count = (int)payload[0];

            binaryWriter.Write(count);
            int payloadIndex = 1;

            for (int i = 0; i < count; i++)
            {
                InstructionCode code = (InstructionCode)payload[payloadIndex++];
                binaryWriter.Write((byte)code);
                switch (code)
                {
                case InstructionCode.SPR:
                case InstructionCode.GPR:
                    binaryWriter.Write((int)payload[payloadIndex++]);
                    break;

                case InstructionCode.CSP:
                case InstructionCode.CGP:
                    WriteObject(binaryWriter, payload[payloadIndex++]);
                    break;

                case InstructionCode.DPR:
                case InstructionCode.CDP:
                    WriteObject(binaryWriter, payload[payloadIndex++]);
                    WriteObject(binaryWriter, payload[payloadIndex++]);
                    break;
                }
            }
        }
Exemplo n.º 3
0
        private void Call(InstructionCode instruction, ReadOnlySpan <byte> program)
        {
            GetOpCodeArg(program, out int address);

            if ((uint)address >= (uint)program.Length)
            {
                throw new VmExecutionException($"Invalid method address '0x{address.ToString("X4")}'.");
            }

            _localsState.Save(_locals);
            _locals = new();

            _argsState.Save(_args);
            _args = new();

            for (int idx = 0; idx < program[address]; idx++)
            {
                _args.Add(program[address] - idx - 1, _stackFrame.Pop());
            }

            // TODO (RH vNext): Use method table instead of arg count.

            _stackFrame.AddStack();
            _stackFrame.Push(_pointer);

            _pointer = address + InstructionFacts.SizeOfMethodHeader;
        }
        void IIntrinsicSupport.EmitInstruction(InstructionCode code, Operand operand0, Operand operand1)
        {
            Contract.Requires(operand0 != null);
            Contract.Requires(operand1 != null);

            throw new NotImplementedException();
        }
Exemplo n.º 5
0
        private void Ret(InstructionCode instruction, ReadOnlySpan <byte> program)
        {
            switch (_stackFrame.StackSize)
            {
            case 1:
            {
                var retAddress = (int)_stackFrame.Pop();
                _pointer = retAddress;
                _stackFrame.DropStack();
                break;
            }

            case 2:
            {
                var retValue   = _stackFrame.Pop();
                var retAddress = (int)_stackFrame.Pop();
                _pointer = retAddress;
                _stackFrame.DropStack();
                _stackFrame.Push(retValue);
                break;
            }

            default:
            {
                Throw.InvalidStackSize(new IlAddress(_pointer), _stackFrame.StackSize);
                break;
            }
            }

            _args   = _argsState.Restore();
            _locals = _localsState.Restore();
        }
        void IIntrinsicSupport.EmitJcc(InstructionCode code, Label label, Hint hint)
        {
            Contract.Requires(label != null);
            Contract.Requires(hint == Hint.None || hint == Hint.NotTaken || hint == Hint.Taken);

            throw new NotImplementedException();
        }
        private void DecodeInterruptingDeviceInstruction()
        {
            // The interrupting device inserts an instruction code on the data bus
            InstructionCode candidateInstructionCode = Z80OpCodes.Tables[0, InternalDataBus];            

            // An opcode was recognized, decode it and prepare its execution
            if (candidateInstructionCode.FetchMoreBytes == 0 && candidateInstructionCode.SwitchToTableNumber == null)
            {
                InstructionCode instructionCode = candidateInstructionCode;

                // Register decoded instruction
                instructionOrigin = new InstructionOrigin(InstructionSource.InterruptingDevice, instructionCode, 0);
                currentInstruction = new Instruction(instructionCode.InstructionTypeIndex, instructionCode.InstructionTypeParamVariant);
                DecodeInstructionExecutionMethod();                

                // Correct the actual duration of the current opcode fetch cycle (depends on the instruction)
                currentMachineCycle = currentInstruction.ExecutionTimings.MachineCycles[machineCycleIndex];

                // Decrease the half T state index to execute the decoded instruction as if it was fetched from memory
                halfTStateIndex = 4;
            }
            // We need to read more bytes to recognize a multi-byte opcode
            else
            {
                throw new NotSupportedException("Multi bytes opcodes are not supported in interrupt mode 0 by this simulator");
            }

            if (TraceMicroInstructions)
            {
                TraceMicroInstruction(new MicroInstruction(Z80MicroInstructionTypes.CPUControlDecodeInterruptingDeviceInstruction));
            }
        }
Exemplo n.º 8
0
        private void Add(InstructionCode instruction, ReadOnlySpan <byte> program)
        {
            if (_stackFrame.StackSize == 0)
            {
                Throw.StackUnderflowException(_pointer);
            }

            var op1 = _stackFrame.Pop();

            if (_stackFrame.StackSize == 0)
            {
                Throw.StackUnderflowException(_pointer);
            }

            var op2 = _stackFrame.Pop();

            if (op1 is not int num1)
            {
                Throw.OperationNotSupported(instruction, op1, op2);
                return;
            }

            if (op2 is not int num2)
            {
                Throw.OperationNotSupported(instruction, op1, op2);
                return;
            }

            var result = num1 + num2;

            _stackFrame.Push(result);
        }
        public void InstructionRequiringDataWithInvalidTypeThrows(InstructionCode instructionCode, VmType vmType)
        {
            var instructions = new List <Instruction>();

            switch (vmType)
            {
            case VmType.Integer:
                instructions.Add(new Instruction(instructionCode, 0L));
                break;

            case VmType.Boolean:
                instructions.Add(new Instruction(instructionCode, true));
                break;

            default:
                Assert.True(false);     // error in test;
                break;
            }

            var functionDefinition = new FunctionDefinition(instructions, new List <VmType>(), new List <VmType>()
            {
                VmType.Boolean
            }, 0);
            var exception = Assert.Throws <InvalidSourceException>(() => new VirtualMachine(functionDefinition));

            Assert.Equal(InvalidSourceDetail.InvalidInstructionData, exception.DetailCode);
        }
Exemplo n.º 10
0
        private void BrCondition(InstructionCode instruction, ReadOnlySpan <byte> program, bool expectedCondition)
        {
            GetOpCodeArg(program, out int target);

            if (target >= program.Length)
            {
                Throw.InvalidInstructionArgument(_pointer);
                return;
            }

            var obj    = _stackFrame.Pop();
            var isTrue = obj switch
            {
                bool value => value,
                int value => value != 0,
                decimal value => value != 0,
                string value => value is not null,
                null => false,  // Object reference check
                _ => throw new VmExecutionException($"Instructuin not supports object type '{obj.GetType()}'.")
            };

            if (isTrue == expectedCondition)
            {
                _pointer = target;
            }
        }
Exemplo n.º 11
0
        private object[] ReadRCPPayload(BinaryReader binaryReader)
        {
            List <object> payload = new List <object>();
            int           count   = binaryReader.ReadInt32();

            payload.Add(count);
            for (int i = 0; i < count; i++)
            {
                InstructionCode code = (InstructionCode)binaryReader.ReadByte();
                payload.Add(code);
                switch (code)
                {
                case InstructionCode.SPR:
                case InstructionCode.GPR:
                    payload.Add(binaryReader.ReadInt32());
                    break;

                case InstructionCode.CSP:
                case InstructionCode.CGP:
                    payload.Add(ReadObject(binaryReader));
                    break;

                case InstructionCode.DPR:
                case InstructionCode.CDP:
                    payload.Add(ReadObject(binaryReader));
                    payload.Add(ReadObject(binaryReader));
                    break;
                }
            }
            return(payload.ToArray());
        }
Exemplo n.º 12
0
        private void Stloc(InstructionCode instruction, ReadOnlySpan <byte> program)
        {
            GetOpCodeArg(program, out int index);

            var value = _stackFrame.Pop();

            _locals[index] = value;
        }
Exemplo n.º 13
0
 internal Instruction(InstructionCode code, object[] payload, int?sourcePosition, bool interruptable, InstructionExecutionBody <G> execute)
 {
     Code           = code;
     Payload        = payload;
     SourcePosition = sourcePosition;
     Interruptable  = interruptable;
     ExecutionBody  = execute;
 }
Exemplo n.º 14
0
        public static void GenerateProgramToExecuteAllInstructions()
        {
            StringBuilder program = new StringBuilder();

            // 1. Execute all opcodes
            int nbTables          = Z80OpCodes.Tables.GetLength(0);
            int nbOpCodesPerTable = Z80OpCodes.Tables.GetLength(1);
            int opCodesCount      = 0;
            int programSize       = 0;

            for (int tableIndex = 0; tableIndex < nbTables; tableIndex++)
            {
                for (int opCodeIndex = 0; opCodeIndex < nbOpCodesPerTable; opCodeIndex++)
                {
                    InstructionCode instrCode = Z80OpCodes.Tables[tableIndex, opCodeIndex];
                    if (instrCode.FetchMoreBytes == 0 && instrCode.SwitchToTableNumber == null)
                    {
                        program.AppendLine(instrCode.InstructionText);
                        opCodesCount++;
                        programSize += instrCode.OpCodeByteCount + instrCode.OperandsByteCount;
                    }
                }
            }

            // 2. Execute all internal instructions
            int nbInstructionTypes = Z80InstructionTypes.Table.Length;

            for (int instrTypeIndex = 1; instrTypeIndex < nbInstructionTypes; instrTypeIndex++)
            {
                InstructionType instructionType = Z80InstructionTypes.Table[instrTypeIndex];
                if (instructionType.IsInternalZ80Operation)
                {
                    switch (instructionType.OpCodeName)
                    {
                    case "NMI":
                        break;

                    case "INT 0":
                        break;

                    case "INT 1":
                        break;

                    case "INT 2":
                        break;

                    case "RESET":
                        break;

                    case "?":
                        break;

                    default:
                        throw new NotImplementedException("No test implemented for internal instruction " + instructionType.OpCodeName);
                    }
                }
            }
        }
Exemplo n.º 15
0
 private static bool Ignore(InstructionCode c)
 {
     switch (c)
     {
     case InstructionCode.Constrained:
         return(true);
     }
     return(false);
 }
Exemplo n.º 16
0
 private void AddReprocessInstruction(InstructionCode code, int location)
 {
     if (!_reprocessRequiredIndexes.TryGetValue(code, out List <int> locations))
     {
         locations = new List <int>();
         _reprocessRequiredIndexes.Add(code, locations);
     }
     locations.Add(location);
 }
Exemplo n.º 17
0
        public static void WriteMessage(InstructionCode instruction, NetworkStream outputStream, NetworkStream inputStream, string[] textItems, params InstructionCode[] okResponses)
        {
            MemoryStream buffer = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(buffer);

            WriteString(writer, textItems);
            writer.Close();
            WriteMessage(instruction, outputStream, inputStream, buffer.ToArray(), okResponses);
        }
Exemplo n.º 18
0
 public static Instruction GetInstruction(InstructionCode code)
 {
     if (_list == null)
     {
         Load();
         Debug.Assert(_list != null);
     }
     return(_list[(int)code].Clone());
 }
Exemplo n.º 19
0
        private void Ceq(InstructionCode instruction, ReadOnlySpan <byte> program)
        {
            var op2 = _stackFrame.Pop();
            var op1 = _stackFrame.Pop();

            var result = Equals(op1, op2);

            _stackFrame.Push(result ? 1 : 0);
        }
Exemplo n.º 20
0
        static private UnaryOp.ArithOp UnaryOpFromCode(InstructionCode code)
        {
            switch (code)
            {
            case InstructionCode.NEG: return(UnaryOp.ArithOp.NEG);

            case InstructionCode.NOT: return(UnaryOp.ArithOp.NOT);
            }
            throw new ConvertionException();
        }
Exemplo n.º 21
0
        static public void WriteInstruction(byte[] instructions, ushort startOffset, InstructionCode instructionCode,
                                            ushort argument1, ushort argument2, ushort argument3)
        {
            ushort offset = startOffset;

            offset = WriteBytesToArray(instructions, (ushort)instructionCode, offset);
            offset = WriteBytesToArray(instructions, argument1, offset);
            offset = WriteBytesToArray(instructions, argument2, offset);
            offset = WriteBytesToArray(instructions, argument3, offset);
        }
Exemplo n.º 22
0
        private void Ldarg(InstructionCode instruction, ReadOnlySpan <byte> program)
        {
            GetOpCodeArg(program, out int index);

            if (!_args.TryGetValue(index, out var value))
            {
                Throw.LocalVariableNotSet(_pointer);
            }

            _stackFrame.Push(value);
        }
        public void VariableOperationOutOfRangeThrows(InstructionCode instructionCode, long variableIndex)
        {
            var instructions = new List <Instruction>()
            {
                new Instruction(instructionCode, variableIndex),
            };

            var exception = Assert.Throws <InvalidSourceException>(() => ExecuteIntegerFunction(instructions, varCount: 2));

            Assert.Equal(InvalidSourceDetail.InvalidVariableIndex, exception.DetailCode);
        }
        public void ConditionalBranchingWithIncorrectTypesOnStackThrows(VmType type, InstructionCode instructionCode)
        {
            var instructions = new List <Instruction>()
            {
                BuildConstantToStackInstruction(type),
                new Instruction(instructionCode, 0L)
            };
            var exception = Assert.Throws <InvalidSourceException>(() => ExecuteBooleanFunction(instructions));

            Assert.Equal(InvalidSourceDetail.IncorrectElementTypeOnStack, exception.DetailCode);
        }
Exemplo n.º 25
0
        internal static void UpdateCoverage(InstructionCode code)
        {
            LoadAllOpCodes();
            UpdateCoverageCore((ushort)code);
            var eq = GetEquivalent(code);

            if (eq != null)
            {
                UpdateCoverageCore((ushort)eq.Value);
            }
        }
Exemplo n.º 26
0
        public static Exception GetErrorInfo(InstructionCode response, byte [] body)
        {
            if (body.Length < IntSize)
            {
                return(new SednaException(response, "General error"));
            }

            Array.Copy(int_array, 0, body, IntSize + 1, IntSize);
            int length = ReadInt(int_array, 0);

            return(new SednaException(response, System.Text.Encoding.ASCII.GetString(body, IntSize + IntSize + StringTypeSize, length - (IntSize + IntSize + StringTypeSize)).Replace("\n", Environment.NewLine)));
        }
Exemplo n.º 27
0
        private void Br(InstructionCode instruction, ReadOnlySpan <byte> program)
        {
            GetOpCodeArg(program, out int target);

            if (target >= program.Length)
            {
                Throw.InvalidInstructionArgument(_pointer);
                return;
            }

            _pointer = target;
        }
        public void BranchingOutOfRangeThrows(InstructionCode instructionCode, long destinationLineNumber)
        {
            var instructions = new List <Instruction>()
            {
                new Instruction(IntegerConstantToStack, 1L),
                new Instruction(IntegerConstantToStack, 1L),
                new Instruction(instructionCode, destinationLineNumber),
                new Instruction(IntegerAdd),
            };

            var exception = Assert.Throws <InvalidSourceException>(() => ExecuteIntegerFunction(instructions));

            Assert.Equal(InvalidSourceDetail.InvalidBranchDestination, exception.DetailCode);
        }
Exemplo n.º 29
0
        private static byte[] EmitObject(object obj)
        {
            // TODO (RH -): add decimal type handling
            var code = obj switch
            {
                InstructionCode instruction => BinaryConvert.GetBytes(instruction),
                string text => BinaryConvert.GetBytes(text),
                int value => BinaryConvert.GetBytes(value),
                _ => throw new ArgumentOutOfRangeException(nameof(obj), obj.GetType().Name, null)
            };

            return(code);
        }
    }
        public void InstructionMissingRequiredDataThrows(InstructionCode instructionCode)
        {
            var instructions = new List <Instruction>()
            {
                new Instruction(instructionCode)
            };

            var functionDefinition = new FunctionDefinition(instructions, new List <VmType>(), new List <VmType>()
            {
                VmType.Boolean
            }, 0);
            var exception = Assert.Throws <InvalidSourceException>(() => new VirtualMachine(functionDefinition));

            Assert.Equal(InvalidSourceDetail.MissingInstructionData, exception.DetailCode);
        }
        public void InstructionWithUnnecessaryDataThrows(InstructionCode instructionCode)
        {
            var instructions = new List <Instruction>()
            {
                new Instruction(instructionCode, 0L)
            };

            var functionDefinition = new FunctionDefinition(instructions, new List <VmType>(), new List <VmType>()
            {
                VmType.Boolean
            }, 0);
            var exception = Assert.Throws <InvalidSourceException>(() => new VirtualMachine(functionDefinition));

            Assert.Equal(InvalidSourceDetail.InstructionCodeDoesNotUseData, exception.DetailCode);
        }
Exemplo n.º 32
0
        private IlObject?ReadArguments(InstructionCode instruction, ReadOnlySpan <byte> program, ref int pointer)
        {
            var address = new IlAddress(pointer);

            switch (instruction)
            {
            case InstructionCode.Ldstr:
            {
                var arg = BinaryConvert.GetString(ref pointer, program);
                return(new IlObject(address, 0, arg));
            }

            case InstructionCode.Ldloc:
            case InstructionCode.Stloc:
            case InstructionCode.Ldc_i4:
            case InstructionCode.Ldarg:
            case InstructionCode.Call:
            {
                var arg = BinaryConvert.GetInt32(ref pointer, program);
                return(new IlObject(address, 0, arg));
            }

            case InstructionCode.Br:
            case InstructionCode.Brfalse:
            case InstructionCode.Brtrue:
            {
                var arg = BinaryConvert.GetInt32(ref pointer, program);
                _labelTargets.Add(new IlAddress(arg));
                return(new IlObject(address, 0, arg));
            }

            case InstructionCode.Ret:
            case InstructionCode.Add:
            case InstructionCode.Ceq:
            case InstructionCode.Pop:
            case InstructionCode.Nop:
            {
                return(null);
            }

            default:
            {
                Throw.NotSupportedInstruction(pointer, program[pointer - 1]);
                return(null);
            }
            }
        }
Exemplo n.º 33
0
        public CompilerJmpInstruction(Compiler compiler, InstructionCode code, Operand[] operands)
            : base(compiler, code, operands)
        {
            if (code < InstructionDescription.JumpBegin || code > InstructionDescription.JumpEnd)
                throw new ArgumentException("The specified instruction code is not a valid jump.");
            Contract.Requires(compiler != null);
            Contract.Requires(operands != null);
            Contract.EndContractBlock();

            _jumpTarget = compiler.GetTarget(Operands[0].Id);
            _jumpTarget.JumpsCount++;

            _jumpNext = _jumpTarget.From;
            _jumpTarget.From = this;

            _isTaken =
                Code == InstructionCode.Jmp
                || (Operands.Length > 1 && Operands[1].IsImm && ((Imm)Operands[1]).Value == (IntPtr)Hint.Taken);
        }
Exemplo n.º 34
0
 static void Simplify(IInstruction i, InstructionCode op, object operand)
 {
     i.Code = op;
     i.Operand0 = operand;
 }
 void IIntrinsicSupport.EmitInstruction(InstructionCode code)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 36
0
 static void AddSByteSimplifier(InstructionCode sByteIns, InstructionCode dest)
 {
     AddSimplifier((context, ins) => SimplifyFromSByte(ins, dest), sByteIns);
 }
Exemplo n.º 37
0
 /// <summary>Initializes a new instance of the <see cref="InstructionByte" /> class.</summary>
 /// <param name="code">The instruction code.</param>
 public InstructionByte(InstructionCode code) {
     _instruction = (byte) code;
 }
Exemplo n.º 38
0
 public InstructionByte(InstructionCode code)
 {
     this.ins = (byte)code;
 }
Exemplo n.º 39
0
 public static void WriteMessage(InstructionCode instruction, NetworkStream outputStream, NetworkStream inputStream, params InstructionCode[] okResponses)
 {
     WriteMessage(instruction, outputStream, inputStream, new byte[0], okResponses);
 }
Exemplo n.º 40
0
        public CompilerInstruction(Compiler compiler, InstructionCode code, Operand[] operands)
            : base(compiler)
        {
            Contract.Requires(compiler != null);
            Contract.Requires(operands != null);

            _code = code;
            _emitOptions = compiler.EmitOptions;
            // Each created instruction takes emit options and clears it.
            compiler.EmitOptions = EmitOptions.None;

            _operands = operands;
            _memoryOperand = null;

            _variables = null;

            for (int i = 0; i < operands.Length; i++)
            {
                if (operands[i].IsMem)
                {
                    _memoryOperand = (Mem)operands[i];
                    break;
                }
            }

            InstructionDescription id = InstructionDescription.FromInstruction(_code);
            _isSpecial = id.IsSpecial;
            _isFPU = id.IsFPU;
            _isGPBHiUsed = false;
            _isGPBLoUsed = false;

            if (_isSpecial)
            {
                // ${SPECIAL_INSTRUCTION_HANDLING_BEGIN}
                switch (_code)
                {
                case InstructionCode.Cpuid:
                    // Special...
                    break;

                case InstructionCode.Cbw:
                case InstructionCode.Cdqe:
                case InstructionCode.Cwde:
                    // Special...
                    break;

                case InstructionCode.Cdq:
                case InstructionCode.Cqo:
                case InstructionCode.Cwd:
                    // Special...
                    break;

                case InstructionCode.Cmpxchg:
                case InstructionCode.Cmpxchg8b:
                case InstructionCode.Cmpxchg16b:
                    // Special...
                    if (_code == InstructionCode.Cmpxchg16b && !Util.IsX64)
                        throw new NotSupportedException(string.Format("The '{0}' instruction is only supported on X64.", _code));

                    break;

                case InstructionCode.Daa:
                case InstructionCode.Das:
                    // Special...
                    if (!Util.IsX86)
                        throw new NotSupportedException(string.Format("The '{0}' instruction is only supported on X86.", _code));

                    break;

                case InstructionCode.Imul:
                    switch (operands.Length)
                    {
                    case 2:
                        // IMUL dst, src is not special instruction.
                        _isSpecial = false;
                        break;
                    case 3:
                        if (!(_operands[0].IsVar && _operands[1].IsVar && _operands[2].IsVarMem))
                        {
                            // Only IMUL dst_hi, dst_lo, reg/mem is special, all others don't.
                            _isSpecial = false;
                        }
                        break;
                    }
                    break;
                case InstructionCode.Mul:
                case InstructionCode.Idiv:
                case InstructionCode.Div:
                    // Special...
                    break;

                case InstructionCode.MovPtr:
                    // Special...
                    break;

                case InstructionCode.Lahf:
                case InstructionCode.Sahf:
                    // Special...
                    break;

                case InstructionCode.Maskmovdqu:
                case InstructionCode.Maskmovq:
                    // Special...
                    break;

                case InstructionCode.Enter:
                case InstructionCode.Leave:
                    // Special...
                    break;

                case InstructionCode.Ret:
                    // Special...
                    break;

                case InstructionCode.Monitor:
                case InstructionCode.Mwait:
                    // Special...
                    break;

                case InstructionCode.Pop:
                case InstructionCode.Popad:
                case InstructionCode.Popfd:
                case InstructionCode.Popfq:
                    // Special...
                    break;

                case InstructionCode.Push:
                case InstructionCode.Pushad:
                case InstructionCode.Pushfd:
                case InstructionCode.Pushfq:
                    // Special...
                    break;

                case InstructionCode.Rcl:
                case InstructionCode.Rcr:
                case InstructionCode.Rol:
                case InstructionCode.Ror:
                case InstructionCode.Sal:
                case InstructionCode.Sar:
                case InstructionCode.Shl:
                case InstructionCode.Shr:
                    // Rot instruction is special only if last operand is variable (register).
                    _isSpecial = _operands[1].IsVar;
                    break;

                case InstructionCode.Shld:
                case InstructionCode.Shrd:
                    // Shld/Shrd instruction is special only if last operand is variable (register).
                    _isSpecial = _operands[2].IsVar;
                    break;

                case InstructionCode.Rdtsc:
                case InstructionCode.Rdtscp:
                    // Special...
                    break;

                case InstructionCode.RepLodsb:
                case InstructionCode.RepLodsd:
                case InstructionCode.RepLodsq:
                case InstructionCode.RepLodsw:
                case InstructionCode.RepMovsb:
                case InstructionCode.RepMovsd:
                case InstructionCode.RepMovsq:
                case InstructionCode.RepMovsw:
                case InstructionCode.RepStosb:
                case InstructionCode.RepStosd:
                case InstructionCode.RepStosq:
                case InstructionCode.RepStosw:
                case InstructionCode.RepeCmpsb:
                case InstructionCode.RepeCmpsd:
                case InstructionCode.RepeCmpsq:
                case InstructionCode.RepeCmpsw:
                case InstructionCode.RepeScasb:
                case InstructionCode.RepeScasd:
                case InstructionCode.RepeScasq:
                case InstructionCode.RepeScasw:
                case InstructionCode.RepneCmpsb:
                case InstructionCode.RepneCmpsd:
                case InstructionCode.RepneCmpsq:
                case InstructionCode.RepneCmpsw:
                case InstructionCode.RepneScasb:
                case InstructionCode.RepneScasd:
                case InstructionCode.RepneScasq:
                case InstructionCode.RepneScasw:
                    // Special...
                    break;

                default:
                    throw new CompilerException("Instruction is marked as special but handling for it is not present.");
                }
                // ${SPECIAL_INSTRUCTION_HANDLING_END}
            }
        }
Exemplo n.º 41
0
 static void SimplifyFromSByte(IInstruction i, InstructionCode op)
 {
     i.Code = op;
     if (!(i.Operand0 is IInstruction))
         i.Operand0 = ((sbyte)i.Operand0);
 }
Exemplo n.º 42
0
 public Info(InstructionCode code,bool ovf,bool un,string name,
     ParamType pType,InstructionTypeSuffix typeSuffix,AdditionalParamType apType)
 {
     this.code = code;
     this.ovf = ovf;
     this.un = un;
     this.name = name;
     this.pType = pType;
     this.typeSuffix = typeSuffix;
     this.apType = apType;
 }
Exemplo n.º 43
0
		private static bool IsFilterExit(InstructionCode code)
		{
			return(code == InstructionCode.ENDFILTER);
		}
Exemplo n.º 44
0
		static public bool IsFloatOperation(InstructionCode code, bool un, bool ovf)
		{
			switch(code)
			{
				case InstructionCode.SUB: 
				case InstructionCode.ADD: 
					return(! ovf); //ovf flag is only allowed in integer arithmetics
				case InstructionCode.XOR:
				case InstructionCode.OR:
				case InstructionCode.AND:
					return(false);
				case InstructionCode.MUL:
				case InstructionCode.DIV: 
				case InstructionCode.REM: 
					return(! un &&  ! ovf); 
					//`div.un` is not a float operation, 
					// though simply `div` is.
					//`rem` is a float operation according to documentation!
				default:
					throw new VerifierException(); //impossible case 
			}
		}
Exemplo n.º 45
0
        public static void WriteMessage(InstructionCode instruction, NetworkStream outputStream, NetworkStream inputStream, byte[] body, params InstructionCode[] okResponses)
        {
            Message msg = new Message();
            msg.Instruction = instruction;
            msg.Body = body;
            WriteMessage(msg, outputStream);
            ReadMessage(msg, inputStream);

            bool ok = false;
            foreach (InstructionCode response in okResponses)
                if (msg.Instruction==response) ok = true;

            if (!ok)
                throw GetErrorInfo(msg.Instruction, msg.Body);
        }
Exemplo n.º 46
0
 public static void WriteMessage(InstructionCode instruction, NetworkStream outputStream, NetworkStream inputStream, string[] textItems, params InstructionCode[] okResponses)
 {
     MemoryStream buffer = new MemoryStream();
     BinaryWriter writer = new BinaryWriter(buffer);
     WriteString(writer, textItems);
     writer.Close();
     WriteMessage(instruction, outputStream, inputStream, buffer.ToArray(), okResponses);
 }
Exemplo n.º 47
0
        private InstructionDescription(InstructionCode code, string name, InstructionGroup group, InstructionFlags flags, OperandFlags[] operandFlags, int opReg, int opcode0, int opcode1)
        {
            Contract.Requires(operandFlags != null);

            _code = code;
            _name = name;
            _group = (byte)group;
            _flags = (byte)flags;
            _operandFlags = new ReadOnlyCollection<OperandFlags>((OperandFlags[])operandFlags.Clone());
            _opcodeR = (short)opReg;
            _opcode0 = opcode0;
            _opcode1 = opcode1;
        }
Exemplo n.º 48
0
		private static bool IsCatchExit(InstructionCode code)
		{
			return(code == InstructionCode.LEAVE || code == InstructionCode.THROW || code == InstructionCode.RETHROW);
		}
Exemplo n.º 49
0
        internal void PreparePrologEpilog(CompilerContext cc)
        {
            Contract.Requires(cc != null);

            _pePushPop = false;
            _emitEMMS = false;
            _emitSFence = false;
            _emitLFence = false;
            _isAssumed16ByteAlignment = false;
            _isPerformed16ByteAlignment = false;

            uint accessibleMemoryBelowStack = 0;
            if (_functionPrototype.CallingConvention == CallingConvention.X64U)
                accessibleMemoryBelowStack = 128;

            if (_isCaller && (cc.MemBytesTotal > 0 || _isAssumed16ByteAlignment))
                _isEspAdjusted = true;

            if (cc.MemBytesTotal > accessibleMemoryBelowStack)
                _isEspAdjusted = true;

            _isAssumed16ByteAlignment = (_hints & FunctionHints.Assume16ByteAlignment) != 0;
            _isPerformed16ByteAlignment = (_hints & FunctionHints.Perform16ByteAlignment) != 0;
            _isNaked = (_hints & FunctionHints.Naked) != 0;
            _pePushPop = (_hints & FunctionHints.PushPopSequence) != 0;
            _emitEMMS = (_hints & FunctionHints.Emms) != 0;
            _emitSFence = (_hints & FunctionHints.StoreFence) != 0;
            _emitLFence = (_hints & FunctionHints.LoadFence) != 0;

            // Updated to respect comment from issue #47, align also when using MMX code.
            if (!_isAssumed16ByteAlignment && !_isNaked && (cc.Mem16BlocksCount + cc.Mem8BlocksCount > 0))
            {
                // Have to align stack to 16-bytes.
                _isPerformed16ByteAlignment = true;
                _isEspAdjusted = true;
            }

            _modifiedAndPreservedGP = cc.ModifiedGPRegisters & _functionPrototype.PreservedGP & ~RegisterMask.FromIndex(RegIndex.Esp);
            _modifiedAndPreservedMM = cc.ModifiedMMRegisters & _functionPrototype.PreservedMM;
            _modifiedAndPreservedXMM = cc.ModifiedXMMRegisters & _functionPrototype.PreservedXMM;

            _movDqInstruction = (IsAssumed16ByteAlignment || IsPerformed16ByteAlignment) ? InstructionCode.Movdqa : InstructionCode.Movdqu;

            // Prolog & Epilog stack size.
            {
                int memGpSize = _modifiedAndPreservedGP.RegisterCount * IntPtr.Size;
                int memMmSize = _modifiedAndPreservedMM.RegisterCount * 8;
                int memXmmSize = _modifiedAndPreservedXMM.RegisterCount * 16;

                if (_pePushPop)
                {
                    _pePushPopStackSize = memGpSize;
                    _peMovStackSize = memXmmSize + Util.AlignTo16(memMmSize);
                }
                else
                {
                    _pePushPopStackSize = 0;
                    _peMovStackSize = memXmmSize + Util.AlignTo16(memMmSize + memGpSize);
                }
            }

            if (IsPerformed16ByteAlignment)
            {
                _peAdjustStackSize += Util.DeltaTo16(_pePushPopStackSize);
            }
            else
            {
                int v = 16 - IntPtr.Size;
                if (!_isNaked)
                    v -= IntPtr.Size;

                v -= _pePushPopStackSize & 15;
                if (v < 0)
                    v += 16;
                _peAdjustStackSize = v;

                //_peAdjustStackSize += deltaTo16(_pePushPopStackSize + v);
            }

            // Memory stack size.
            _memStackSize = cc.MemBytesTotal;
            _memStackSize16 = Util.AlignTo16(_memStackSize);

            if (_isNaked)
            {
                cc.ArgumentsBaseReg = RegIndex.Esp;
                cc.ArgumentsBaseOffset = (_isEspAdjusted)
                  ? (_functionCallStackSize + _memStackSize16 + _peMovStackSize + _pePushPopStackSize + _peAdjustStackSize)
                  : (_pePushPopStackSize);
            }
            else
            {
                cc.ArgumentsBaseReg = RegIndex.Ebp;
                cc.ArgumentsBaseOffset = IntPtr.Size;
            }

            cc.VariablesBaseReg = RegIndex.Esp;
            cc.VariablesBaseOffset = _functionCallStackSize;
            if (!_isEspAdjusted)
                cc.VariablesBaseOffset = -_memStackSize16 - _peMovStackSize - _peAdjustStackSize;
        }
Exemplo n.º 50
0
		private static bool IsTryExit(InstructionCode code)
		{
			return(code == InstructionCode.LEAVE || code == InstructionCode.THROW);
		}
Exemplo n.º 51
0
        public static Exception GetErrorInfo(InstructionCode response, byte [] body)
        {
            if (body.Length < IntSize) return new SednaException(response, "General error");

            Array.Copy(int_array, 0, body, IntSize + 1, IntSize);
            int length = ReadInt(int_array, 0);

            return new SednaException(response, System.Text.Encoding.ASCII.GetString(body, IntSize + IntSize + StringTypeSize, length - (IntSize + IntSize + StringTypeSize)).Replace("\n", Environment.NewLine));
        }
Exemplo n.º 52
0
 private static InstructionDescription MAKE_INST(InstructionCode code, string name, InstructionGroup group, InstructionFlags flags, OperandFlags oflags0, OperandFlags oflags1, int opReg, uint opcode0, uint opcode1)
 {
     return new InstructionDescription(code, name, group, flags, new OperandFlags[] { oflags0, oflags1 }, opReg, (int)opcode0, (int)opcode1);
 }
 public InstructionOrigin(InstructionSource source, InstructionCode opCode, ushort memoryAddress)
 {
     Source = source;
     OpCode = opCode;
     Address = memoryAddress;
 }
Exemplo n.º 54
0
		private static bool IsFinallyExit(InstructionCode code)
		{
			return(code == InstructionCode.ENDFINALLY);
		}
Exemplo n.º 55
0
        public static InstructionDescription FromInstruction(InstructionCode code)
        {
            InstructionDescription description = instructionDescriptions[(int)code];
            if (description.Code != code)
                throw new InvalidOperationException();

            return description;
        }
Exemplo n.º 56
0
 public SednaException(InstructionCode retCode, string message)
     : base(message)
 {
     ReturnCode = retCode;
 }
Exemplo n.º 57
0
        internal Instruction(ILMethodDecoder decoder)
        {
            stack = null;

            startOffset = decoder.GetOffset();
            int code = decoder.ReadCode();
            Info info = instructions[code];

            if (info.code == InstructionCode.TAIL)
            {
                hasTail = true;
                code = decoder.ReadCode();
                info = instructions[code];
            }
            else
                hasTail = false;

            hasUnaligned = false;
            hasVolatile = false;
            unalignedParam = 0;

            while (info.code == InstructionCode.VOLATILE || info.code == InstructionCode.UNALIGNED)
            {
                if (info.code == InstructionCode.VOLATILE)
                    hasVolatile = true;
                else
                {
                    hasUnaligned = true;
                    unalignedParam = (Int32)(decoder.ReadUint8());
                }

                code = decoder.ReadCode();
                info = instructions[code];
            }

            instructionCode = info.code;
            ovfFlag = info.ovf;
            unFlag = info.un;
            typeSuffix = info.typeSuffix;
            name = info.name;

            paramIsOffset = false;

            switch (info.pType)
            {
                case ParamType.pNone:
                    if (info.apType >= AdditionalParamType.apU0 &&
                        info.apType <= AdditionalParamType.apU3)
                        param = (Int32)(info.apType-AdditionalParamType.apU0);

                    if (info.apType >= AdditionalParamType.apIM1 &&
                        info.apType <= AdditionalParamType.apI8)
                        param = (Int32)(info.apType-AdditionalParamType.apIM1-1);
                    break;

                case ParamType.pInt8:
                    param = (Int32)(decoder.ReadInt8());
                    if (info.apType == AdditionalParamType.apOfs)
                        paramIsOffset = true;
                    break;

                case ParamType.pInt32:
                    param = decoder.ReadInt32();
                    if (info.apType == AdditionalParamType.apOfs)
                        paramIsOffset = true;
                    break;

                case ParamType.pInt64:
                    param = decoder.ReadInt64();
                    break;

                case ParamType.pUint8:
                    param = (Int32)(decoder.ReadUint8());
                    break;

                case ParamType.pUint16:
                    param = (Int32)(decoder.ReadUint16());
                    break;

                case ParamType.pFloat32:
                    param = (double)(decoder.ReadFloat32());
                    break;

                case ParamType.pFloat64:
                    param = decoder.ReadFloat64();
                    break;

                case ParamType.pToken:
                    param = decoder.ReadToken();
                    break;

                case ParamType.pSwitch:
                    param = decoder.ReadSwitch();
                    paramIsOffset = true;
                    break;
            }

            afterEndOffset = decoder.GetOffset();
        }
 public Apdu(byte cla, InstructionCode ins, byte p1, byte p2, byte? le = null) : this(cla, (byte)ins, p1, p2, le) { }
Exemplo n.º 59
0
 /// <summary>Initializes a new instance of the <see cref="InstructionByte" /> class.</summary>
 /// <param name="code">The instruction code.</param>
 public InstructionByte(InstructionCode code) {
     Value = (byte) code;
 }