private static (string soName, IList <string> depends) Process64BitElfFile(ELF <ulong> elf) { var dynamicSection = elf.GetSections <DynamicSection <ulong> >().FirstOrDefault(); if (dynamicSection == null) { throw new Exception($"Unable to process the ELF file '{elf}' as it does not have a Dynamic Section."); } var stringTableEntry = dynamicSection.Entries.FirstOrDefault(x => x.Tag == DynamicTag.StrTab); if (stringTableEntry == null) { throw new Exception($"Unable to process the ELF file '{elf}' as it does not have a Dynamic String Table."); } var dynStringTable = elf.GetSections <StringTable <ulong> >().FirstOrDefault(x => x.Offset == stringTableEntry.Value); var soNameEntry = dynamicSection.Entries.FirstOrDefault(x => x.Tag == DynamicTag.SoName); var neededEntries = dynamicSection.Entries.Where(x => x.Tag == DynamicTag.Needed); var soName = soNameEntry != null ? dynStringTable[(long)soNameEntry.Value] : null; var needed = neededEntries.Select(x => dynStringTable[(long)x.Value]).ToList(); return(soName, needed); }
/// <summary> /// Initializes a new instance of the <see cref="ElfImage"/> class. /// </summary> /// <param name="path">The image path.</param> /// <param name="loadOffset">Offset from where image was loaded.</param> public ElfImage(string path, ulong loadOffset = 0) { elf = ELFReader.Load <ulong>(path); LoadOffset = loadOffset; foreach (var segment in elf.Segments) { if (segment.Type == ELFSharp.ELF.Segments.SegmentType.ProgramHeader) { CodeSegmentOffset = segment.Address - (ulong)segment.Offset; break; } } List <PublicSymbol> publicSymbols = new List <PublicSymbol>(); SymbolTable <ulong> symbols = elf.Sections.FirstOrDefault(s => s.Type == SectionType.SymbolTable) as SymbolTable <ulong>; if (symbols == null || !symbols.Entries.Any()) { symbols = elf.Sections.FirstOrDefault(s => s.Type == SectionType.DynamicSymbolTable) as SymbolTable <ulong>; } if (symbols != null) { foreach (SymbolEntry <ulong> symbol in symbols.Entries) { publicSymbols.Add(new PublicSymbol(symbol.Name, symbol.Value - CodeSegmentOffset)); } } PublicSymbols = publicSymbols; }
internal SymbolTable(SectionHeader header, Func <EndianBinaryReader> readerSource, IStringTable table, ELF <T> elf) : base(header, readerSource) { this.table = table; this.elf = elf; ReadSymbols(); }
/// <summary> /// Loads the symbols from ELF and puts the symbols into the SymbolLookup. /// </summary> /// <param name="elf">Elf.</param> public void LoadELF(ELF <TAddress> elf, bool useVirtualAddress) { Section <uint> symtabSection; if (!elf.TryGetSection(".symtab", out symtabSection)) { return; } var symtab = (SymbolTable <uint>)symtabSection; var thumb = elf.Machine == ELFSharp.ELF.Machine.ARM; var elfSymbols = symtab.Entries.Where(x => !armSpecificSymbolNames.Contains(x.Name)).Where(x => !excludedSymbolTypes.Contains(x.Type)).Select(x => new Symbol(x, thumb)); InsertSymbols(elfSymbols); EntryPoint = elf.EntryPoint; var segments = elf.Segments.Where(x => x.Type == ELFSharp.ELF.Segments.SegmentType.Load); foreach (var segment in segments) { var loadAddress = useVirtualAddress ? segment.Address : segment.PhysicalAddress; if (maxLoadAddress > loadAddress + segment.Size) { maxLoadAddress = loadAddress + segment.Size; } } }
/// <summary> /// Initializes a new instance of the <see cref="ElfImage"/> class. /// </summary> /// <param name="path">The image path.</param> /// <param name="loadOffset">Offset from where image was loaded.</param> public ElfImage(string path, ulong loadOffset = 0) { elf = ELFReader.Load <ulong>(path); LoadOffset = loadOffset; foreach (var segment in elf.Segments) { if (segment.Type == ELFSharp.ELF.Segments.SegmentType.ProgramHeader) { CodeSegmentOffset = segment.Address - (ulong)segment.Offset; break; } } List <PublicSymbol> publicSymbols = new List <PublicSymbol>(); SymbolTable <ulong> symbols = elf.Sections.FirstOrDefault(s => s.Type == SectionType.SymbolTable) as SymbolTable <ulong>; if (symbols == null || !symbols.Entries.Any()) { symbols = elf.Sections.FirstOrDefault(s => s.Type == SectionType.DynamicSymbolTable) as SymbolTable <ulong>; } if (symbols != null) { foreach (SymbolEntry <ulong> symbol in symbols.Entries) { publicSymbols.Add(new PublicSymbol(symbol.Name, symbol.Value - CodeSegmentOffset)); } } PublicSymbols = publicSymbols; sectionRegions = SimpleCache.Create(() => elf.Sections.Where(s => s.LoadAddress > 0).OrderBy(s => s.LoadAddress).ToArray()); sectionRegionFinder = SimpleCache.Create(() => new MemoryRegionFinder(sectionRegions.Value.Select(s => new MemoryRegion { BaseAddress = s.LoadAddress, RegionSize = s.Size }).ToArray())); }
private void LoadELF <T>(ELF <T> elf, bool useVirtualAddress) where T : struct { if (!elf.TryGetSection(".symtab", out var symtabSection)) { return; } var thumb = elf.Machine == ELFSharp.ELF.Machine.ARM; var symtab = (SymbolTable <T>)symtabSection; var elfSymbols = symtab.Entries.Where(x => !armSpecificSymbolNames.Contains(x.Name)).Where(x => !excludedSymbolTypes.Contains(x.Type)) .Where(x => x.PointedSectionIndex != (uint)SpecialSectionIndex.Undefined).Select(x => new Symbol(x, thumb)); InsertSymbols(elfSymbols); EntryPoint = elf.GetEntryPoint(); FirstNotNullSectionAddress = elf.Sections .Where(x => x.Type != SectionType.Null && x.Flags.HasFlag(SectionFlags.Allocatable)) .Select(x => x.GetSectionPhysicalAddress()) .Cast <ulong?>() .Min(); var segments = elf.Segments.Where(x => x.Type == ELFSharp.ELF.Segments.SegmentType.Load).OfType <ELFSharp.ELF.Segments.Segment <T> >(); foreach (var segment in segments) { var loadAddress = useVirtualAddress ? segment.GetSegmentAddress() : segment.GetSegmentPhysicalAddress(); maxLoadAddress = SymbolAddress.Max(maxLoadAddress, loadAddress + segment.GetSegmentSize()); } }
static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: ReadElf <elf file>"); return; } string elfFilename = args[0]; using (FileStream strm = new FileStream(elfFilename, FileMode.Open)) { ELF elfHeader = new ELF(); byte[] data = new byte[Marshal.SizeOf(elfHeader)]; // Read ELF header data strm.Read(data, 0, data.Length); // Convert to struct elfHeader = ByteArrayToStructure <ELF>(data); Console.WriteLine("Entry point: " + elfHeader.e_entry.ToString("X4")); Console.WriteLine("Number of program header entries: " + elfHeader.e_phnum); // Read first program header entry strm.Seek(elfHeader.e_phoff, SeekOrigin.Begin); data = new byte[elfHeader.e_phentsize]; strm.Read(data, 0, (int)elfHeader.e_phentsize); // Now, do something with it ... see cppreadelf for a hint } }
public static IEnumerable <AssembledInstruction> GetAllocatableData(this ELF <uint> self) { var properSegments = self.Segments .Select((x, i) => { var delta = self.EntryPoint - x.Address; if (i == 0) { return new { Address = x.Address + delta, LoadAddress = x.PhysicalAddress + delta, Size = x.Size - delta } } ; return(new { x.Address, LoadAddress = x.PhysicalAddress, Size = x.Size }); }) .ToArray(); var withData = properSegments .SelectMany(x => self.Sections .Where(y => y.Type == ELFSharp.ELF.Sections.SectionType.ProgBits) .Where(y => y.Flags.HasFlag(ELFSharp.ELF.Sections.SectionFlags.Allocatable)) .Where(y => y.LoadAddress >= x.Address && y.LoadAddress < x.Address + x.Size) .SelectMany(y => y.GetContents().ToWords() .Select(z => (uint)IPAddress.NetworkToHostOrder((int)z)) .Select((z, i) => new { Ram = y.LoadAddress + (uint)i * 4, Rom = y.LoadAddress - x.Address + x.LoadAddress + (uint)i * 4, Word = z }) )) .ToArray(); return(withData .Select(x => new AssembledInstruction(x.Rom, x.Ram, x.Word))); }
/// <summary> /// Initializes a new instance of the <see cref="ElfCoreDump"/> class. /// </summary> /// <param name="coreDumpPath">The core dump path.</param> public ElfCoreDump(string coreDumpPath) { elf = ELFReader.Load <ulong>(coreDumpPath); if (elf.Type != FileType.Core) { throw new Exception($"Expected core dump, but got: {elf.Type}"); } switch (elf.Machine) { case Machine.Intel386: instance = new Intel386Instance(elf); break; case Machine.AMD64: instance = new AMD64Instance(elf); break; default: throw new Exception($"Unsupported machine type: {elf.Machine}"); } Path = coreDumpPath; foreach (var segment in elf.Segments) { if (segment.Type == SegmentType.Note) { DwarfMemoryReader reader = new DwarfMemoryReader(ReadSegment(segment)); int noteStructSize = Marshal.SizeOf <elf_32note>(); while (reader.Position + noteStructSize < reader.Data.Length) { // Read note elf_32note note = reader.ReadStructure <elf_32note>(); int nameEnd = reader.Position + (int)note.NameSize; // Check if note is available to be read if (nameEnd + note.n_descsz > reader.Data.Length) { break; } // Read name and content string name = reader.ReadString(); reader.Position = nameEnd; byte[] content = reader.ReadBlock(note.n_descsz); instance.ProcessNote(name, content, note.n_type); if (note.n_type == elf_note_type.File) { DwarfMemoryReader data = new DwarfMemoryReader(content); files = elf_note_file.Parse(data, Is64bit); } } } } DumpFileMemoryReader = new CoreDumpReader(coreDumpPath, elf.Segments.Where(s => s.Type == SegmentType.Load)); }
public static void Run() { while (true) { try { //BTC.Do(); BCH.Do(); ETH.Do(); ETC.Do(); LTC.Do(); EOS.Do(); XRP.Do(); OMG.Do(); DASH.Do(); ZEC.Do(); Thread.Sleep(1000 * 5); // 创新 ITC.Do(); NAS.Do(); RUFF.Do(); ZIL.Do(); DTA.Do(); Thread.Sleep(1000 * 5); LET.Do(); HT.Do(); THETA.Do(); HSR.Do(); QTUM.Do(); Thread.Sleep(1000 * 5); SNT.Do(); IOST.Do(); NEO.Do(); STORJ.Do(); GNT.Do(); Thread.Sleep(1000 * 5); CVC.Do(); SMT.Do(); VEN.Do(); ELF.Do(); XEM.Do(); Thread.Sleep(1000 * 5); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public SymbolEntry(string name, T value, T size, SymbolBinding binding, SymbolType type, ELF <T> elf, ushort sectionIdx) { Name = name; Value = value; Size = size; Binding = binding; Type = type; this.elf = elf; PointedSectionIndex = sectionIdx; }
public void Create() { MItDag jointIterator = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kJoint); //Create Joints and collect their DAG Paths short jointID = 0; for (; !jointIterator.isDone; jointIterator.next()) { MFnIkJoint ikJoint = new MFnIkJoint(); MDagPath jointDagPath = new MDagPath(); jointIterator.getPath(jointDagPath); this.JointDagPaths.Add(jointDagPath); ikJoint.setObject(jointDagPath); MTransformationMatrix local = new MTransformationMatrix(ikJoint.transformationMatrix); MTransformationMatrix inverseGlobal = new MTransformationMatrix(jointDagPath.inclusiveMatrixInverse); this.Joints.Add(new SKLJoint(jointID, ikJoint.name, local, inverseGlobal)); this.JointIndices.Add(ELF.Hash(ikJoint.name), jointID); jointID++; } //Set Joint parents for (int i = 0; i < this.Joints.Count; i++) { MFnIkJoint ikJoint = new MFnIkJoint(this.JointDagPaths[i]); if (ikJoint.parentCount == 1 && ikJoint.parent(0).apiType == MFn.Type.kJoint) { MFnIkJoint parentJoint = new MFnIkJoint(ikJoint.parent(0)); MDagPath parentDagPath = new MDagPath(); parentJoint.getPath(parentDagPath); //Find index of parent for (int j = 0; j < this.JointDagPaths.Count; j++) { if (parentDagPath.equalEqual(this.JointDagPaths[j])) { this.Joints[i].ParentID = (short)j; } } } else { this.Joints[i].ParentID = -1; } } MGlobal.displayInfo("SKLFile:Create - Created SKL File"); }
public ElfRunner(string filename) { // todo: hack up this baby to take Streams _elf = ELFReader.Load <long>(filename); var loadsegs = _elf.Segments.Where(s => s.Type == SegmentType.Load); long orig_start = loadsegs.Min(s => s.Address); orig_start &= ~(Environment.SystemPageSize - 1); long orig_end = loadsegs.Max(s => s.Address + s.Size); _base = new MemoryBlock(0, (ulong)(orig_end - orig_start)); _loadoffset = (long)_base.Start - orig_start; try { _base.Set(_base.Start, _base.Size, MemoryBlock.Protection.RW); foreach (var seg in loadsegs) { var data = seg.GetContents(); Marshal.Copy(data, 0, Z.SS(seg.Address + _loadoffset), data.Length); } RegisterSymbols(); ProcessRelocations(); _base.Set(_base.Start, _base.Size, MemoryBlock.Protection.R); foreach (var sec in _elf.Sections.Where(s => s.Flags.HasFlag(SectionFlags.Allocatable))) { if (sec.Flags.HasFlag(SectionFlags.Executable)) { _base.Set((ulong)(sec.LoadAddress + _loadoffset), (ulong)sec.Size, MemoryBlock.Protection.RX); } else if (sec.Flags.HasFlag(SectionFlags.Writable)) { _base.Set((ulong)(sec.LoadAddress + _loadoffset), (ulong)sec.Size, MemoryBlock.Protection.RW); } } //FixupGOT(); ConnectAllClibPatches(); Console.WriteLine("Loaded {0}@{1:X16}", filename, _base.Start); } catch { _base.Dispose(); throw; } }
public SKLJoint(short id, string name, MTransformationMatrix local, MTransformationMatrix inverseGlobal) { this.IsLegacy = false; this.Flags = 0; this.ID = id; this.Name = name; this.Hash = ELF.Hash(name); this.Local = local; this.InverseGlobal = inverseGlobal; PrintInfo(); }
/// <summary> /// Loads the symbols from ELF and puts the symbols into the SymbolLookup. /// </summary> /// <param name="elf">Elf.</param> public void LoadELF(ELF <TAddress> elf) { Section <uint> symtabSection; if (!elf.TryGetSection(".symtab", out symtabSection)) { return; } var symtab = (SymbolTable <uint>)symtabSection; var thumb = elf.Machine == ELFSharp.ELF.Machine.ARM; var elfSymbols = symtab.Entries.Where(x => !armSpecificSymbolNames.Contains(x.Name)).Where(x => !excludedSymbolTypes.Contains(x.Type)).Select(x => new Symbol(x, thumb)); InsertSymbols(elfSymbols); EntryPoint = elf.EntryPoint; }
public ElfRunner(string filename) { // todo: hack up this baby to take Streams _elf = ELFReader.Load<long>(filename); var loadsegs = _elf.Segments.Where(s => s.Type == SegmentType.Load); long orig_start = loadsegs.Min(s => s.Address); orig_start &= ~(Environment.SystemPageSize - 1); long orig_end = loadsegs.Max(s => s.Address + s.Size); _base = new MemoryBlock(UIntPtr.Zero, orig_end - orig_start); _loadoffset = (long)_base.Start - orig_start; try { _base.Set(_base.Start, _base.Size, MemoryBlock.Protection.RW); foreach (var seg in loadsegs) { var data = seg.GetContents(); Marshal.Copy(data, 0, (IntPtr)(seg.Address + _loadoffset), data.Length); } RegisterSymbols(); ProcessRelocations(); _base.Set(_base.Start, _base.Size, MemoryBlock.Protection.R); foreach (var sec in _elf.Sections.Where(s => s.Flags.HasFlag(SectionFlags.Allocatable))) { if (sec.Flags.HasFlag(SectionFlags.Executable)) _base.Set((UIntPtr)(sec.LoadAddress + _loadoffset), sec.Size, MemoryBlock.Protection.RX); else if (sec.Flags.HasFlag(SectionFlags.Writable)) _base.Set((UIntPtr)(sec.LoadAddress + _loadoffset), sec.Size, MemoryBlock.Protection.RW); } //FixupGOT(); ConnectAllClibPatches(); Console.WriteLine("Loaded {0}@{1:X16}", filename, (long)_base.Start); } catch { _base.Dispose(); throw; } }
public static Program ReadProgram(ELF <uint> elf, bool generateMemory = true) { var state = new State(); if (generateMemory) { state.Memory = new byte[1000000]; } var littleEndian = elf.Endianess == Endianess.LittleEndian; var sections = new Dictionary <string, ISection>(); foreach (var x in elf.Sections) { sections.Add(x.Name, x); } var text = sections[".text"] as ProgBitsSection <uint>; var textReader = new BinaryReader(new MemoryStream(text.GetContents())); var reader = new InstructionsReader(littleEndian); var instructions = reader.ReadInstructions(textReader, littleEndian, text.LoadAddress); if (generateMemory) { Array.Copy(text.GetContents(), 0, state.Memory, text.LoadAddress, text.Size); } var names = new string[] { ".rodata", ".data", ".sdata" }; if (generateMemory) { foreach (var n in names) { ISection sect; if (sections.TryGetValue(n, out sect)) { var section = sect as ProgBitsSection <uint>; Array.Copy(section.GetContents(), 0, state.Memory, section.LoadAddress, section.Size); } } } return(new Program() { EntryPoint = elf.EntryPoint, Instructions = instructions, State = state, LittleEndian = littleEndian, TextSectionAddress = text.LoadAddress }); }
void LoadMap(string name, ulong pointer, uint entry_count, Action <string, string> addToMap) { string entries = entry_count == 1 ? "entry" : "entries"; Log.Info($" Loading {name} map: {entry_count} {entries}, please wait..."); ulong size = 0; size += GetPaddedSize <string> (size); // from size += GetPaddedSize <string> (size); // to ulong mapSize = entry_count * size; byte[] data = ELF.GetData(pointer, mapSize); ulong offset = 0; string mapFrom; string mapTo; for (uint i = 0; i < entry_count; i++) { pointer = ReadPointer(data, ref offset); if (pointer != 0) { mapFrom = ELF.GetASCIIZ(pointer); } else { mapFrom = $"#{i}"; } pointer = ReadPointer(data, ref offset); if (pointer != 0) { mapTo = ELF.GetASCIIZ(pointer); } else { mapTo = $"#{i}"; } addToMap(mapFrom, mapTo); } }
public override void InitFromElf(ELF<uint> elf) { var bamSection = elf.GetSections<Section<uint>>().FirstOrDefault(x => x.Name == ".__bam_bootarea"); if(bamSection != null) { var bamSectionContents = bamSection.GetContents(); var isValidResetConfigHalfWord = bamSectionContents[1] == 0x5a; if(!isValidResetConfigHalfWord) { this.Log(LogLevel.Warning, "Invalid BAM section, ignoring."); } else { StartInVle = (bamSectionContents[0] & 0x1) == 1; this.Log(LogLevel.Info, "Will {0}start in VLE mode.", StartInVle ? "" : "not "); } } base.InitFromElf(elf); }
List <TypeMapJava> LoadJavaTypes(string filePath) { ulong javaTypeCount = (ulong)ELF.GetUInt32(JavaTypeCountSymbolName); ulong javaNameWidth = (ulong)ELF.GetUInt32(JavaNameWidthSymbolName); // MUST be kept in sync with: src/monodroid/jni/xamarin-app.hh (struct TypeMapModule) ulong size = 0; size += GetPaddedSize <uint> (size); // module_index size += GetPaddedSize <uint> (size); // type_token_id size += javaNameWidth; byte[] data = ELF.GetData(MapJavaSymbolName); if (data.Length == 0) { throw new InvalidOperationException($"{filePath} doesn't have a valid '{MapJavaSymbolName}' symbol"); } ulong calculatedJavaTypeCount = (ulong)data.LongLength / size; if (calculatedJavaTypeCount != javaTypeCount) { throw new InvalidOperationException($"{filePath} has invalid '{JavaTypeCountSymbolName}' symbol value ({javaTypeCount}), '{JavaTypeCountSymbolName}' size indicates there are {calculatedJavaTypeCount} managedToJava instead"); } var ret = new List <TypeMapJava> (); ulong offset = 0; for (ulong i = 0; i < javaTypeCount; i++) { var javaEntry = new TypeMapJava { module_index = ReadUInt32(data, ref offset, packed: true), type_token_id = ReadUInt32(data, ref offset, packed: true), }; javaEntry.java_name = ELF.GetASCIIZ(data, offset); offset += javaNameWidth; ret.Add(javaEntry); } return(ret); }
public override void InitFromElf(ELF <uint> elf) { var bamSection = elf.GetSections <Section <uint> >().FirstOrDefault(x => x.Name == ".__bam_bootarea"); if (bamSection != null) { var bamSectionContents = bamSection.GetContents(); var isValidResetConfigHalfWord = bamSectionContents[1] == 0x5a; if (!isValidResetConfigHalfWord) { this.Log(LogLevel.Warning, "Invalid BAM section, ignoring."); } else { StartInVle = (bamSectionContents[0] & 0x1) == 1; this.Log(LogLevel.Info, "Will {0}start in VLE mode.", StartInVle ? "" : "not "); } } base.InitFromElf(elf); }
public void BootStage1(ELF <uint> elfFile) { foreach (var segment in elfFile.Segments) { byte[] data = segment.GetContents(); if (IsAddressInTCSM(segment.Address)) { data = PadData(data, JZ4780_TCSM_BANK_SIZE); } Console.WriteLine(string.Format("Writing from {0:X8} to {1:X8}", segment.Address, segment.Address + data.Length)); SetDataAddress(segment.Address); SendData(data); } FlushCaches(); Console.WriteLine(string.Format("Executing at {0:X8}", elfFile.EntryPoint)); Start2(elfFile.EntryPoint); }
bool DoLoadMaps() { // MUST be kept in sync with: src/monodroid/jni/xamarin-app.hh (struct TypeMap) ulong size = 0; size += GetPaddedSize <uint> (size); // entry_count size += GetPaddedSize <string> (size); // assembly_name (pointer) size += GetPaddedSize <string> (size); // data (pointer) size += GetPaddedSize <string> (size); // java_to_managed (pointer) size += GetPaddedSize <string> (size); // managed_to_java (pointer) string filePath = ELF.FilePath; byte[] mapData = ELF.GetData(TypeMapSymbolName); if (mapData.Length == 0) { Log.Error($"{filePath} doesn't have a valid '{TypeMapSymbolName}' symbol"); return(false); } if ((ulong)mapData.Length != size) { Log.Error($"Symbol '{TypeMapSymbolName}' in {filePath} has invalid size. Expected {size}, got {mapData.Length}"); return(false); } ulong offset = 0; uint entry_count = ReadUInt32(mapData, ref offset); ReadPointer(mapData, ref offset); // assembly_name, unused in Debug mode ReadPointer(mapData, ref offset); // data, unused in Debug mode ulong pointer = ReadPointer(mapData, ref offset); // java_to_managed LoadMap("Java to Managed", pointer, entry_count, AddJavaToManaged); pointer = ReadPointer(mapData, ref offset); // managed_to_java LoadMap("Managed to Java", pointer, entry_count, AddManagedToJava); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="ElfImage"/> class. /// </summary> /// <param name="path">The image path.</param> public ElfImage(string path) { elf = ELFReader.Load <ulong>(path); List <PublicSymbol> publicSymbols = new List <PublicSymbol>(); SymbolTable <ulong> symbols = elf.Sections.FirstOrDefault(s => s.Type == SectionType.SymbolTable) as SymbolTable <ulong>; if (symbols == null || !symbols.Entries.Any()) { symbols = elf.Sections.FirstOrDefault(s => s.Type == SectionType.DynamicSymbolTable) as SymbolTable <ulong>; } if (symbols != null) { ulong codeSegmentOffset = CodeSegmentOffset; foreach (SymbolEntry <ulong> symbol in symbols.Entries) { publicSymbols.Add(new PublicSymbol(symbol.Name, symbol.Value - codeSegmentOffset)); } } PublicSymbols = publicSymbols; }
private void openToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { compressRPLRPXToolStripMenuItem.Enabled = false; decompressRPLRPXToolStripMenuItem.Enabled = false; extractROMToolStripMenuItem.Enabled = false; FileELF = ELF.Open(openFileDialog.FileName); richTextBox.Clear(); if (FileELF != null) { LastFile = openFileDialog.FileName; richTextBox.AppendText("File: \"" + openFileDialog.FileName + "\"\n\n" + FileELF.ToString()); } else { LastFile = ""; richTextBox.AppendText("File: \"" + openFileDialog.FileName + "\"\n\nIt is not an ELF, RPX or RPL file."); } if (FileELF is RPX) { compressRPLRPXToolStripMenuItem.Enabled = true; decompressRPLRPXToolStripMenuItem.Enabled = true; } if (FileELF is RPXNES || FileELF is RPXSNES) { extractROMToolStripMenuItem.Enabled = true; } richTextBox.Font = new Font(richTextBox.Font.FontFamily, richTextBox.Font.Size, richTextBox.Font.Style); } }
static void Main(string[] args) { var devices = LibUsbDotNet.UsbDevice.AllDevices; for (int i = 0; i < devices.Count; i++) { var device = devices[i]; Console.WriteLine(devices[i].FullName); } try { ELF <uint> elfFile = ELFReader.Load <uint>(args[0]); USBLoader loader = new USBLoader(VendorID, ProductID); try { loader.BootStage1(elfFile); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { loader.Cleanup(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); }
void IControllableCPU.InitFromElf(ELF<uint> elf) { // do nothing }
public ElfRunner(string filename, long heapsize, long sealedheapsize, long invisibleheapsize) { using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { _elfhash = Hash(fs); } // todo: hack up this baby to take Streams _elf = ELFReader.Load<long>(filename); var loadsegs = _elf.Segments.Where(s => s.Type == SegmentType.Load); long orig_start = loadsegs.Min(s => s.Address); orig_start &= ~(Environment.SystemPageSize - 1); long orig_end = loadsegs.Max(s => s.Address + s.Size); if (HasRelocations()) { _base = new MemoryBlock((ulong)(orig_end - orig_start)); _loadoffset = (long)_base.Start - orig_start; _lockkey = 0; } else { _lockkey = (ulong)orig_start; _base = new MemoryBlock(_lockkey, (ulong)(orig_end - orig_start)); _loadoffset = 0; Enter(); } try { _disposeList.Add(_base); _memoryBlocks.Add(_base); _base.Activate(); _base.Protect(_base.Start, _base.Size, MemoryBlock.Protection.RW); foreach (var seg in loadsegs) { var data = seg.GetContents(); Marshal.Copy(data, 0, Z.SS(seg.Address + _loadoffset), data.Length); } RegisterSymbols(); ProcessRelocations(); _base.Protect(_base.Start, _base.Size, MemoryBlock.Protection.R); foreach (var sec in _elf.Sections.Where(s => (s.Flags & SectionFlags.Allocatable) != 0)) { if ((sec.Flags & SectionFlags.Executable) != 0) _base.Protect((ulong)(sec.LoadAddress + _loadoffset), (ulong)sec.Size, MemoryBlock.Protection.RX); else if ((sec.Flags & SectionFlags.Writable) != 0) _base.Protect((ulong)(sec.LoadAddress + _loadoffset), (ulong)sec.Size, MemoryBlock.Protection.RW); } ulong end = _base.End; if (heapsize > 0) { _heap = new Heap(GetHeapStart(end), (ulong)heapsize, "sbrk-heap"); _heap.Memory.Activate(); end = _heap.Memory.End; _disposeList.Add(_heap); _memoryBlocks.Add(_heap.Memory); } if (sealedheapsize > 0) { _sealedheap = new Heap(GetHeapStart(end), (ulong)sealedheapsize, "sealed-heap"); _sealedheap.Memory.Activate(); end = _sealedheap.Memory.End; _disposeList.Add(_sealedheap); _memoryBlocks.Add(_sealedheap.Memory); } if (invisibleheapsize > 0) { _invisibleheap = new Heap(GetHeapStart(end), (ulong)invisibleheapsize, "invisible-heap"); _invisibleheap.Memory.Activate(); end = _invisibleheap.Memory.End; _disposeList.Add(_invisibleheap); _memoryBlocks.Add(_invisibleheap.Memory); } ConnectAllClibPatches(); Console.WriteLine("Loaded {0}@{1:X16}", filename, _base.Start); foreach (var sec in _elf.Sections.Where(s => s.LoadAddress != 0)) { Console.WriteLine(" {0}@{1:X16}, size {2}", sec.Name.PadLeft(20), sec.LoadAddress + _loadoffset, sec.Size.ToString().PadLeft(12)); } PrintTopSavableSymbols(); } catch { Dispose(); throw; } finally { Exit(); } }
internal DynamicSection(SectionHeader header, SimpleEndianessAwareReader reader, ELF <T> elf) : base(header, reader) { this.elf = elf; ReadEntries(); }
protected void OnBtnLoadClick(object sender, EventArgs e) { txtFile.Text = ""; txtType.Text = ""; txtInformation.Text = ""; cmbArch.Items.Clear(); lblSubsystem.Visible = false; txtSubsystem.Visible = false; tabStrings.Visible = false; tabGemResources.Visible = false; tabSegments.Visible = false; tabNeResources.Visible = false; tabLeVxdVersion.Visible = false; tabLxResources.Visible = false; tabPeResources.Visible = false; tabBeResources.Visible = false; OpenFileDialog dlgOpen = new OpenFileDialog { Title = "Choose executable file", MultiSelect = false }; if (dlgOpen.ShowDialog(this) != DialogResult.Ok) { return; } txtFile.Text = dlgOpen.FileName; txtInformation.Text = ""; txtOs.Text = ""; txtSubsystem.Text = ""; txtType.Text = ""; IExecutable mzExe = new MZ(dlgOpen.FileName); IExecutable neExe = new libexeinfo.NE(dlgOpen.FileName); IExecutable stExe = new AtariST(dlgOpen.FileName); IExecutable lxExe = new libexeinfo.LX(dlgOpen.FileName); IExecutable coffExe = new COFF(dlgOpen.FileName); IExecutable peExe = new libexeinfo.PE(dlgOpen.FileName); IExecutable geosExe = new Geos(dlgOpen.FileName); IExecutable elfExe = new ELF(dlgOpen.FileName); IExecutable recognizedExe = null; if (mzExe.Recognized) { recognizedExe = mzExe; if (((MZ)mzExe).ResourceObjectRoots != null && ((MZ)mzExe).ResourceObjectRoots.Any()) { tabGemResources.Update(((MZ)mzExe).ResourceObjectRoots, ((MZ)mzExe).GemColorIcons); tabGemResources.Visible = true; } } if (neExe.Recognized) { recognizedExe = neExe; if (((libexeinfo.NE)neExe).Resources.types != null && ((libexeinfo.NE)neExe).Resources.types.Any()) { tabNeResources.Update(((libexeinfo.NE)neExe).Resources.types, ((libexeinfo.NE)neExe).Header.target_os); tabNeResources.Visible = true; } } else if (lxExe.Recognized) { recognizedExe = lxExe; if (((libexeinfo.LX)lxExe).WinVersion != null) { tabLeVxdVersion.Visible = true; tabLeVxdVersion.Update(((libexeinfo.LX)lxExe).WinVersion); } if (((libexeinfo.LX)lxExe).neFormatResourceTable.types != null && ((libexeinfo.LX)lxExe).neFormatResourceTable.types.Any()) { tabLxResources.Update(((libexeinfo.LX)lxExe).neFormatResourceTable.types); tabLxResources.Visible = true; } } else if (peExe.Recognized) { recognizedExe = peExe; if (((libexeinfo.PE)peExe).WindowsResourcesRoot?.children != null) { tabPeResources.Update(((libexeinfo.PE)peExe).WindowsResourcesRoot); tabPeResources.Visible = true; } if (((libexeinfo.PE)peExe).BeosResources != null) { tabBeResources.Update(((libexeinfo.PE)peExe).BeosResources, peExe.IsBigEndian); tabBeResources.Visible = true; } } else if (stExe.Recognized) { recognizedExe = stExe; if (((AtariST)stExe).ResourceObjectRoots != null && ((AtariST)stExe).ResourceObjectRoots.Any()) { tabGemResources.Update(((AtariST)stExe).ResourceObjectRoots, ((AtariST)stExe).GemColorIcons); tabGemResources.Visible = true; } } else if (coffExe.Recognized) { recognizedExe = coffExe; } else if (elfExe.Recognized) { recognizedExe = elfExe; } else if (geosExe.Recognized) { recognizedExe = geosExe; } else { txtType.Text = "Format not recognized"; } if (recognizedExe == null) { return; } txtType.Text = recognizedExe.Type; txtInformation.Text = recognizedExe.Information; foreach (Architecture arch in recognizedExe.Architectures) { cmbArch.Items.Add(Enums.ArchitectureName.FirstOrDefault(ar => ar.arch == arch).longName); } cmbArch.SelectedIndex = 0; if (recognizedExe.RequiredOperatingSystem.MajorVersion > 0) { txtOs.Text = $"{recognizedExe.RequiredOperatingSystem.Name}" + $" {recognizedExe.RequiredOperatingSystem.MajorVersion}" + $".{recognizedExe.RequiredOperatingSystem.MinorVersion}"; } else { txtOs.Text = recognizedExe.RequiredOperatingSystem.Name; } if (!string.IsNullOrEmpty(recognizedExe.RequiredOperatingSystem.Subsystem)) { lblSubsystem.Visible = true; txtSubsystem.Visible = true; txtSubsystem.Text = recognizedExe.RequiredOperatingSystem.Subsystem; } if (recognizedExe.Strings != null && recognizedExe.Strings.Any()) { tabStrings.Update(recognizedExe.Strings); tabStrings.Visible = true; } if (recognizedExe.Segments != null && recognizedExe.Segments.Any()) { tabSegments.Update(recognizedExe.Segments); tabSegments.Visible = true; } }
public void BootStage1(ELF<uint> elfFile) { foreach (var segment in elfFile.Segments) { byte[] data = segment.GetContents(); if (IsAddressInTCSM(segment.Address)) { data = PadData(data, JZ4780_TCSM_BANK_SIZE); } Console.WriteLine(string.Format("Writing from {0:X8} to {1:X8}", segment.Address, segment.Address + data.Length)); SetDataAddress(segment.Address); SendData(data); } FlushCaches(); Console.WriteLine(string.Format("Executing at {0:X8}", elfFile.EntryPoint)); Start2(elfFile.EntryPoint); }
public ElfRunner(string filename, long heapsize, long sealedheapsize, long invisibleheapsize) { using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { _elfhash = WaterboxUtils.Hash(fs); } // todo: hack up this baby to take Streams _elf = ELFReader.Load <long>(filename); var loadsegs = _elf.Segments.Where(s => s.Type == SegmentType.Load); long orig_start = loadsegs.Min(s => s.Address); orig_start &= ~(Environment.SystemPageSize - 1); long orig_end = loadsegs.Max(s => s.Address + s.Size); if (HasRelocations()) { _base = new MemoryBlock((ulong)(orig_end - orig_start)); _loadoffset = (long)_base.Start - orig_start; Initialize(0); } else { Initialize((ulong)orig_start); _base = new MemoryBlock((ulong)orig_start, (ulong)(orig_end - orig_start)); _loadoffset = 0; Enter(); } try { _disposeList.Add(_base); AddMemoryBlock(_base, "elf"); _base.Activate(); _base.Protect(_base.Start, _base.Size, MemoryBlock.Protection.RW); foreach (var seg in loadsegs) { var data = seg.GetContents(); Marshal.Copy(data, 0, Z.SS(seg.Address + _loadoffset), data.Length); } RegisterSymbols(); ProcessRelocations(); _base.Protect(_base.Start, _base.Size, MemoryBlock.Protection.R); foreach (var sec in _elf.Sections.Where(s => (s.Flags & SectionFlags.Allocatable) != 0)) { if ((sec.Flags & SectionFlags.Executable) != 0) { _base.Protect((ulong)(sec.LoadAddress + _loadoffset), (ulong)sec.Size, MemoryBlock.Protection.RX); } else if ((sec.Flags & SectionFlags.Writable) != 0) { _base.Protect((ulong)(sec.LoadAddress + _loadoffset), (ulong)sec.Size, MemoryBlock.Protection.RW); } } ulong end = _base.End; if (heapsize > 0) { _heap = new Heap(GetHeapStart(end), (ulong)heapsize, "sbrk-heap"); _heap.Memory.Activate(); end = _heap.Memory.End; _disposeList.Add(_heap); AddMemoryBlock(_heap.Memory, "sbrk - heap"); } if (sealedheapsize > 0) { _sealedheap = new Heap(GetHeapStart(end), (ulong)sealedheapsize, "sealed-heap"); _sealedheap.Memory.Activate(); end = _sealedheap.Memory.End; _disposeList.Add(_sealedheap); AddMemoryBlock(_sealedheap.Memory, "sealed-heap"); } if (invisibleheapsize > 0) { _invisibleheap = new Heap(GetHeapStart(end), (ulong)invisibleheapsize, "invisible-heap"); _invisibleheap.Memory.Activate(); end = _invisibleheap.Memory.End; _disposeList.Add(_invisibleheap); AddMemoryBlock(_invisibleheap.Memory, "invisible-heap"); } ConnectAllClibPatches(); Console.WriteLine("Loaded {0}@{1:X16}", filename, _base.Start); foreach (var sec in _elf.Sections.Where(s => s.LoadAddress != 0)) { Console.WriteLine(" {0}@{1:X16}, size {2}", sec.Name.PadLeft(20), sec.LoadAddress + _loadoffset, sec.Size.ToString().PadLeft(12)); } PrintTopSavableSymbols(); } catch { Dispose(); throw; } finally { Exit(); } }
internal SymbolTable(SectionHeader header, SimpleEndianessAwareReader Reader, IStringTable table, ELF <T> elf) : base(header, Reader) { this.table = table; this.elf = elf; ReadSymbols(); }
void IControllableCPU.InitFromElf(ELF <uint> elf) { // do nothing }
public virtual void InitFromElf(ELF<uint> elf) { this.Log(LogLevel.Info, "Setting PC value to 0x{0:X}.", elf.EntryPoint); SetPCFromEntryPoint(elf.EntryPoint); }
/// FUNCTION: Open ELF file, read elf header, read each program header entr (PHE) and store segment(s) to RAM /// if succesful elf header read, then /// - clear memory and registers /// - set programCounter with elf header entry point /// - load PHEs to RAM /// RETURNS: /// returns -1 if failed to load segments into ram /// returns 0 if success public int loadSegmentsIntoRAM(string fileName) { try { using (FileStream strm = new FileStream(fileName, FileMode.Open)) { ELF elfHeader = new ELF(); byte[] data = new byte[Marshal.SizeOf(elfHeader)]; strm.Read(data, 0, data.Length); // Read ELF header data elfHeader = ByteArrayToStructure <ELF>(data); // Convert to struct debugLog.WriteLineToLog("IMPORTANT: Debug logging information for developers: " + DateTime.Now); debugLog.WriteLineToLog("Loader: in loadSegmentsIntoRAM (): Opening " + fileName + "…"); debugLog.WriteLineToLog("Loader: in loadSegmentsIntoRAM (): Program entry address: " + elfHeader.e_entry); debugLog.WriteLineToLog("Loader: in loadSegmentsIntoRAM (): Program header offset (location in file): " + elfHeader.e_phoff); debugLog.WriteLineToLog("Loader: in loadSegmentsIntoRAM (): Size of Program header entry: " + elfHeader.e_phentsize); debugLog.WriteLineToLog("Loader: in loadSegmentsIntoRAM (): Number of segments: " + elfHeader.e_phnum); //NumberelfHeader.e_entry.ToString("X4")); // clear memory, registers, nzcv flags memory.clearMemory(); registers.clearRegisters(); registers.clearNZCVFlags(); // update program counter r15 registers.updateProgramCounter(elfHeader.e_entry); // update stack pointer r13 registers.updateStackPointer(0x7000); // Read all program header entries and load segments to RAM uint nextElfHeaderOffset = elfHeader.e_phoff; int segmentNum = 0; for (int i = 0; i < elfHeader.e_phnum; i++, segmentNum++) // Read all program headers { // Read a program header PHE headerTable = new PHE(); data = new byte[elfHeader.e_phentsize]; strm.Seek(nextElfHeaderOffset, SeekOrigin.Begin); // move position to start of next program header entry strm.Read(data, 0, (int)elfHeader.e_phentsize); // Read ELF header data headerTable = ByteArrayToStructure <PHE>(data); // Convert to struct // Load PHE to RAM strm.Seek(headerTable.p_offset, SeekOrigin.Begin); // move position to start of segment data = new byte[headerTable.p_filesz]; // resize data strm.Read(data, 0, (int)headerTable.p_filesz); // Read segment to data int succesfulLoad = memory.loadRAMfromDataArrayBytes(ref data, ref headerTable); if (succesfulLoad == -1) // return if fail to load registers, mostlikely it doesn't fit in the RAM { return(-1); } debugLog.WriteLineToLog("Loader: Segment " + segmentNum + " - vAddress = " + headerTable.p_vaddr + ", File Offset: " + headerTable.p_offset + ", Size: " + headerTable.p_filesz); nextElfHeaderOffset += ((uint)elfHeader.e_phentsize); } uint cksum = memory.ComputeRAMChecksum(null); debugLog.WriteLineToLog("\nCurrent RAM hex digest: " + cksum); //Console.WriteLine("\nCurrent RAM hex digest: " + cksum); } } catch (Exception e) { debugLog.WriteLineToLog("Loader: in loadSegmentsIntoRAM(): File cannot be opened: " + e.Message); //Console.WriteLine("For help try: armmemory.exe --help"); MessageBox.Show(e.Message, "Error Openning Executable File", MessageBoxButtons.OK, MessageBoxIcon.Error); return(-1); } return(0); }