Exemple #1
0
        public void Save(AsmContext context, Stream stream)
        {
            var file = new ElfFile();
            var writer = new BinaryWriter(stream);
            file.Sections.Add(new ElfSection());
            AddCode(file, context);
            AddData(file, context);
            AddFlash(file, context);
            AddDebugLine(file, context);

            var sectionsStringsIndex = file.AddStringsSection();

            const int headerSize = 0x34;
            const int segmentsOffset = headerSize;
            const int segmentEntrySize = 0x20;
            var dataOffset = (uint)(segmentsOffset + file.Segments.Count * segmentEntrySize);
            var sectionsOffset = dataOffset + file.Data.Length;
            var header = new ElfHeader {
                Identification = {
                    Magic = new[] { (char)0x7f, 'E', 'L', 'F' },
                    FileClass = ElfFileClass.Elf32,
                    DataType = ElfDataType.Lsb,
                    Version = 1,
                },
                Type = ElfType.Executable,
                Machine = 0x53,
                Version = 1,
                Entry = 0x0,
                ProgramHeaderOffset = segmentsOffset,
                SectionHeaderOffset = (uint)sectionsOffset,
                Flags = 0x84,
                ElfHeaderSize = headerSize,
                ProgramHeaderEntrySize = segmentEntrySize,
                ProgramHeaderCount = (ushort)file.Segments.Count,
                SectionHeaderEntrySize = 0x28,
                SectionHeaderCount = (ushort)file.Sections.Count,
                StringSectionIndex = (ushort)sectionsStringsIndex
            };
            writer.WriteElf32(header);
            foreach (var segment in file.Segments) {
                var cloned = segment;
                cloned.Offset += dataOffset;
                writer.WriteElf32(cloned);
            }
            writer.Write(file.Data.ToArray());
            foreach (var section in file.Sections) {
                var cloned = section;
                if (section.Type != ElfSectionType.Null) {
                    cloned.Offset += dataOffset;
                }
                writer.WriteElf32(cloned);
            }
        }