/// <summary>
 /// Parses the data for this instance.
 /// </summary>
 /// <param name="data">The data memory reader.</param>
 /// <param name="defaultAddressSize">Default size of the address.</param>
 /// <param name="endPosition">The end position.</param>
 private void ParseData(DwarfMemoryReader data, byte defaultAddressSize, int endPosition)
 {
     Version      = data.ReadByte();
     Augmentation = data.ReadString();
     if (!string.IsNullOrEmpty(Augmentation))
     {
         AddressSize           = 4;
         SegmentSelectorSize   = 0;
         CodeAlignmentFactor   = 0;
         DataAlignmentFactor   = 0;
         ReturnAddressRegister = 0;
     }
     else
     {
         if (Version >= 4)
         {
             AddressSize         = data.ReadByte();
             SegmentSelectorSize = data.ReadByte();
         }
         else
         {
             AddressSize         = defaultAddressSize;
             SegmentSelectorSize = 0;
         }
         CodeAlignmentFactor   = data.LEB128();
         DataAlignmentFactor   = data.LEB128();
         ReturnAddressRegister = data.LEB128();
     }
     InitialInstructions = data.ReadBlock((uint)(endPosition - data.Position));
 }
        /// <summary>
        /// Parses the data for this instance.
        /// </summary>
        /// <param name="data">The data memory reader.</param>
        /// <param name="endPosition">The end position.</param>
        /// <param name="input">The input data for parsing configuration.</param>
        private void ParseData(DwarfMemoryReader data, int endPosition, DwarfExceptionHandlingFrameParsingInput input)
        {
            Version             = data.ReadByte();
            Augmentation        = data.ReadString();
            CodeAlignmentFactor = data.LEB128();
            DataAlignmentFactor = data.SLEB128();
            if (Version == 1)
            {
                ReturnAddressRegister = data.ReadByte();
            }
            else
            {
                ReturnAddressRegister = data.LEB128();
            }
            AddressSize         = input.DefaultAddressSize;
            SegmentSelectorSize = 0;
            int instructionsStart = -1;

            for (int i = 0; i < Augmentation.Length; i++)
            {
                if (Augmentation[i] == 'z')
                {
                    uint length = data.LEB128();

                    instructionsStart = data.Position + (int)length;
                }
                else if (Augmentation[i] == 'L')
                {
                    LanguageSpecificDataAreaEncoding = (DwarfExceptionHandlingEncoding)data.ReadByte();
                }
                else if (Augmentation[i] == 'R')
                {
                    FrameDescriptionAddressEncoding = (DwarfExceptionHandlingEncoding)data.ReadByte();
                }
                else if (Augmentation[i] == 'S')
                {
                    StackFrame = true;
                }
                else if (Augmentation[i] == 'P')
                {
                    PersonalityEncoding = (DwarfExceptionHandlingEncoding)data.ReadByte();
                    PersonalityLocation = ReadEncodedAddress(data, PersonalityEncoding, input);
                }
                else
                {
                    break;
                }
            }
            if (instructionsStart >= 0)
            {
                data.Position = instructionsStart;
            }
            InitialInstructions = data.ReadBlock((uint)(endPosition - data.Position));
        }
Exemple #3
0
            /// <summary>
            /// Gets the debug data description for the specified code.
            /// </summary>
            /// <param name="findCode">The code to be found.</param>
            public DataDescription GetDebugDataDescription(uint findCode)
            {
                DataDescription result;

                if (readDescriptions.TryGetValue(findCode, out result))
                {
                    return(result);
                }

                debugDataDescription.Position = lastReadPosition;
                while (!debugDataDescription.IsEnd)
                {
                    uint     code        = debugDataDescription.LEB128();
                    DwarfTag tag         = (DwarfTag)debugDataDescription.LEB128();
                    bool     hasChildren = debugDataDescription.ReadByte() != 0;
                    List <DataDescriptionAttribute> attributes = new List <DataDescriptionAttribute>();

                    while (!debugDataDescription.IsEnd)
                    {
                        DwarfAttribute attribute = (DwarfAttribute)debugDataDescription.LEB128();
                        DwarfFormat    format    = (DwarfFormat)debugDataDescription.LEB128();

                        while (format == DwarfFormat.Indirect)
                        {
                            format = (DwarfFormat)debugDataDescription.LEB128();
                        }

                        if (attribute == DwarfAttribute.None && format == DwarfFormat.None)
                        {
                            break;
                        }

                        attributes.Add(new DataDescriptionAttribute()
                        {
                            Attribute = attribute,
                            Format    = format,
                        });
                    }

                    result = new DataDescription()
                    {
                        Tag         = tag,
                        HasChildren = hasChildren,
                        Attributes  = attributes,
                    };
                    readDescriptions.Add(code, result);
                    if (code == findCode)
                    {
                        lastReadPosition = debugDataDescription.Position;
                        return(result);
                    }
                }

                throw new NotImplementedException();
            }
Exemple #4
0
        /// <summary>
        /// Reads the data for single instance.
        /// </summary>
        /// <param name="debugLine">The debug line data stream.</param>
        /// <param name="addressNormalizer">Normalize address delegate (<see cref="NormalizeAddressDelegate"/>)</param>
        /// <returns>List of file information.</returns>
        private static List <DwarfFileInformation> ReadData(DwarfMemoryReader debugLine, NormalizeAddressDelegate addressNormalizer)
        {
            // Read header
            bool   is64bit;
            int    beginPosition            = debugLine.Position;
            ulong  length                   = debugLine.ReadLength(out is64bit);
            int    endPosition              = debugLine.Position + (int)length;
            ushort version                  = debugLine.ReadUshort();
            int    headerLength             = debugLine.ReadOffset(is64bit);
            byte   minimumInstructionLength = debugLine.ReadByte();
            bool   defaultIsStatement       = debugLine.ReadByte() != 0;
            sbyte  lineBase                 = (sbyte)debugLine.ReadByte();
            byte   lineRange                = debugLine.ReadByte();
            byte   operationCodeBase        = debugLine.ReadByte();

            // Read operation code lengths
            uint[] operationCodeLengths = new uint[operationCodeBase];

            operationCodeLengths[0] = 0;
            for (int i = 1; i < operationCodeLengths.Length && debugLine.Position < endPosition; i++)
            {
                operationCodeLengths[i] = debugLine.LEB128();
            }

            // Read directories
            List <string> directories = new List <string>();

            while (debugLine.Position < endPosition && debugLine.Peek() != 0)
            {
                string directory = debugLine.ReadString();

                directory = directory.Replace('/', Path.DirectorySeparatorChar);
                directories.Add(directory);
            }
            debugLine.ReadByte(); // Skip zero termination byte

            // Read files
            List <DwarfFileInformation> files = new List <DwarfFileInformation>();

            while (debugLine.Position < endPosition && debugLine.Peek() != 0)
            {
                files.Add(ReadFile(debugLine, directories));
            }
            debugLine.ReadByte(); // Skip zero termination byte

            // Parse lines
            ParsingState state       = new ParsingState(files.FirstOrDefault(), defaultIsStatement, minimumInstructionLength);
            uint         lastAddress = 0;

            while (debugLine.Position < endPosition)
            {
                byte operationCode = debugLine.ReadByte();

                if (operationCode >= operationCodeLengths.Length)
                {
                    // Special operation code
                    int adjustedOperationCode = operationCode - operationCodeBase;
                    int operationAdvance      = adjustedOperationCode / lineRange;
                    state.AdvanceAddress(operationAdvance);
                    int lineAdvance = lineBase + (adjustedOperationCode % lineRange);
                    state.Line += (uint)lineAdvance;
                    state.AddCurrentLineInfo();
                    state.IsBasicBlock  = false;
                    state.IsPrologueEnd = false;
                    state.IsEpilogueEnd = false;
                    state.Discriminator = 0;
                }
                else
                {
                    switch ((DwarfLineNumberStandardOpcode)operationCode)
                    {
                    case DwarfLineNumberStandardOpcode.Extended:
                    {
                        uint extendedLength = debugLine.LEB128();
                        int  newPosition    = debugLine.Position + (int)extendedLength;
                        DwarfLineNumberExtendedOpcode extendedCode = (DwarfLineNumberExtendedOpcode)debugLine.ReadByte();

                        switch (extendedCode)
                        {
                        case DwarfLineNumberExtendedOpcode.EndSequence:
                            lastAddress         = state.Address;
                            state.IsSequenceEnd = true;
                            state.AddCurrentLineInfo();
                            state.Reset(files.FirstOrDefault());
                            break;

                        case DwarfLineNumberExtendedOpcode.SetAddress:
                        {
                            state.Address = debugLine.ReadUint();
                            if (state.Address == 0)
                            {
                                state.Address = lastAddress;
                            }
                            state.OperationIndex = 0;
                        }
                        break;

                        case DwarfLineNumberExtendedOpcode.DefineFile:
                            state.File = ReadFile(debugLine, directories);
                            files.Add(state.File);
                            break;

                        case DwarfLineNumberExtendedOpcode.SetDiscriminator:
                            state.Discriminator = debugLine.LEB128();
                            break;

                        default:
                            throw new Exception($"Unsupported DwarfLineNumberExtendedOpcode: {extendedCode}");
                        }
                        debugLine.Position = newPosition;
                    }
                    break;

                    case DwarfLineNumberStandardOpcode.Copy:
                        state.AddCurrentLineInfo();
                        state.IsBasicBlock  = false;
                        state.IsPrologueEnd = false;
                        state.IsEpilogueEnd = false;
                        state.Discriminator = 0;
                        break;

                    case DwarfLineNumberStandardOpcode.AdvancePc:
                        state.AdvanceAddress((int)debugLine.LEB128());
                        break;

                    case DwarfLineNumberStandardOpcode.AdvanceLine:
                        state.Line += debugLine.SLEB128();
                        break;

                    case DwarfLineNumberStandardOpcode.SetFile:
                        state.File = files[(int)debugLine.LEB128() - 1];
                        break;

                    case DwarfLineNumberStandardOpcode.SetColumn:
                        state.Column = debugLine.LEB128();
                        break;

                    case DwarfLineNumberStandardOpcode.NegateStmt:
                        state.IsStatement = !state.IsStatement;
                        break;

                    case DwarfLineNumberStandardOpcode.SetBasicBlock:
                        state.IsBasicBlock = true;
                        break;

                    case DwarfLineNumberStandardOpcode.ConstAddPc:
                        state.AdvanceAddress((255 - operationCodeBase) / lineRange);
                        break;

                    case DwarfLineNumberStandardOpcode.FixedAdvancePc:
                        state.Address       += debugLine.ReadUshort();
                        state.OperationIndex = 0;
                        break;

                    case DwarfLineNumberStandardOpcode.SetPrologueEnd:
                        state.IsPrologueEnd = true;
                        break;

                    case DwarfLineNumberStandardOpcode.SetEpilogueBegin:
                        state.IsEpilogueEnd = true;
                        break;

                    case DwarfLineNumberStandardOpcode.SetIsa:
                        state.Isa = debugLine.LEB128();
                        break;

                    default:
                        throw new Exception($"Unsupported DwarfLineNumberStandardOpcode: {(DwarfLineNumberStandardOpcode)operationCode}");
                    }
                }
            }

            // Fix lines in files...
            foreach (DwarfFileInformation file in files)
            {
                for (int i = 0; i < file.Lines.Count; i++)
                {
                    file.Lines[i].Address = (uint)addressNormalizer(file.Lines[i].Address);
                }
            }
            return(files);
        }
Exemple #5
0
        /// <summary>
        /// Reads the data for this instance.
        /// </summary>
        /// <param name="debugData">The debug data.</param>
        /// <param name="debugDataDescription">The debug data description.</param>
        /// <param name="debugStrings">The debug strings.</param>
        /// <param name="addressNormalizer">Normalize address delegate (<see cref="NormalizeAddressDelegate"/>)</param>
        private void ReadData(DwarfMemoryReader debugData, DwarfMemoryReader debugDataDescription, DwarfMemoryReader debugStrings, NormalizeAddressDelegate addressNormalizer)
        {
            // Read header
            bool   is64bit;
            int    beginPosition = debugData.Position;
            ulong  length        = debugData.ReadLength(out is64bit);
            int    endPosition   = debugData.Position + (int)length;
            ushort version       = debugData.ReadUshort();
            int    debugDataDescriptionOffset = debugData.ReadOffset(is64bit);
            byte   addressSize = debugData.ReadByte();
            DataDescriptionReader dataDescriptionReader = new DataDescriptionReader(debugDataDescription, debugDataDescriptionOffset);

            // Read data
            List <DwarfSymbol>  symbols = new List <DwarfSymbol>();
            Stack <DwarfSymbol> parents = new Stack <DwarfSymbol>();

            while (debugData.Position < endPosition)
            {
                int  dataPosition = debugData.Position;
                uint code         = debugData.LEB128();

                if (code == 0)
                {
                    parents.Pop();
                    continue;
                }

                DataDescription description = dataDescriptionReader.GetDebugDataDescription(code);
                Dictionary <DwarfAttribute, DwarfAttributeValue> attributes = new Dictionary <DwarfAttribute, DwarfAttributeValue>();

                foreach (DataDescriptionAttribute descriptionAttribute in description.Attributes)
                {
                    DwarfAttribute      attribute      = descriptionAttribute.Attribute;
                    DwarfFormat         format         = descriptionAttribute.Format;
                    DwarfAttributeValue attributeValue = new DwarfAttributeValue();

                    switch (format)
                    {
                    case DwarfFormat.Address:
                        attributeValue.Type  = DwarfAttributeValueType.Address;
                        attributeValue.Value = debugData.ReadUlong(addressSize);
                        break;

                    case DwarfFormat.Block:
                        attributeValue.Type  = DwarfAttributeValueType.Block;
                        attributeValue.Value = debugData.ReadBlock(debugData.LEB128());
                        break;

                    case DwarfFormat.Block1:
                        attributeValue.Type  = DwarfAttributeValueType.Block;
                        attributeValue.Value = debugData.ReadBlock(debugData.ReadByte());
                        break;

                    case DwarfFormat.Block2:
                        attributeValue.Type  = DwarfAttributeValueType.Block;
                        attributeValue.Value = debugData.ReadBlock(debugData.ReadUshort());
                        break;

                    case DwarfFormat.Block4:
                        attributeValue.Type  = DwarfAttributeValueType.Block;
                        attributeValue.Value = debugData.ReadBlock(debugData.ReadUint());
                        break;

                    case DwarfFormat.Data1:
                        attributeValue.Type  = DwarfAttributeValueType.Constant;
                        attributeValue.Value = (ulong)debugData.ReadByte();
                        break;

                    case DwarfFormat.Data2:
                        attributeValue.Type  = DwarfAttributeValueType.Constant;
                        attributeValue.Value = (ulong)debugData.ReadUshort();
                        break;

                    case DwarfFormat.Data4:
                        attributeValue.Type  = DwarfAttributeValueType.Constant;
                        attributeValue.Value = (ulong)debugData.ReadUint();
                        break;

                    case DwarfFormat.Data8:
                        attributeValue.Type  = DwarfAttributeValueType.Constant;
                        attributeValue.Value = (ulong)debugData.ReadUlong();
                        break;

                    case DwarfFormat.SData:
                        attributeValue.Type  = DwarfAttributeValueType.Constant;
                        attributeValue.Value = (ulong)debugData.SLEB128();
                        break;

                    case DwarfFormat.UData:
                        attributeValue.Type  = DwarfAttributeValueType.Constant;
                        attributeValue.Value = (ulong)debugData.LEB128();
                        break;

                    case DwarfFormat.String:
                        attributeValue.Type  = DwarfAttributeValueType.String;
                        attributeValue.Value = debugData.ReadString();
                        break;

                    case DwarfFormat.Strp:
                        attributeValue.Type  = DwarfAttributeValueType.String;
                        attributeValue.Value = debugStrings.ReadString(debugData.ReadOffset(is64bit));
                        break;

                    case DwarfFormat.Flag:
                        attributeValue.Type  = DwarfAttributeValueType.Flag;
                        attributeValue.Value = debugData.ReadByte() != 0;
                        break;

                    case DwarfFormat.FlagPresent:
                        attributeValue.Type  = DwarfAttributeValueType.Flag;
                        attributeValue.Value = true;
                        break;

                    case DwarfFormat.Ref1:
                        attributeValue.Type  = DwarfAttributeValueType.Reference;
                        attributeValue.Value = (ulong)debugData.ReadByte() + (ulong)beginPosition;
                        break;

                    case DwarfFormat.Ref2:
                        attributeValue.Type  = DwarfAttributeValueType.Reference;
                        attributeValue.Value = (ulong)debugData.ReadUshort() + (ulong)beginPosition;
                        break;

                    case DwarfFormat.Ref4:
                        attributeValue.Type  = DwarfAttributeValueType.Reference;
                        attributeValue.Value = (ulong)debugData.ReadUint() + (ulong)beginPosition;
                        break;

                    case DwarfFormat.Ref8:
                        attributeValue.Type  = DwarfAttributeValueType.Reference;
                        attributeValue.Value = (ulong)debugData.ReadUlong() + (ulong)beginPosition;
                        break;

                    case DwarfFormat.RefUData:
                        attributeValue.Type  = DwarfAttributeValueType.Reference;
                        attributeValue.Value = (ulong)debugData.LEB128() + (ulong)beginPosition;
                        break;

                    case DwarfFormat.RefAddr:
                        attributeValue.Type  = DwarfAttributeValueType.Reference;
                        attributeValue.Value = (ulong)debugData.ReadOffset(is64bit);
                        break;

                    case DwarfFormat.RefSig8:
                        attributeValue.Type = DwarfAttributeValueType.Invalid;
                        debugData.Position += 8;
                        break;

                    case DwarfFormat.ExpressionLocation:
                        attributeValue.Type  = DwarfAttributeValueType.ExpressionLocation;
                        attributeValue.Value = debugData.ReadBlock(debugData.LEB128());
                        break;

                    case DwarfFormat.SecOffset:
                        attributeValue.Type  = DwarfAttributeValueType.SecOffset;
                        attributeValue.Value = (ulong)debugData.ReadOffset(is64bit);
                        break;

                    default:
                        throw new Exception($"Unsupported DwarfFormat: {format}");
                    }

                    if (attributes.ContainsKey(attribute))
                    {
                        if (attributes[attribute] != attributeValue)
                        {
                            attributes[attribute] = attributeValue;
                        }
                    }
                    else
                    {
                        attributes.Add(attribute, attributeValue);
                    }
                }

                DwarfSymbol symbol = new DwarfSymbol()
                {
                    Tag        = description.Tag,
                    Attributes = attributes,
                    Offset     = dataPosition,
                };

                symbolsByOffset.Add(symbol.Offset, symbol);

                if (parents.Count > 0)
                {
                    parents.Peek().Children.Add(symbol);
                    symbol.Parent = parents.Peek();
                }
                else
                {
                    symbols.Add(symbol);
                }

                if (description.HasChildren)
                {
                    symbol.Children = new List <DwarfSymbol>();
                    parents.Push(symbol);
                }
            }

            SymbolsTree = symbols.ToArray();

            if (SymbolsTree.Length > 0)
            {
                // Add void type symbol
                DwarfSymbol voidSymbol = new DwarfSymbol()
                {
                    Tag        = DwarfTag.BaseType,
                    Offset     = -1,
                    Parent     = SymbolsTree[0],
                    Attributes = new Dictionary <DwarfAttribute, DwarfAttributeValue>()
                    {
                        { DwarfAttribute.Name, new DwarfAttributeValue()
                          {
                              Type = DwarfAttributeValueType.String, Value = "void"
                          } },
                        { DwarfAttribute.ByteSize, new DwarfAttributeValue()
                          {
                              Type = DwarfAttributeValueType.Constant, Value = (ulong)0
                          } },
                    },
                };
                if (SymbolsTree[0].Children == null)
                {
                    SymbolsTree[0].Children = new List <DwarfSymbol>();
                }
                SymbolsTree[0].Children.Insert(0, voidSymbol);
                symbolsByOffset.Add(voidSymbol.Offset, voidSymbol);

                // Post process all symbols
                foreach (DwarfSymbol symbol in Symbols)
                {
                    Dictionary <DwarfAttribute, DwarfAttributeValue> attributes = symbol.Attributes as Dictionary <DwarfAttribute, DwarfAttributeValue>;

                    foreach (DwarfAttributeValue value in attributes.Values)
                    {
                        if (value.Type == DwarfAttributeValueType.Reference)
                        {
                            DwarfSymbol reference;

                            if (symbolsByOffset.TryGetValue((int)value.Address, out reference))
                            {
                                value.Type  = DwarfAttributeValueType.ResolvedReference;
                                value.Value = reference;
                            }
                        }
                        else if (value.Type == DwarfAttributeValueType.Address)
                        {
                            value.Value = addressNormalizer(value.Address);
                        }
                    }

                    if ((symbol.Tag == DwarfTag.PointerType && !attributes.ContainsKey(DwarfAttribute.Type)) ||
                        (symbol.Tag == DwarfTag.Typedef && !attributes.ContainsKey(DwarfAttribute.Type)))
                    {
                        attributes.Add(DwarfAttribute.Type, new DwarfAttributeValue()
                        {
                            Type  = DwarfAttributeValueType.ResolvedReference,
                            Value = voidSymbol,
                        });
                    }
                }

                // Merge specifications
                foreach (DwarfSymbol symbol in Symbols)
                {
                    Dictionary <DwarfAttribute, DwarfAttributeValue> attributes = symbol.Attributes as Dictionary <DwarfAttribute, DwarfAttributeValue>;
                    DwarfAttributeValue specificationValue;

                    if (attributes.TryGetValue(DwarfAttribute.Specification, out specificationValue) && specificationValue.Type == DwarfAttributeValueType.ResolvedReference)
                    {
                        DwarfSymbol reference = specificationValue.Reference;
                        Dictionary <DwarfAttribute, DwarfAttributeValue> referenceAttributes = reference.Attributes as Dictionary <DwarfAttribute, DwarfAttributeValue>;

                        foreach (KeyValuePair <DwarfAttribute, DwarfAttributeValue> kvp in attributes)
                        {
                            if (kvp.Key != DwarfAttribute.Specification)
                            {
                                referenceAttributes[kvp.Key] = kvp.Value;
                            }
                        }
                    }
                }
            }
        }