Exemplo n.º 1
0
        public List <string> FindProcedureUsages(int?id)
        {
            DecoderContext db = null;

            try
            {
                db = new DecoderContext();
                var decoder = db.Decoders.Find(id);
                if (decoder != null)
                {
                    var proceduresThatUseIt =
                        db.Decoders.Where(d => d.BlocklyDef.Contains("<mutation name=\"" + decoder.Name + "\">"))
                        .Select(d => d.Name)
                        .ToList();
                    return(proceduresThatUseIt);
                }
                else
                {
                    throw new KeyNotFoundException();
                }
            }
            finally
            {
                db?.Dispose();
            }
        }
Exemplo n.º 2
0
        public void HandleUpstream(IPipelineHandlerContext ctx, IPipelineMessage message)
        {
            if (message is Connected)
            {
                _context = new DecoderContext {
                    ParserMethod = ParseBeforeHeader
                };
            }
            else if (message is Closed)
            {
                _context = null;
            }
            if (!(message is Received))
            {
                ctx.SendUpstream(message);
                return;
            }


            var evt    = (Received)message;
            var buffer = evt.BufferSlice;

            _logger.Trace("Pos: " + buffer.Position);
            _context.Reader.Assign(buffer);


            try
            {
                var canrun = true;
                while (canrun)
                {
                    _logger.Trace("Parsing using " + _context.ParserMethod.Method.Name);
                    canrun = _context.ParserMethod();
                }
            }
            catch (Exception err)
            {
                _logger.Error("Failed to parse message.", err);
                ctx.SendUpstream(new PipelineFailure(err));
                return;
            }

            if (!_context.IsComplete)
            {
                //_leftOvers = Encoding.UTF8.GetString(buffer.Buffer, buffer.Offset, buffer.RemainingLength);
                return; // Need more data from the channel
            }

            _context.ParserMethod = ParseBeforeHeader;
            _logger.Debug("Got message " + _context.Message.Headers["Content-Type"]);
            if (string.IsNullOrEmpty(_context.Message.Headers["Content-Type"]))
            {
                _logger.Warning("Malformed message\r\n" +
                                Encoding.ASCII.GetString(buffer.Buffer, buffer.StartOffset, buffer.Count));
                Debugger.Break();
            }

            ctx.SendUpstream(new ReceivedMessage(_context.Message));
            _context.Message = new Message();
        }
        public Decoder GetDecoder(Guid?id)
        {
            DecoderContext db = null;

            try
            {
                var decoder = db.Decoders.Find(id);
                return(decoder);
            }
            catch (Exception e)
            {
                throw;
            }
            finally
            {
                try
                {
                    db?.Dispose();
                }
                catch (Exception e)
                {
                    throw;
                }
            }
        }
        //private DecoderContext db = new DecoderContext();

        public void AddDecoder(Decoder decoder)
        {
            DecoderContext db = null;

            try
            {
                db = new DecoderContext();
                decoder.SetCategoryAndTags();
                db.Decoders.Add(decoder);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                throw;
            }
            finally
            {
                try
                {
                    db?.Dispose();
                }
                catch (Exception e)
                {
                    throw;
                }
            }
        }
        public void UpdateDecoder(Guid?id, string xml, string code)
        {
            DecoderContext db = null;

            try
            {
                var decoder = db.Decoders.Find(id);
                if (decoder != null)
                {
                    decoder.Xml  = xml;
                    decoder.Code = code;
                    decoder.SetCategoryAndTags();
                    db.SaveChanges();
                }
                else
                {
                    throw new KeyNotFoundException();
                }
            }
            catch (Exception e)
            {
                throw;
            }
            finally
            {
                try
                {
                    db?.Dispose();
                }
                catch (Exception e)
                {
                    throw;
                }
            }
        }
Exemplo n.º 6
0
        public Dictionary <string, List <BlockInfos> > GetCategoryInfos()
        {
            DecoderContext db = null;

            try
            {
                db = new DecoderContext();

                /* Dictionary<string, List<BlockInfos>> categoryInfos = db.Decoders
                 *   //.Select(d => new { d.Category, callInfos = new CallInfos(d.Id, d.Name, d.Parameters, d.Tags, d.Editable) })
                 *   .GroupBy(d => d.Category, d => new BlockInfos(d.Id, d.Name, d.Parameters, d.Tags, d.Editable))
                 * .ToDictionary(g => g.Key, g => g.ToList());*/
                var fromServer =
                    db.Decoders.Select(
                        d => new { d.Category, d.Id, d.Name, d.Parameters, d.Tags, d.Version, d.Editable }).ToList();
                var categoryInfos =
                    fromServer.GroupBy(
                        d => d.Category,
                        d => new BlockInfos((int)d.Id, d.Name, d.Category, d.Parameters, d.Tags, d.Version, d.Editable))
                    .ToDictionary(d => d.Key, d => d.ToList());
                return(categoryInfos);
            }
            finally
            {
                db?.Dispose();
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Decodes an instruction.
        /// </summary>
        /// <param name="code">X86 binary code.</param>
        /// <param name="startIndex">Index of the first byte to start
        /// decoding.</param>
        /// <param name="context">Decoding context.</param>
        /// <returns>The decoded instruction.</returns>
        /// <exception cref="InvalidInstructionException">If decoding failed.
        /// </exception>
        public Instruction Decode(
            byte[] code, 
            int startIndex,
            int count,
            DecoderContext context)
        {
            Instruction instruction = new Instruction();

            // Create an instruction reader.
            InstructionReader reader = new InstructionReader(code, startIndex, count);

            // Reset the context.
            context.AddressSize = CpuSize.Use16Bit;
            context.OperandSize = CpuSize.Use16Bit;
            context.SegmentOverride = Register.None;

            // Decode prefixes.
            Prefixes prefix = DecodeLegacyPrefixes(reader);
            if ((prefix & Prefixes.OperandSizeOverride) != 0)
            {
                context.OperandSize = CpuSize.Use32Bit;
            }
            if ((prefix & Prefixes.AddressSizeOverride) != 0)
            {
                context.AddressSize = CpuSize.Use32Bit;
            }
            if ((prefix & Prefixes.Group2) != 0)
            {
                Register seg = Register.None;
                switch (prefix & Prefixes.Group2)
                {
                    case Prefixes.ES: seg = Register.ES; break;
                    case Prefixes.CS: seg = Register.CS; break;
                    case Prefixes.SS: seg = Register.SS; break;
                    case Prefixes.DS: seg = Register.DS; break;
                    case Prefixes.FS: seg = Register.FS; break;
                    case Prefixes.GS: seg = Register.GS; break;
                }
                context.SegmentOverride = seg;
            }
            instruction.Prefix = prefix;

            // Decode the opcode to retrieve opcode specification.
            Op spec = DecodeOpcode(reader);
            instruction.Operation = spec.Operation;

            // Decode operands.
            instruction.Operands = new Operand[spec.Operands.Length];
            for (int i = 0; i < spec.Operands.Length; i++)
            {
                instruction.Operands[i] =
                    DecodeOperand(spec.Operands[i], reader, context);
            }

            // Update the encoded length of the instruction.
            instruction.EncodedLength = reader.Position;
            //instruction.Location = location;
            return instruction;
        }
        public void HandleUpstream(IPipelineHandlerContext ctx, IPipelineMessage message)
        {
            if (message is Connected)
            {
                _context = new DecoderContext {ParserMethod = ParseBeforeHeader};
            }
            else if (message is Closed)
            {
                _context = null;
            }
            if (!(message is Received))
            {
                ctx.SendUpstream(message);
                return;
            }


            var evt = (Received) message;
            var buffer = evt.BufferReader;
            _logger.Trace("Pos: " + buffer.Position);
            _context.Reader.Assign(buffer);


            try
            {
                var canrun = true;
                while (canrun)
                {
                    _logger.Trace("Parsing using " + _context.ParserMethod.Method.Name);
                    canrun = _context.ParserMethod();
                }
            }
            catch (Exception err)
            {
                _logger.Error("Failed to parse message.", err);
                ctx.SendUpstream(new PipelineFailure(err));
                return;
            }

            if (!_context.IsComplete)
            {
                //_leftOvers = Encoding.UTF8.GetString(buffer.Buffer, buffer.Offset, buffer.RemainingLength);
                return; // Need more data from the channel
            }

            _context.ParserMethod = ParseBeforeHeader;
            _logger.Debug("Got message " + _context.Message.Headers["Content-Type"]);
            if (string.IsNullOrEmpty(_context.Message.Headers["Content-Type"]))
            {
                _logger.Warning("Malformed message\r\n" +
                                Encoding.ASCII.GetString(buffer.Buffer, buffer.StartOffset, buffer.Count));
                Debugger.Break();
            }

            ctx.SendUpstream(new ReceivedMessage(_context.Message));
            _context.Message = new Message();
        }
Exemplo n.º 9
0
        public static T Decode <T>(DecoderContext context, RlpBehaviors rlpBehaviors = RlpBehaviors.None)
        {
            if (Decoders.ContainsKey(typeof(T)))
            {
                return(((IRlpDecoder <T>)Decoders[typeof(T)]).Decode(context, rlpBehaviors));
            }

            throw new RlpException($"{nameof(Rlp)} does not support decoding {typeof(T).Name}");
        }
Exemplo n.º 10
0
        /// <summary>
        /// Decodes an instruction.
        /// </summary>
        /// <param name="code">Code buffer.</param>
        /// <param name="cpuMode">CPU operating mode.</param>
        /// <returns>The decoded instruction.</returns>
        /// <exception cref="InvalidInstructionException">If decoding fails.
        /// </exception>
        public static Instruction Decode(ArraySegment<byte> code, CpuMode cpuMode)
        {
            if (cpuMode != CpuMode.RealAddressMode)
                throw new NotSupportedException();

            DecoderContext context = new DecoderContext();
            context.AddressSize = CpuSize.Use16Bit;
            context.OperandSize = CpuSize.Use16Bit;

            X86Codec.Decoder decoder = new X86Codec.Decoder();
            return decoder.Decode(code.Array, code.Offset, code.Count, context);
        }
Exemplo n.º 11
0
        public static T[] DecodeArray <T>(DecoderContext context, RlpBehaviors rlpBehaviors = RlpBehaviors.None)
        {
            if (Decoders.ContainsKey(typeof(T)))
            {
                IRlpDecoder <T> decoder       = (IRlpDecoder <T>)Decoders[typeof(T)];
                int             checkPosition = context.ReadSequenceLength() + context.Position;
                T[]             result        = new T[context.ReadNumberOfItemsRemaining(checkPosition)];
                for (int i = 0; i < result.Length; i++)
                {
                    result[i] = decoder.Decode(context, rlpBehaviors);
                }

                return(result);
            }

            throw new RlpException($"{nameof(Rlp)} does not support decoding {typeof(T).Name}");
        }
Exemplo n.º 12
0
        // private DecoderContext db = new DecoderContext();
        public int?AddDecoder(Decoder decoder)
        {
            DecoderContext db = null;

            try
            {
                db = new DecoderContext();
                decoder.UpdateFieldsFromXml();
                db.Decoders.Add(decoder);
                db.SaveChanges();
                return(decoder.Id);
            }
            finally
            {
                db?.Dispose();
            }
        }
Exemplo n.º 13
0
        public bool UpdateDecoder(Decoder updatedDecoder)
        {
            DecoderContext db = null;
            var            mustRefreshToolbox = false;

            try
            {
                db = new DecoderContext();
                updatedDecoder.UpdateFieldsFromXml();
                var decoder = db.Decoders.Find(updatedDecoder.Id);
                if (decoder != null)
                {
                    /*decoder.Name = updatedDecoder.Name;
                     * decoder.Version = updatedDecoder.Version;
                     * decoder.Category = updatedDecoder.Category;
                     * decoder.Tags = updatedDecoder.Tags;
                     * decoder.Xml = updatedDecoder.Xml;
                     * decoder.Code = updatedDecoder.Code;
                     * decoder.FrenchSpec = updatedDecoder.FrenchSpec;
                     * decoder.UpdateFieldsFromXml();*/
                    if (decoder.Name != updatedDecoder.Name || decoder.Version != updatedDecoder.Version ||
                        decoder.Category != updatedDecoder.Category ||
                        decoder.Parameters != updatedDecoder.Parameters || decoder.Tags != updatedDecoder.Tags ||
                        decoder.Editable != updatedDecoder.Editable)
                    {
                        mustRefreshToolbox = true;
                    }

                    //TODO DO NOT OVERRIDE CODE AND SPEC

                    db.Entry(decoder).CurrentValues.SetValues(updatedDecoder);
                    db.SaveChanges();
                    return(mustRefreshToolbox);
                }
                else
                {
                    throw new KeyNotFoundException();
                }
            }
            finally
            {
                db?.Dispose();
            }
        }
Exemplo n.º 14
0
        public IEnumerable <BlockInfos> GetAllBlockInfos()
        {
            DecoderContext db = null;

            try
            {
                db = new DecoderContext();
                var fromServer =
                    db.Decoders.ToList()
                    .Select(
                        d =>
                        new BlockInfos((int)d.Id, d.Name, d.Category, d.Parameters, d.Tags, d.Version, d.Editable));
                return(fromServer);
            }
            finally
            {
                db?.Dispose();
            }
        }
Exemplo n.º 15
0
        public void HandleUpstream(IChannelHandlerContext ctx, IChannelEvent e)
        {
            if (e is ConnectedEvent)
            {
                ctx.State = new DecoderContext
                                {
                                    ParserMethod = ParseBeforeHeader
                                };
            }
            else if (e is ClosedEvent)
            {
                ctx.State = null;
            }
            if (!(e is MessageEvent))
            {
                ctx.SendUpstream(e);
                return;
            }

            var evt = e.As<MessageEvent>();
            _context = ctx.State.As<DecoderContext>();

            var buffer = evt.Message.As<BufferSlice>();
            _context.Reader.Assign(buffer);

            try
            {
                while (_context.ParserMethod()) ;
            }
            catch (Exception err)
            {
                ctx.SendUpstream(new ExceptionEvent(err));
                return;
            }

            if (!_context.IsComplete)
                return; // no more processing

            evt.Message = _context.Message;
            _context.ParserMethod = ParseBeforeHeader;
            ctx.SendUpstream(evt);
            _context.Message.Reset();
        }
Exemplo n.º 16
0
        public static void ParseHeaders(Dictionary <string, string> headers, DecoderContext decoder)
        {
            decoder.Headers   = "";
            decoder.Referer   = "";
            decoder.UserAgent = "";

            foreach (var hdr in headers)
            {
                if (hdr.Key.ToLower() == "user-agent")
                {
                    decoder.UserAgent = hdr.Value;
                }
                else if (hdr.Key.ToLower() == "referer")
                {
                    decoder.Referer = hdr.Value;
                }
                else
                {
                    decoder.Headers += hdr.Key + ": " + hdr.Value + "\r\n";
                }
            }
        }
Exemplo n.º 17
0
        public Decoder GetDecoder(int?id)
        {
            DecoderContext db = null;

            try
            {
                db = new DecoderContext();
                var decoder = db.Decoders.Find(id);
                if (decoder != null)
                {
                    return(decoder);
                }
                else
                {
                    throw new KeyNotFoundException("L'ID envoyée ne correspond à aucun décodeur dans la base de donnée");
                }
            }
            finally
            {
                db?.Dispose();
            }
        }
Exemplo n.º 18
0
        public void DeleteDecoder(int?id)
        {
            DecoderContext db = null;

            try
            {
                db = new DecoderContext();
                var decoder = db.Decoders.Find(id);
                if (decoder != null)
                {
                    db.Decoders.Remove(decoder);
                    db.SaveChanges();
                }
                else
                {
                    throw new KeyNotFoundException("L'ID envoyée ne correspond à aucun décodeur dans la base de donnée");
                }
            }
            finally
            {
                db?.Dispose();
            }
        }
Exemplo n.º 19
0
        private static Rlp[] ExtractRlpList(DecoderContext context)
        {
            List <Rlp> result = new List <Rlp>();

            while (context.CurrentIndex < context.MaxIndex)
            {
                byte   prefix      = context.Pop();
                byte[] lenghtBytes = null;

                int concatenationLength;

                if (prefix == 0)
                {
                    result.Add(new Rlp(new byte[] { 0 }));
                    continue;
                }

                if (prefix < 128)
                {
                    result.Add(new Rlp(new[] { prefix }));
                    continue;
                }

                if (prefix == 128)
                {
                    result.Add(new Rlp(new byte[] { }));
                    continue;
                }

                if (prefix <= 183)
                {
                    int    length  = prefix - 128;
                    byte[] content = context.Pop(length);
                    if (content.Length == 1 && content[0] < 128)
                    {
                        throw new RlpException($"Unexpected byte value {content[0]}");
                    }

                    result.Add(new Rlp(new[] { prefix }.Concat(content).ToArray()));
                    continue;
                }

                if (prefix <= 247)
                {
                    concatenationLength = prefix - 192;
                }
                else
                {
                    int lengthOfConcatenationLength = prefix - 247;
                    if (lengthOfConcatenationLength > 4)
                    {
                        // strange but needed to pass tests -seems that spec gives int64 length and tests int32 length
                        throw new RlpException("Expected length of lenth less or equal 4");
                    }

                    lenghtBytes         = context.Pop(lengthOfConcatenationLength);
                    concatenationLength = DeserializeLength(lenghtBytes);
                    if (concatenationLength < 56)
                    {
                        throw new RlpException("Expected length greater or equal 56");
                    }
                }

                byte[] data      = context.Pop(concatenationLength);
                byte[] itemBytes = { prefix };
                if (lenghtBytes != null)
                {
                    itemBytes = itemBytes.Concat(lenghtBytes).ToArray();
                }

                result.Add(new Rlp(itemBytes.Concat(data).ToArray()));
            }

            return(result.ToArray());
        }
Exemplo n.º 20
0
        /// <summary>
        /// Decodes a register operand from the REG field of the ModR/M byte.
        /// Since the REG field only contains the register number, additional
        /// parameters are used to determine the register's type and size.
        /// </summary>
        /// <param name="reader">Instruction reader.</param>
        /// <param name="registerType">Type of the register to return.</param>
        /// <param name="operandSize">Size of the register to return.</param>
        /// <param name="context">Decoding context.</param>
        /// <returns>The decoded register operand.</returns>
        private static RegisterOperand DecodeRegisterOperand(
            InstructionReader reader,
            RegisterType registerType,
            CpuSize operandSize,
            DecoderContext context)
        {
            if (context.CpuMode == CpuMode.X64Mode)
                throw new NotSupportedException();
            if (operandSize == CpuSize.Default)
                throw new ArgumentException("operandSize is not specified.");

            int reg = reader.GetModRM().REG;
            if (registerType == RegisterType.General &&
                operandSize == CpuSize.Use8Bit &&
                reg >= 4)
            {
                return new RegisterOperand(new Register(
                    RegisterType.HighByte,
                    reg - 4,
                    CpuSize.Use8Bit));
            }
            return new RegisterOperand(new Register(registerType, reg, operandSize));
        }
Exemplo n.º 21
0
        private void TestDecode(
            byte[] image,
            Pointer startAddress,
            Pointer baseAddress)
        {
            DecoderContext options = new DecoderContext();

            options.AddressSize = CpuSize.Use16Bit;
            options.OperandSize = CpuSize.Use16Bit;

            X86Codec.Decoder decoder = new X86Codec.Decoder();

            Pointer ip = startAddress;

            for (int index = startAddress - baseAddress; index < image.Length;)
            {
                Instruction instruction = null;
                try
                {
                    instruction = decoder.Decode(image, index, ip, options);
                }
                catch (InvalidInstructionException ex)
                {
                    if (MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OKCancel)
                        == DialogResult.Cancel)
                    {
                        throw;
                    }
                    break;
                }
#if false
                // Output address.
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("0000:{0:X4}  ", index - startAddress);

                // Output binary code. */
                for (int i = 0; i < 8; i++)
                {
                    if (i < instruction.EncodedLength)
                    {
                        sb.AppendFormat("{0:x2} ", image[index + i]);
                    }
                    else
                    {
                        sb.Append("   ");
                    }
                }

                // Output the instruction.
                string s = instruction.ToString();
                if (s.StartsWith("*"))
                {
                    throw new InvalidOperationException("Cannot format instruction.");
                }
                sb.Append(s);

                System.Diagnostics.Debug.WriteLine(sb.ToString());
#else
                DisplayInstruction(instruction);
#endif
                index += instruction.EncodedLength;
                ip    += instruction.EncodedLength;
            }
        }
Exemplo n.º 22
0
        public List <Decoder> FindDescendants(int?id)
        {
            DecoderContext db = null;

            try
            {
                db = new DecoderContext();
                var decoder = db.Decoders.Find(id);

                if (decoder != null)
                {
                    var names    = new List <string>();
                    var decoders = new List <Decoder> {
                        decoder
                    };

                    // names.AddRange(decoder.FindDescendants());
                    var firsts = decoder.FindDescendants();
                    foreach (var name in firsts)
                    {
                        if (!names.Exists(x => x == name))
                        {
                            names.Add(name);
                        }
                    }

                    for (var i = 0; i < names.Count; i++)
                    {
                        var curName    = names[i];
                        var descendant = db.Decoders.Single(d => d.Name == curName);
                        var namesToAdd = descendant.FindDescendants();
                        foreach (var name in namesToAdd)
                        {
                            if (!names.Exists(x => x == name))
                            {
                                names.Add(name);
                            }
                        }

                        decoders.Add(descendant);
                    }

                    return(decoders);

                    /*var decoders = new List<Decoder>();
                     * foreach (var name in names)
                     * {
                     *  decoders.Add(db.Decoders.Find(name));
                     * }
                     * return decoders;*/
                }
                else
                {
                    throw new KeyNotFoundException();
                }
            }
            finally
            {
                db?.Dispose();
            }
        }
Exemplo n.º 23
0
        // Note: we need to take into account OperandSizeOverride and
        // AddressSizeOverride!!!!!!

        /// <summary>
        /// Decodes a memory operand encoded by the ModRM byte, SIB byte, and
        /// Displacement, or a register operand if MOD=3 and registerType is
        /// specified.
        /// </summary>
        /// <param name="reader">Instruction reader.</param>
        /// <param name="registerType">Type of the register to return if the
        /// Mod field of the ModR/M byte is 3. If this parameter is set to
        /// RegisterType.None, an exception is thrown if Mod=3.</param>
        /// <param name="operandSize">Size of the returned operand.</param>
        /// <param name="context">Decoding context.</param>
        /// <returns>The decoded memory or register operand.</returns>
        /// <exception cref="InvalidInstructionException">If registerType is
        /// set to None but the ModR/M byte encodes a register.</exception>
        static Operand DecodeMemoryOperand(
            InstructionReader reader,
            RegisterType registerType,
            CpuSize operandSize,
            DecoderContext context)
        {
            if (context.CpuMode == CpuMode.X64Mode)
                throw new NotSupportedException();
            //if (operandSize == CpuSize.Default)
            //    throw new ArgumentException("operandSize is not specified.");
            if (context.AddressSize != CpuSize.Use16Bit)
                throw new NotSupportedException("32-bit addressing mode is not supported.");

            ModRM modrm = reader.GetModRM();
            int rm = modrm.RM;
            int mod = modrm.MOD;

            // Decode a register if MOD = (11).
            if (mod == 3)
            {
                // If the instruction expects a memory operand, throw an exception.
                if (registerType == RegisterType.None)
                {
                    throw new InvalidInstructionException(
                        "The instruction expects a memory operand, but the ModR/M byte encodes a register.");
                }

                // Treat AH-DH specially.
                if (registerType == RegisterType.General &&
                    operandSize == CpuSize.Use8Bit &&
                    rm >= 4)
                {
                    return new RegisterOperand(new Register(
                        RegisterType.HighByte,
                        rm - 4,
                        CpuSize.Use8Bit));
                }
                else
                {
                    return new RegisterOperand(new Register(registerType, rm, operandSize));
                }
            }

            // Take into account segment override prefix if present.
            Register segment = context.SegmentOverride;

            // Special treatment for MOD = (00) and RM = (110).
            // This encodes a 16-bit sign-extended displacement.
            if (mod == 0 && rm == 6)
            {
                return new MemoryOperand
                {
                    Size = operandSize,
                    Segment = segment,
                    Displacement = reader.ReadImmediate(CpuSize.Use16Bit)
                };
            }

            /* Decode an indirect memory address XX[+YY][+disp]. */
            MemoryOperand mem = new MemoryOperand();
            mem.Size = operandSize;
            mem.Segment = segment;
            switch (rm)
            {
                case 0: /* [BX+SI] */
                    mem.Base = Register.BX;
                    mem.Index = Register.SI;
                    break;
                case 1: /* [BX+DI] */
                    mem.Base = Register.BX;
                    mem.Index = Register.DI;
                    break;
                case 2: /* [BP+SI] */
                    mem.Base = Register.BP;
                    mem.Index = Register.SI;
                    break;
                case 3: /* [BP+DI] */
                    mem.Base = Register.BP;
                    mem.Index = Register.DI;
                    break;
                case 4: /* [SI] */
                    mem.Base = Register.SI;
                    break;
                case 5: /* [DI] */
                    mem.Base = Register.DI;
                    break;
                case 6: /* [BP] */
                    mem.Base = Register.BP;
                    break;
                case 7: /* [BX] */
                    mem.Base = Register.BX;
                    break;
            }
            if (mod == 1) /* disp8, sign-extended */
            {
                mem.Displacement = reader.ReadImmediate(CpuSize.Use8Bit);
            }
            else if (mod == 2) /* disp16, sign-extended */
            {
                mem.Displacement = reader.ReadImmediate(CpuSize.Use16Bit);
            }
            return mem;
        }
Exemplo n.º 24
0
        static Operand DecodeOperand(O spec,
            InstructionReader reader, DecoderContext context)
        {
            int number;
            CpuSize size;

            switch (spec)
            {
                case O.Imm0:
                case O.Imm1:
                case O.Imm2:
                case O.Imm3:
                    return new ImmediateOperand(spec - O.Imm0, CpuSize.Use8Bit);

                case O.ES:
                case O.CS:
                case O.SS:
                case O.DS:
                    return CreateRegisterOperand(
                        RegisterType.Segment,
                        spec - O.ES,
                        CpuSize.Use16Bit);

                case O.AL:
                case O.CL:
                case O.DL:
                case O.BL:
                    return CreateRegisterOperand(
                        RegisterType.General,
                        spec - O.AL,
                        CpuSize.Use8Bit);

                case O.AH:
                case O.CH:
                case O.DH:
                case O.BH:
                    return CreateRegisterOperand(
                        RegisterType.HighByte,
                        spec - O.AH,
                        CpuSize.Use8Bit);

                case O.AX:
                case O.CX:
                case O.DX:
                case O.BX:
                case O.SP:
                case O.BP:
                case O.SI:
                case O.DI:
                    return CreateRegisterOperand(
                        RegisterType.General,
                        spec - O.AX,
                        CpuSize.Use16Bit);

                case O.eAX:
                case O.eCX:
                case O.eDX:
                case O.eBX:
                case O.eSP:
                case O.eBP:
                case O.eSI:
                case O.eDI:
                    number = spec - O.eAX;
                    size = (context.OperandSize == CpuSize.Use16Bit) ?
                        CpuSize.Use16Bit : CpuSize.Use32Bit;
                    return CreateRegisterOperand(RegisterType.General, number, size);

                case O.rAX:
                case O.rCX:
                case O.rDX:
                case O.rBX:
                case O.rSP:
                case O.rBP:
                case O.rSI:
                case O.rDI:
                    number = spec - O.rAX;
                    return CreateRegisterOperand(RegisterType.General, number, context.OperandSize);

                case O.ST0:
                    return new RegisterOperand(Register.ST0);

                case O.Ap: // off:seg encoded in the instruction
                    if (context.OperandSize != CpuSize.Use16Bit)
                    {
                        throw new NotSupportedException();
                    }
                    else
                    {
                        var off = reader.ReadImmediate(CpuSize.Use16Bit);
                        var seg = reader.ReadImmediate(CpuSize.Use16Bit);
                        return new PointerOperand(
                            new Operand.LocationAware<UInt16>(seg.Location, (UInt16)seg.Value),
                            new Operand.LocationAware<UInt32>(off.Location, (UInt16)off.Value));
                    }

                case O.Eb: // r/m; 8-bit
                    return DecodeMemoryOperand(reader, RegisterType.General, CpuSize.Use8Bit, context);

                case O.Ep: // r/m; contains far ptr
                    if (context.OperandSize != CpuSize.Use16Bit)
                        throw new NotSupportedException();
                    // TBD: operand size? address size?
                    return DecodeMemoryOperand(reader, RegisterType.General, CpuSize.Use16Bit, context);

                case O.Ev: // r/m; 16, 32, or 64 bit
                    return DecodeMemoryOperand(reader, RegisterType.General, context.OperandSize, context);

                case O.Ew: // r/m; 16-bit
                    return DecodeMemoryOperand(reader, RegisterType.General, CpuSize.Use16Bit, context);

                case O.Fv: // FLAGS/EFLAGS/RFLAGS
                    return new RegisterOperand(Register.FLAGS.Resize(context.OperandSize));

                case O.Gb: // general-purpose register; byte
                    return DecodeRegisterOperand(reader, RegisterType.General, CpuSize.Use8Bit, context);

                case O.Gv: // general-purpose register; 16, 32, or 64 bit
                    return DecodeRegisterOperand(reader, RegisterType.General, context.OperandSize, context);

                case O.Gw: // general-purpose register; 16-bit
                    return DecodeRegisterOperand(reader, RegisterType.General, CpuSize.Use16Bit, context);

                case O.Gz: // general-purpose register; 16 or 32 bit
                    return DecodeRegisterOperand(
                        reader,
                        RegisterType.General,
                        context.OperandSize == CpuSize.Use16Bit ? CpuSize.Use16Bit : CpuSize.Use32Bit,
                        context);

                case O.Ib: // immediate; byte
                    return DecodeImmediateOperand(reader, CpuSize.Use8Bit);

                case O.Iw: // immediate; 16 bit
                    return DecodeImmediateOperand(reader, CpuSize.Use16Bit);

                case O.Iv: // immediate, 16, 32, or 64 bit
                    return DecodeImmediateOperand(reader, context.OperandSize);

                case O.Iz: // immediate, 16 or 32 bit
                    return DecodeImmediateOperand(reader,
                        (context.OperandSize == CpuSize.Use16Bit) ?
                        CpuSize.Use16Bit : CpuSize.Use32Bit);

                case O.Jb: // immediate encodes relative offset; byte
                    return DecodeRelativeOperand(reader, CpuSize.Use8Bit);

                case O.Jz: // immediate encodes relative offset; 16 or 32 bit
                    return DecodeRelativeOperand(reader,
                        (context.OperandSize == CpuSize.Use16Bit) ?
                        CpuSize.Use16Bit : CpuSize.Use32Bit);

                case O.M_: // r/m must refer to memory; contains void pointer
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Default, context);

                case O.Ma: // r/m must refer to memory; contains a pair of words or dwords
                    // TODO: handle 32-bit
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Use32Bit, context);

                case O.Mp: // r/m must refer to memory; contains far pointer
                    // seg:ptr of 32, 48, or 80 bits.
                    if (context.OperandSize != CpuSize.Use16Bit)
                        throw new NotSupportedException();
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Use32Bit, context);

                case O.Mb: // r/m refers to memory; byte
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Use8Bit, context);

                case O.Mw: // r/m refers to memory; word
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Use16Bit, context);

                case O.Md: // r/m refers to memory; dword
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Use32Bit, context);

                case O.Mq:
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Use64Bit, context);

                case O.M14or28b: // r/m refers to memory; 14 or 28 bytes
                    // TODO: we actually need to check the CPU operation mode,
                    // not the operand-size attribute.
                    return DecodeMemoryOperand(
                        reader,
                        RegisterType.None,
                        (context.OperandSize == CpuSize.Use16Bit) ? 
                            CpuSize.Use14Bytes : CpuSize.Use28Bytes,
                        context);

                case O.M32fp: // r/m refers to memory; single-precision float
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Use32Bit, context);

                case O.M64fp: // r/m refers to memory; double-precision float
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Use64Bit, context);

                case O.M80fp: // r/m refers to memory; extended-precision float
                    return DecodeMemoryOperand(reader, RegisterType.None, CpuSize.Use80Bit, context);

                case O.Ob: // absolute address (w/o segment); byte
                    // TODO: check 64-bit mode behavior
                    return new MemoryOperand
                    {
                        Size = CpuSize.Use8Bit,
                        Displacement = reader.ReadImmediate(context.AddressSize),
                        // Segment = Register.DS,
                    };

                case O.Ov: // absolute address (w/o segment); 16, 32, or 64 bit
                    // TODO: check 64-bit mode behavior
                    return new MemoryOperand
                    {
                        Size = context.OperandSize,
                        Displacement = reader.ReadImmediate(context.AddressSize),
                        // Segment = Register.DS,
                    };

                case O.Sw: // REG(modrm) selects segment register
                    return DecodeRegisterOperand(reader, RegisterType.Segment, CpuSize.Use16Bit, context);

                case O.T80fp: // r/m selects x87 FPU register ST0-ST7
                    return CreateRegisterOperand(RegisterType.Fpu, reader.GetModRM().RM, CpuSize.Use80Bit);

                case O.Xb: // memory addressed by DS:rSI; byte
                    return new MemoryOperand
                    {
                        Size = CpuSize.Use8Bit,
                        Segment = Register.DS,
                        Base = Register.SI.Resize(context.AddressSize)
                    };

                case O.Xv: // memory addressed by DS:rSI; 16, 32, or 64 bit
                    return new MemoryOperand
                    {
                        Size = context.OperandSize,
                        Segment = Register.DS,
                        Base = Register.SI.Resize(context.AddressSize)
                    };

                case O.Xz: // memory addressed by DS:rSI; 16 or 32 bit
                    return new MemoryOperand
                    {
                        Size = CpuSize.Use16Bit, // TODO: handle 32 bit
                        Segment = Register.DS,
                        Base = Register.SI.Resize(context.AddressSize)
                    };

                case O.Yb: // memory addressed by ES:rDI; byte
                    return new MemoryOperand
                    {
                        Size = CpuSize.Use8Bit,
                        Segment = Register.ES,
                        Base = Register.DI.Resize(context.AddressSize)
                    };

                case O.Yv: // memory addressed by ES:rDI; 16, 32, or 64 bit
                    return new MemoryOperand
                    {
                        Size = context.OperandSize,
                        Segment = Register.ES,
                        Base = Register.DI.Resize(context.AddressSize)
                    };

                case O.Yz: // memory addressed by ES:rDI; 16 or 32 bit
                    return new MemoryOperand
                    {
                        Size = CpuSize.Use16Bit, // TODO: handle 32 bit
                        Segment = Register.ES,
                        Base = Register.DI.Resize(context.AddressSize)
                    };

                case O._XLAT:
                    return new MemoryOperand
                    {
                        Size = CpuSize.Use8Bit,
                        Segment = context.SegmentOverride,
                        Base = (context.AddressSize == CpuSize.Use16Bit) ?
                            Register.BX : Register.EBX
                    };

                default:
                    throw new NotImplementedException(
                        "DecodeOperand() is not implemented for operand type " + spec.ToString());
            }
        }
Exemplo n.º 25
0
 unsafe public void UseContext(DecoderContext ctx)
 {
     this.ctx     = ctx;
     timebase_den = ctx.CodecCtx->time_base.den;
 }
Exemplo n.º 26
0
        private void TestDecode(
            byte[] image,
            Pointer startAddress,
            Pointer baseAddress)
        {
            DecoderContext options = new DecoderContext();
            options.AddressSize = CpuSize.Use16Bit;
            options.OperandSize = CpuSize.Use16Bit;

            X86Codec.Decoder decoder = new X86Codec.Decoder();

            Pointer ip = startAddress;
            for (int index = startAddress - baseAddress; index < image.Length; )
            {
                Instruction instruction = null;
                try
                {
                    instruction = decoder.Decode(image, index, ip, options);
                }
                catch (InvalidInstructionException ex)
                {
                    if (MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OKCancel)
                        == DialogResult.Cancel)
                    {
                        throw;
                    }
                    break;
                }
            #if false
                // Output address.
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("0000:{0:X4}  ", index - startAddress);

                // Output binary code. */
                for (int i = 0; i < 8; i++)
                {
                    if (i < instruction.EncodedLength)
                        sb.AppendFormat("{0:x2} ", image[index + i]);
                    else
                        sb.Append("   ");
                }

                // Output the instruction.
                string s = instruction.ToString();
                if (s.StartsWith("*"))
                    throw new InvalidOperationException("Cannot format instruction.");
                sb.Append(s);

                System.Diagnostics.Debug.WriteLine(sb.ToString());
            #else
                DisplayInstruction(instruction);
            #endif
                index += instruction.EncodedLength;
                ip += instruction.EncodedLength;
            }
        }
Exemplo n.º 27
0
 public MessageDecoder()
 {
     _context = new DecoderContext {
         ParserMethod = ParseBeforeHeader
     };
 }
Exemplo n.º 28
0
 public void UseContext(DecoderContext ctx)
 {
     this.ctx = ctx;
 }
Exemplo n.º 29
0
 public MessageDecoder()
 {
     _context = new DecoderContext {ParserMethod = ParseBeforeHeader};
 }