Пример #1
0
        private void chkConstructor_CheckedChanged(object sender, EventArgs e)
        {
            if (_updating || TargetRelocation == null)
            {
                return;
            }

            if (TargetRelocation == _prologReloc)
            {
                if (!(_prologReloc._prolog = chkConstructor.Checked))
                {
                    _prologReloc = null;
                }
            }
            else
            {
                if (chkConstructor.Checked)
                {
                    if (_prologReloc != null)
                    {
                        _prologReloc._prolog = false;
                    }
                    _prologReloc         = TargetRelocation;
                    _prologReloc._prolog = true;
                }
            }
        }
Пример #2
0
        private void Load(BinaryReaderX reader)
        {
            ModuleHeader = new Header(reader);

            // Initialize Section Entries
            Sections = new Section[ModuleHeader.NumSections];
            reader.Seek(ModuleHeader.SectionInfoOffset);
            for (var i = 0; i < Sections.Length; i++)
            {
                Sections[i]    = new Section(reader);
                Sections[i].Id = i;
            }

            // Initialize Imports & Relocations
            Imports = new Import[ModuleHeader.ImportTableSize / Import.IMPORT_SIZE];
            for (var i = 0; i < Imports.Length; i++)
            {
                reader.Seek(ModuleHeader.ImportTableOffset + i * Import.IMPORT_SIZE);
                Imports[i] = new Import(reader);

                // Load relocations
                var relocations = new List <Relocation>();
                reader.Seek(Imports[i].Offset);
                while (true)
                {
                    var relocation = new Relocation(reader);
                    relocations.Add(relocation);
                    if (relocation.Type == RelocationType.R_DOLPHIN_END)
                    {
                        break;
                    }
                }
                Imports[i].Relocations = relocations.ToArray();
            }
        }
Пример #3
0
        public void ResetTest()
        {
            var     objectFile = new ObjectFileMock();
            Context context    = new Context(objectFile);

            Section section    = new Section("Test");
            var     symbol     = new Symbol(SymbolType.Public, "test");
            var     relocation = new Relocation(symbol, section, 0, 0, RelocationType.Default32);

            context.SymbolTable.Add(symbol);
            context.RelocationTable.Add(relocation);
            context.Section = section;
            context.Address = 123456789;
            Assert.AreEqual(symbol, context.SymbolTable[0]);
            Assert.AreEqual(relocation, context.RelocationTable[0]);
            Assert.AreEqual(section, context.Section);
            Assert.AreEqual((Int128)123456789, context.Address);

            context.Reset();

            // These have not changed
            Assert.AreEqual(symbol, context.SymbolTable[0]);
            Assert.AreEqual(relocation, context.RelocationTable[0]);

            // These are reset
            Assert.AreEqual(null, context.Section);
            Assert.AreEqual((Int128)0, context.Address);
        }
Пример #4
0
        /// <summary>
        /// Checks an import list against the configured ordering and spacing.
        /// </summary>
        /// <param name="holder">The import list container - either a file, or a namespace
        /// declaration block.</param>
        /// <param name="highlights">If the import does not meet the configured requirements,
        /// we allocate a list containing a highlight describing the problem and return
        /// it via this argument. (We allocate the list on demand to avoid allocations
        /// in the happy path in which all the import lists are correctly ordered and
        /// spaced.)</param>
        private void CheckImports(
            ICSharpTypeAndNamespaceHolderDeclaration holder, ref List <HighlightingInfo> highlights)
        {
            List <UsingDirectiveOrSpace>  items = ImportReader.ReadImports(holder);
            List <UsingDirective>         imports;
            List <List <UsingDirective> > requiredOrderByGroups;

            ImportInspector.FlattenImportsAndDetermineOrderAndSpacing(
                _config, items, out imports, out requiredOrderByGroups);

            bool orderIsCorrect = true;

            if (requiredOrderByGroups != null)
            {
                Relocation nextChange = ImportInspector.GetNextUsingToMove(requiredOrderByGroups, imports);
                if (nextChange != null)
                {
                    orderIsCorrect = false;
                    AddHighlight(holder, ref highlights, new UsingOrderHighlighting(holder, _config));
                }
            }

            // If (and only if) the order is correct, we go on to check the spacing.
            if (orderIsCorrect)
            {
                SpaceChange nextChange = ImportInspector.GetNextSpacingModification(requiredOrderByGroups, items);
                if (nextChange != null)
                {
                    AddHighlight(holder, ref highlights, new UsingSpacingHighlighting(holder, _config));
                }
            }
        }
Пример #5
0
    public override void UseProp()
    {
        Relocation relocation = GameMap.GM.relocation;

        relocation.ChangeLevel();
        Debug.Log("EXITUSED");
    }
Пример #6
0
        public bool TryMoveToOtherLoc(int personId, int?fromLocId, int?toLocId)
        {
            bool access;
            var  entity = repo.FindPersonRoomPair(personId, toLocId);

            if (entity == null)
            {
                access = false;
            }
            else
            {
                access = true;
            }
            DateTime dateTime   = DateTime.UtcNow;
            var      relocation = new Relocation
            {
                PersonId    = personId,
                FromLocId   = fromLocId,
                ToLocId     = toLocId,
                DateAndTime = dateTime,
                Success     = access
            };

            repo.AddRelocation(relocation);
            repo.SaveChanges();
            return(access);
        }
Пример #7
0
        private String GetCodeForNodeData(List <NodeDataSection> nodeDataSections, Relocation[] relocs, byte[] byteData, DependencyNode node, int offset, NodeFactory factory)
        {
            CppGenerationBuffer nodeDataDecl = new CppGenerationBuffer();
            int relocCounter       = 0;
            int divisionStartIndex = offset;

            nodeDataDecl.Indent();
            nodeDataDecl.Indent();
            nodeDataDecl.AppendLine();

            for (int i = 0; i < nodeDataSections.Count; i++)
            {
                if (nodeDataSections[i].SectionType == NodeDataSectionType.Relocation)
                {
                    Relocation reloc = relocs[relocCounter];
                    nodeDataDecl.Append(GetCodeForReloc(reloc, node, factory));
                    nodeDataDecl.Append(",");
                    relocCounter++;
                }
                else
                {
                    AppendFormattedByteArray(nodeDataDecl, byteData, divisionStartIndex, divisionStartIndex + nodeDataSections[i].SectionSize);
                    nodeDataDecl.Append(",");
                }
                divisionStartIndex += nodeDataSections[i].SectionSize;
                nodeDataDecl.AppendLine();
            }
            return(nodeDataDecl.ToString());
        }
Пример #8
0
        public void OpenRelocation(Relocation target)
        {
            if (target == null)
            {
                return;
            }

            if (target._section != _section)
            {
                foreach (SectionEditor r in _openedSections)
                {
                    if (r._section == target._section)
                    {
                        r.Position = target._index * 4;
                        r.Focus();
                        r.hexBox1.Focus();
                        return;
                    }
                }

                SectionEditor x = new SectionEditor(target._section as ModuleSectionNode);
                x.Show();

                x.Position = target._index * 4;
                x.hexBox1.Focus();
            }
            else
            {
                Position = target._index * 4;
                hexBox1.Focus();
            }
        }
        /// <summary>
        /// Emits the immediate value as part of the instruction, if any.
        /// </summary>
        /// <param name="writer">The <see cref="BinaryWriter"/> to which the encoded instruction is written.</param>
        /// <param name="instructionOffset">The offset of the instruction in the stream underlying
        /// <paramref name="writer"/>.</param>
        /// <param name="context">The <see cref="Context"/> of the instruction.</param>
        /// <param name="expression">The <see cref="ReferenceOffset"/> to emit.</param>
        /// <param name="size">The size of the value to emit.</param>
        void EmitReferenceOffset(BinaryWriter writer, long instructionOffset, Context context, ReferenceOffset expression, DataSize size)
        {
            if (expression == null)
            {
                return;
            }

            // Number of bytes before the expression.
            var        relocationDiff = (ulong)(writer.BaseStream.Position - instructionOffset);
            Relocation relocation     = null;

            var actualValue = expression.Evaluate(context);

            if (expression.Reference != null)
            {
                relocation = new Relocation(expression.Reference.Symbol, (long)context.Address, actualValue, RelocationType.Default32);
            }

            // Emit the expression's value.
            EmitConstant(writer, size, actualValue);

            // Add the relocation to the context.
            if (relocation != null)
            {
                relocation.Offset += (long)relocationDiff;
                context.RelocationTable.Add(relocation);
            }
        }
Пример #10
0
        private String GetCodeForReloc(Relocation reloc, DependencyNode node, NodeFactory factory)
        {
            CppGenerationBuffer relocCode = new CppGenerationBuffer();

            if (reloc.Target is CppMethodCodeNode)
            {
                var method = reloc.Target as CppMethodCodeNode;

                relocCode.Append("(void*)&");
                relocCode.Append(GetCppMethodDeclarationName(method.Method.OwningType, GetCppMethodName(method.Method), false));
            }
            else if (reloc.Target is EETypeNode && node is EETypeNode)
            {
                relocCode.Append(GetCppMethodDeclarationName((reloc.Target as EETypeNode).Type, "__getMethodTable", false));
                relocCode.Append("()");
            }
            // Node is either an non-emitted type or a generic composition - both are ignored for CPP codegen
            else if ((reloc.Target is TypeManagerIndirectionNode || reloc.Target is InterfaceDispatchMapNode || reloc.Target is EETypeOptionalFieldsNode || reloc.Target is GenericCompositionNode) && !(reloc.Target as ObjectNode).ShouldSkipEmittingObjectNode(factory))
            {
                string mangledTargetName = reloc.Target.GetMangledName(factory.NameMangler);
                bool   shouldReplaceNamespaceQualifier = reloc.Target is GenericCompositionNode || reloc.Target is EETypeOptionalFieldsNode;
                relocCode.Append(shouldReplaceNamespaceQualifier ? mangledTargetName.Replace("::", "_") : mangledTargetName);
                relocCode.Append("()");
            }
            else if (reloc.Target is ObjectAndOffsetSymbolNode &&
                     (reloc.Target as ObjectAndOffsetSymbolNode).Target is ArrayOfEmbeddedPointersNode <InterfaceDispatchMapNode> )
            {
                relocCode.Append("dispatchMapModule");
            }
            else
            {
                relocCode.Append("NULL");
            }
            return(relocCode.ToString());
        }
Пример #11
0
            private void SetSibling()
            {
                if (_sibling != null)
                {
                    return;
                }

                switch (Type)
                {
                case RelocationType.R_MIPS_HI16:
                    break;

                case RelocationType.R_MIPS_LO16:
                    _sibling = _parent.Relocations
                               .Reverse()
                               .SkipWhile(r => r.Location > Location)
                               .First(r => r.Type == RelocationType.R_MIPS_HI16 &&
                                      new Instruction(Data).GprBase == new Instruction(r.Data).GprRt);

                    _sibling._sibling = this;
                    break;

                default:
                    throw new Exception();
                }
            }
Пример #12
0
    void SaveDeathPoint()
    {
        PlayerSaves playerSaves = SaveSystem.instance.saves.playerSaves;
        Relocation  relocation  = GameMap.GM.relocation;
        Vector2     deathPos    = new Vector2(transform.position.x, transform.position.y);

        playerSaves.deathPointData = new DeathPointData(Relocation.CurrentDungeonLevel, deathPos);
    }
Пример #13
0
 public static bool TryLoadLibrary(string path, out IntPtr address, Relocation relocation = Relocation.Now)
 {
     var mode = (int)relocation;
     //HACK: returns 0 on first call, somehow
     dlerror();
     address = dlopen(path, mode);
     return address != IntPtr.Zero;
 }
Пример #14
0
        public static bool TryLoadLibrary(string path, out IntPtr address, Relocation relocation = Relocation.Now)
        {
            var mode = (int)relocation;

            //HACK: returns 0 on first call, somehow
            dlerror();
            address = dlopen(path, mode);
            return(address != IntPtr.Zero);
        }
Пример #15
0
        public void ReportsPositionWhenExpectedSecondItemInWrongPlace()
        {
            var        required = new[] { D1, D2, D3 };
            var        current  = new[] { D1, D3, D2 };
            Relocation result   = OrderChecker.GetNextUsingToMove(required, current);

            Assert.AreEqual(2, result.From, "Source");
            Assert.AreEqual(1, result.To, "Destination");
        }
Пример #16
0
 public DialogResult ShowDialog(Relocation relocation, SectionEditor mainWindow)
 {
     _mainWindow                  = mainWindow;
     _targetRelocation            = relocation;
     oldValue                     = _targetRelocation.RawValue;
     propertyGrid1.SelectedObject = _code = _targetRelocation.Code;
     label3.Text                  = "0x" + (_targetRelocation._index * 4).ToString("X");
     return(base.ShowDialog());
 }
Пример #17
0
 /// <summary>
 /// Loads the given library to memory.
 /// </summary>
 /// <returns>
 /// The address of the loaded library.
 /// </returns>
 /// <param name='path'>
 /// Path to the library file.
 /// </param>
 /// <param name='relocation'>
 /// Whether relocation should be done immediately after loading or being deferred (lazy).
 /// The default option is to relocate immediately.
 /// </param>
 public static IntPtr LoadLibrary(string path, Relocation relocation = Relocation.Now)
 {
     IntPtr address;
     if (!TryLoadLibrary(path, out address, relocation))
     {
         HandleError("opening");
     }
     return address;
 }
Пример #18
0
        /// <summary>
        /// Loads the given library to memory.
        /// </summary>
        /// <returns>
        /// The address of the loaded library.
        /// </returns>
        /// <param name='path'>
        /// Path to the library file.
        /// </param>
        /// <param name='relocation'>
        /// Whether relocation should be done immediately after loading or being deferred (lazy).
        /// The default option is to relocate immediately.
        /// </param>
        public static IntPtr LoadLibrary(string path, Relocation relocation = Relocation.Now)
        {
            IntPtr address;

            if (!TryLoadLibrary(path, out address, relocation))
            {
                HandleError("opening");
            }
            return(address);
        }
Пример #19
0
        private void ObjectRangeRelocation(Address oldBase, Address newBase, uint size)
        {
            Relocation reloc = new Relocation();

            reloc.SourceStart  = oldBase;
            reloc.DiffToTarget = newBase - oldBase;
            reloc.SourceEnd    = oldBase + (ulong)size;

            m_relocs.Add(reloc);
        }
Пример #20
0
 public Color GetStatusColor(Relocation c)
 {
     if (c.Code is PPCblr)
     {
         return(ModuleDataNode.clrBlr);
     }
     if (c.Command == null)
     {
         return(ModuleDataNode.clrNotRelocated);
     }
     return(ModuleDataNode.clrRelocated);
 }
Пример #21
0
 private void FixRelocation(Relocation w, int amt, long offset)
 {
     foreach (Relocation l in w.Linked)
     {
         if (l.Command != null)
         {
             if (l.Command.TargetSectionID == _section.Index && l.Command._addend >= offset)
             {
                 l.Command._addend = (uint)((int)l.Command._addend + amt * 4);
             }
         }
     }
 }
Пример #22
0
 public void StartSession()
 {
     if (PlayerPrefs.HasKey("Save"))
     {
         GameMap.GM.relocation.LoadClosestSavedCheckPoint();
         return;
     }
     else
     {
         Relocation.InitFirstPlayData();
         GameMap.GM.relocation.ChangeLevel();
     }
 }
Пример #23
0
        public void Update(Relocation r)
        {
            if (r == null)
            {
                return;
            }
            int index = _relocations.IndexOf(r);

            if (index < 0)
            {
                return;
            }
            UpdateRow(index);
        }
Пример #24
0
        private String GetCodeForNodeData(List <NodeDataSection> nodeDataSections, Relocation[] relocs, byte[] byteData, DependencyNode node, int offset)
        {
            CppGenerationBuffer nodeDataDecl = new CppGenerationBuffer();
            int relocCounter       = 0;
            int divisionStartIndex = offset;

            nodeDataDecl.Indent();
            nodeDataDecl.AppendLine();

            for (int i = 0; i < nodeDataSections.Count; i++)
            {
                nodeDataDecl.Indent();

                if (nodeDataSections[i].SectionType == NodeDataSectionType.Relocation)
                {
                    Relocation reloc = relocs[relocCounter];
                    if (reloc.Target is CppMethodCodeNode)
                    {
                        var method = reloc.Target as CppMethodCodeNode;

                        nodeDataDecl.Append("(void*)&");
                        nodeDataDecl.Append(GetCppMethodDeclarationName(method.Method.OwningType, GetCppMethodName(method.Method)));
                        nodeDataDecl.Append(",");
                    }
                    else if (reloc.Target is EETypeNode && node is EETypeNode && _emittedTypes.Contains((reloc.Target as EETypeNode).Type))
                    {
                        nodeDataDecl.Append(GetCppMethodDeclarationName((reloc.Target as EETypeNode).Type, "__getMethodTable"));
                        nodeDataDecl.Append("(),");
                    }
                    else
                    {
                        // TODO Add support for other relocs
                        nodeDataDecl.Append("NULL,");
                    }
                    relocCounter++;
                }
                else
                {
                    AppendFormattedByteArray(nodeDataDecl, byteData, divisionStartIndex, divisionStartIndex + nodeDataSections[i].SectionSize);
                    nodeDataDecl.Append(",");
                }
                divisionStartIndex += nodeDataSections[i].SectionSize;
                nodeDataDecl.AppendLine();
                nodeDataDecl.Exdent();
            }
            return(nodeDataDecl.ToString());
        }
Пример #25
0
        public SectionEditor(ModuleSectionNode section)
        {
            InitializeComponent();

            ppcDisassembler1._editor = this;

            if ((_section = section) != null)
            {
                _section._linkedEditor = this;

                Relocation[] temp = new Relocation[_section._relocations.Count];
                _section._relocations.CopyTo(temp);
                _relocations  = temp.ToList();
                _firstCommand = _section._firstCommand;
            }
            _openedSections.Add(this);

            Text = String.Format("Module Section Editor - {0}", _section.Name);

            hexBox1.SectionEditor  = this;
            chkCodeSection.Checked = _section._isCodeSection;
            chkBSSSection.Checked  = _section._isBSSSection;

            if (section.Root is RELNode)
            {
                RELNode r = (RELNode)section.Root;
                if (r._prologReloc != null && r._prologReloc._section == section)
                {
                    _prologReloc = r._prologReloc;
                }
                if (r._epilogReloc != null && r._epilogReloc._section == section)
                {
                    _epilogReloc = r._epilogReloc;
                }
                if (r._unresReloc != null && r._unresReloc._section == section)
                {
                    _unresReloc = r._unresReloc;
                }
                //if (r._nameReloc != null && r._nameReloc._section == section)
                //    _nameReloc = r._nameReloc;
            }

            panel5.Enabled = true;
        }
Пример #26
0
        /// <summary>
        /// Fixes the order of the using directives in a given file or namespace block
        /// to match the specified configuration.
        /// </summary>
        /// <param name="holder">The file or namespace block in which to fix the order
        /// of using directives (if any are present).</param>
        /// <param name="configuration">The configuration determining the correct order.</param>
        public static void FixOrder(
            ICSharpTypeAndNamespaceHolderDeclaration holder,
            OrderUsingsConfiguration configuration)
        {
            // The reordering proceeds one item at a time, so we just keep reapplying it
            // until there's nothing left to do.
            // To avoid hanging VS in the event that an error in the logic causes the
            // sequence of modifications not to terminate, we ensure we don't try to
            // apply more changes than there are using directives.
            int tries     = 0;
            int itemCount = 0;

            while (tries == 0 || tries <= itemCount)
            {
                List <UsingDirectiveOrSpace>  items = ImportReader.ReadImports(holder);
                List <UsingDirective>         imports;
                List <List <UsingDirective> > requiredOrderByGroups;
                ImportInspector.FlattenImportsAndDetermineOrderAndSpacing(
                    configuration, items, out imports, out requiredOrderByGroups);

                if (requiredOrderByGroups == null)
                {
                    break;
                }

                itemCount = imports.Count;
                Relocation nextChange = ImportInspector.GetNextUsingToMove(requiredOrderByGroups, imports);
                if (nextChange != null)
                {
                    IUsingDirective toMove = holder.Imports[nextChange.From];
                    IUsingDirective before = holder.Imports[nextChange.To];
                    holder.RemoveImport(toMove);
                    holder.AddImportBefore(toMove, before);
                    tries += 1;
                }
                else
                {
                    break;
                }
            }
        }
Пример #27
0
        public override int Read(FileStream stream)
        {
            relocations.Empty();

            int        bytesRead = base.Read(stream);
            uint       offset    = 0;
            Relocation currRelocation;

            while (offset < bytesRead)
            {
                currRelocation = new Relocation();

                currRelocation.Offset = (byte *)ByteConverter.ToUInt32(data, offset + 0);
                currRelocation.Info   = ByteConverter.ToUInt32(data, offset + 4);

                relocations.Add(currRelocation);

                offset += header.EntrySize;
            }

            return(relocations.Count);
        }
Пример #28
0
        /// <summary>
        /// Emits the immediate value as part of the instruction, if any.
        /// </summary>
        /// <param name="writer">The <see cref="BinaryWriter"/> to which the encoded instruction is written.</param>
        /// <param name="instructionOffset">The offset of the instruction in the stream underlying
        /// <paramref name="writer"/>.</param>
        /// <param name="context">The <see cref="Context"/> of the instruction.</param>
        /// <param name="expression">The <see cref="SimpleExpression"/> to emit.</param>
        /// <param name="size">The size of the value to emit.</param>
        private void EmitSimpleExpression(BinaryWriter writer, long instructionOffset, Context context, SimpleExpression expression, DataSize size)
        {
            #region Contract
            Contract.Requires <ArgumentNullException>(writer != null);
            Contract.Requires <ArgumentNullException>(context != null);
            Contract.Requires <InvalidEnumArgumentException>(Enum.IsDefined(typeof(DataSize), size));
            #endregion

            if (expression == null)
            {
                return;
            }

            // Number of bytes before the expression.
            ulong      relocationDiff = (ulong)(writer.BaseStream.Position - instructionOffset);
            Relocation relocation     = null;

            Int128 actualValue = expression.Evaluate(context);
            if (expression.Reference != null)
            {
                relocation = new Relocation(
                    expression.Reference.Symbol,
                    context.Section,
                    context.Address,
                    actualValue,
                    RelocationType.Default32);
            }

            // Emit the expression's value.
            EmitConstant(writer, size, actualValue);

            // Add the relocation to the context.
            if (relocation != null)
            {
                relocation.Offset += relocationDiff;
                context.RelocationTable.Add(relocation);
            }
        }
Пример #29
0
        public bool TryMoveToOtherLoc(string cardKey, int readerId)
        {
            bool access = true;
            var  reader = repo.GetReaderById(readerId);

            if (reader == null)
            {
                return(false);
            }
            var person = repo.GetPersonByCardNum(cardKey);

            if (person == null)
            {
                return(false);
            }
            if (reader.NextLocId != null)
            {
                var entity = repo.FindPersonRoomPair(person.Id, reader.NextLocId);
                if (entity == null)
                {
                    access = false;
                }
            }
            DateTime dateTime   = DateTime.UtcNow;
            var      relocation = new Relocation
            {
                PersonId    = person.Id,
                FromLocId   = reader.CurrentLocId,
                ToLocId     = reader.NextLocId,
                DateAndTime = dateTime,
                Success     = access
            };

            repo.AddRelocation(relocation);
            repo.SaveChanges();
            return(access);
        }
Пример #30
0
        /// <summary>
        /// Emit the .reloc section based on file relocation information in the individual blocks.
        /// We rely on the fact that the .reloc section is emitted last so that, by the time
        /// it's getting serialized, all other sections that may contain relocations have already
        /// been laid out.
        /// </summary>
        private BlobBuilder SerializeRelocationSection(SectionLocation sectionLocation)
        {
            // There are 12 bits for the relative offset
            const int RelocationTypeShift      = 12;
            const int MaxRelativeOffsetInBlock = (1 << RelocationTypeShift) - 1;

            // Even though the format doesn't dictate it, it seems customary
            // to align the base RVA's on 4K boundaries.
            const int BaseRVAAlignment = 1 << RelocationTypeShift;

            BlobBuilder   builder         = new BlobBuilder();
            int           baseRVA         = 0;
            List <ushort> offsetsAndTypes = null;

            Section relocSection = FindSection(R2RPEBuilder.RelocSectionName);

            if (relocSection != null)
            {
                relocSection.FilePosWhenPlaced = sectionLocation.PointerToRawData;
                relocSection.RVAWhenPlaced     = sectionLocation.RelativeVirtualAddress;
                builder = relocSection.Content;
            }

            // Traverse relocations in all sections in their RVA order
            // By now, all "normal" sections with relocations should already have been laid out
            foreach (Section section in _sections.OrderBy((sec) => sec.RVAWhenPlaced))
            {
                foreach (PlacedObjectData placedObjectData in section.PlacedObjectDataToRelocate)
                {
                    for (int relocIndex = 0; relocIndex < placedObjectData.Relocs.Length; relocIndex++)
                    {
                        RelocType relocType     = placedObjectData.Relocs[relocIndex].RelocType;
                        RelocType fileRelocType = Relocation.GetFileRelocationType(relocType);
                        if (fileRelocType != RelocType.IMAGE_REL_BASED_ABSOLUTE)
                        {
                            int relocationRVA = section.RVAWhenPlaced + placedObjectData.Offset + placedObjectData.Relocs[relocIndex].Offset;
                            if (offsetsAndTypes != null && relocationRVA - baseRVA > MaxRelativeOffsetInBlock)
                            {
                                // Need to flush relocation block as the current RVA is too far from base RVA
                                FlushRelocationBlock(builder, baseRVA, offsetsAndTypes);
                                offsetsAndTypes = null;
                            }
                            if (offsetsAndTypes == null)
                            {
                                // Create new relocation block
                                baseRVA         = relocationRVA & -BaseRVAAlignment;
                                offsetsAndTypes = new List <ushort>();
                            }
                            ushort offsetAndType = (ushort)(((ushort)fileRelocType << RelocationTypeShift) | (relocationRVA - baseRVA));
                            offsetsAndTypes.Add(offsetAndType);
                        }
                    }
                }
            }

            if (offsetsAndTypes != null)
            {
                FlushRelocationBlock(builder, baseRVA, offsetsAndTypes);
            }

            _relocationDirectoryEntry = new DirectoryEntry(sectionLocation.RelativeVirtualAddress, builder.Count);

            return(builder);
        }
Пример #31
0
        /// <summary>
        /// Add an ObjectData block to a given section.
        /// </summary>
        /// <param name="data">Block to add</param>
        /// <param name="sectionIndex">Section index</param>
        /// <param name="name">Node name to emit in the map file</param>
        /// <param name="mapFileBuilder">Optional map file to emit</param>
        public void AddObjectData(ObjectNode.ObjectData objectData, int sectionIndex, string name, MapFileBuilder mapFileBuilder)
        {
            Section section = _sections[sectionIndex];

            // Calculate alignment padding - apparently ObjectDataBuilder can produce an alignment of 0
            int alignedOffset = section.Content.Count;

            if (objectData.Alignment > 1)
            {
                alignedOffset = (section.Content.Count + objectData.Alignment - 1) & -objectData.Alignment;
                int padding = alignedOffset - section.Content.Count;
                if (padding > 0)
                {
                    if ((section.Characteristics & SectionCharacteristics.ContainsCode) != 0)
                    {
                        uint cp = _codePadding;
                        while (padding >= sizeof(uint))
                        {
                            section.Content.WriteUInt32(cp);
                            padding -= sizeof(uint);
                        }
                        if (padding >= 2)
                        {
                            section.Content.WriteUInt16(unchecked ((ushort)cp));
                            cp >>= 16;
                        }
                        if ((padding & 1) != 0)
                        {
                            section.Content.WriteByte(unchecked ((byte)cp));
                        }
                    }
                    else
                    {
                        section.Content.WriteBytes(0, padding);
                    }
                }
            }

            if (mapFileBuilder != null)
            {
                MapFileNode node = new MapFileNode(sectionIndex, alignedOffset, objectData.Data.Length, name);
                mapFileBuilder.AddNode(node);
                if (objectData.Relocs != null)
                {
                    foreach (Relocation reloc in objectData.Relocs)
                    {
                        RelocType fileReloc = Relocation.GetFileRelocationType(reloc.RelocType);
                        if (fileReloc != RelocType.IMAGE_REL_BASED_ABSOLUTE)
                        {
                            mapFileBuilder.AddRelocation(node, fileReloc);
                        }
                    }
                }
            }

            section.Content.WriteBytes(objectData.Data);

            if (objectData.DefinedSymbols != null)
            {
                foreach (ISymbolDefinitionNode symbol in objectData.DefinedSymbols)
                {
                    if (mapFileBuilder != null)
                    {
                        Utf8StringBuilder sb = new Utf8StringBuilder();
                        symbol.AppendMangledName(GetNameMangler(), sb);
                        int sectionRelativeOffset = alignedOffset + symbol.Offset;
                        mapFileBuilder.AddSymbol(new MapFileSymbol(sectionIndex, sectionRelativeOffset, sb.ToString()));
                    }
                    _symbolMap.Add(symbol, new SymbolTarget(
                                       sectionIndex: sectionIndex,
                                       offset: alignedOffset + symbol.Offset,
                                       size: objectData.Data.Length));
                }
            }

            if (objectData.Relocs != null && objectData.Relocs.Length != 0)
            {
                section.PlacedObjectDataToRelocate.Add(new PlacedObjectData(alignedOffset, objectData));
            }
        }
Пример #32
0
 public void AddRelocation(Relocation relocation)
 {
     db.Relocations.Add(relocation);
 }
Пример #33
0
        public override int Read(FileStream stream)
        {
            relocations.Empty();

            int bytesRead = base.Read(stream);
            uint offset = 0;
            Relocation currRelocation;
            while (offset < bytesRead)
            {
                currRelocation = new Relocation();

                currRelocation.Offset = (byte*)ByteConverter.ToUInt32(data, offset + 0);
                currRelocation.Info = ByteConverter.ToUInt32(data, offset + 4);
                
                relocations.Add(currRelocation);

                offset += header.EntrySize;
            }

            return relocations.Count;
        }