protected void WriteToMemory()
        {
            foreach (var sectionHeader in SectionHeadersWithFlag(Elf.SectionHeader.FlagsSet.Allocate))
            {
                var sectionHeaderFileStream   = FileStream.SliceWithLength(sectionHeader.Offset, sectionHeader.Size);
                var sectionHeaderMemoryStream =
                    MemoryStream.SliceWithLength(sectionHeader.Address + BaseAddress, sectionHeader.Size);

                Console.WriteLine("WriteToMemory('{0:X}') : 0x{1:X} : {2} : {3}",
                                  GetStringFromStringTable(sectionHeader.Name), sectionHeader.Address, sectionHeader.Type,
                                  sectionHeader.Size);
                Console.WriteLine("   0x{0:X} - 0x{1:X}", sectionHeader.Address + BaseAddress, sectionHeader.Size);

                switch (sectionHeader.Type)
                {
                case Elf.SectionHeader.TypeEnum.ProgramBits:
                    //Console.WriteLine(SectionHeaderFileStream.ReadAll().ToHexString());
                    sectionHeaderMemoryStream.WriteStream(sectionHeaderFileStream);
                    break;

                case Elf.SectionHeader.TypeEnum.NoBits:
                    sectionHeaderMemoryStream.WriteByteRepeated(0, sectionHeader.Size);
                    break;

                default:
                    break;
                }
            }
        }
Exemple #2
0
        public String Detect(Stream Stream)
        {
            var StartMagic = Stream.SliceWithLength(0, 4).ReadAllContentsAsString(Encoding.ASCII);

            Console.WriteLine(StartMagic);

            if (StartMagic == '\0' + "PBP")
            {
                return("Pbp");
            }
            if (StartMagic == '\0' + "PSF")
            {
                return("Psf");
            }
            if (StartMagic == '\x7F' + "ELF")
            {
                return("Elf");
            }
            if (StartMagic == "CISO")
            {
                return("Cso");
            }
            if (StartMagic == "DAX" + '\0')
            {
                return("Dax");
            }

            if (Stream.SliceWithLength(0x8000, 6).ReadAllContentsAsString() == '\x01' + "CD001")
            {
                return("Iso");
            }

            return("Unknown");
        }
Exemple #3
0
        public SE3 Load(Stream Stream)
        {
            var Header = Stream.ReadStruct <HeaderStruct>();

            if (Header.Magic != 0x53453320)
            {
                throw(new Exception("Not a SE3 File"));
            }
            var NameStream = Stream.SliceWithLength(0x10, Header.NameSize);
            var ELBP       = NameStream.ReadStruct <uint_be>();
            var NameCount  = (uint)NameStream.ReadStruct <uint_be>();

            Entries         = new List <SE3Entry>();
            EntriesWithName = new Dictionary <string, SE3Entry>();
            for (int n = 0; n < NameCount; n++)
            {
                var Entry = new SE3Entry()
                {
                    Name = NameStream.ReadStringz(0x30),
                };
                Entries.Add(Entry);
                EntriesWithName[Entry.Name] = Entry;
            }
            _LoadData(Stream.SliceWithLength(Header.DataStart));
            return(this);
        }
Exemple #4
0
        public Psf Load(Stream stream)
        {
            EntryDictionary = new Dictionary <string, object>();
            Header          = stream.ReadStruct <HeaderStruct>();
            Entries         = stream.ReadStructVector <EntryStruct>(Header.NumberOfPairs);
            KeysStream      = stream.SliceWithLength(Header.KeyTable);
            ValuesStream    = stream.SliceWithLength(Header.ValueTable);
            foreach (var entry in Entries)
            {
                var key         = KeysStream.ReadStringzAt(entry.KeyOffset);
                var valueStream = ValuesStream.SliceWithLength(entry.ValueOffset, entry.ValueSize);
                switch (entry.DataType)
                {
                case DataType.Binary:
                    EntryDictionary[key] = valueStream.ReadAll();
                    break;

                case DataType.Int:
                    EntryDictionary[key] = valueStream.ReadStruct <int>();
                    break;

                case DataType.Text:
                    EntryDictionary[key] = valueStream.ReadStringz(-1, Encoding.UTF8);
                    break;

                default: throw new NotImplementedException();
                }
            }
            return(this);
        }
    /// <summary>
    ///
    /// </summary>
    /// <param name="Stream"></param>
    /// <param name="ToRead"></param>
    /// <param name="AlignTo4"></param>
    /// <returns></returns>
    static public int CountStringzBytes(this Stream Stream, int ToRead = -1, bool AlignTo4 = false, int AlignPosition = 0, bool KeepStreamPosition = true)
    {
        if (AlignTo4 == true)
        {
            throw(new NotImplementedException());
        }
        if (KeepStreamPosition)
        {
            Stream = Stream.SliceWithLength(Stream.Position);
        }
        if (Stream.Eof())
        {
            return(0);
        }
        bool ContinueReading = false;

        if (ToRead == -1)
        {
            ToRead          = 0x100;
            ContinueReading = true;
        }

        var StartPosition = Stream.Position;
        var Bytes         = Stream.ReadBytesUpTo(ToRead);
        int ZeroIndex     = Array.IndexOf(Bytes, (byte)0x00);

        if (ZeroIndex == -1)
        {
            if (ContinueReading)
            {
                return(Bytes.Length + CountStringzBytes(Stream, ToRead, AlignTo4, KeepStreamPosition: false));
            }
            else
            {
                return(Bytes.Length);
            }
        }
        else
        {
            if (AlignTo4)
            {
                var Bytes2 = Stream.SliceWithLength(StartPosition + ZeroIndex, 5).ReadBytesUpTo(5);
                int n      = 0;
                for (; n < Bytes2.Length; n++)
                {
                    if (Bytes2[n] != 0)
                    {
                        break;
                    }
                }
                return(ZeroIndex + n);
            }
            else
            {
                return(ZeroIndex + 1);
            }
        }
    }
Exemple #6
0
        public TXM Load(Stream TXMStream, Stream TXVStream)
        {
            this.TXVStream = TXVStream;

            if (!IsValid(TXMStream.Slice().ReadBytesUpTo(0x100)))
            {
                throw(new Exception("Invalid TXM!"));
            }

            this.ImageVersion = TXMStream.Slice().ReadStruct <ImageVersionStruct>();

            if (ImageVersion.Version == 1)
            {
                this.Surface2DEntriesByName = new Dictionary <string, Surface2DEntryInfo>();
                this.Surface2DEntries       = new Surface2DEntryInfo[0];
                this.Surface3DEntriesByName = new Dictionary <string, Surface3DEntryInfo>();
                this.Surface3DEntries       = new Surface3DEntryInfo[0];
                Console.Error.WriteLine("Not Implemented TXM V1!!!!!!!");
            }
            else
            {
                this.ImageHeader = TXMStream.ReadStruct <ImageHeaderStructV2>();

                this.Surface2DEntriesByName = new Dictionary <string, Surface2DEntryInfo>();
                this.Surface2DEntries       = new Surface2DEntryInfo[ImageHeader.Surface2DCount];
                for (int n = 0; n < ImageHeader.Surface2DCount; n++)
                {
                    var ImageEntry = TXMStream.ReadStruct <Surface2DInfoStructV2>();
                    var Name       = TXMStream.SliceWithLength(TXMStream.Position + Marshal.OffsetOf(typeof(Surface2DInfoStructV2), "StringOffset").ToInt32() - sizeof(Surface2DInfoStructV2) + ImageEntry.StringOffset).ReadStringz();
                    var Entry      = new Surface2DEntryInfo(this, n, ImageEntry, Name);
                    this.Surface2DEntries[n]          = Entry;
                    this.Surface2DEntriesByName[Name] = Entry;
                }

                this.Surface3DEntriesByName = new Dictionary <string, Surface3DEntryInfo>();
                this.Surface3DEntries       = new Surface3DEntryInfo[ImageHeader.Surface3DCount];
                if (this.ImageHeader.VersionInfo.Version != 1)
                {
                    for (int n = 0; n < ImageHeader.Surface3DCount; n++)
                    {
                        var ImageEntry = TXMStream.ReadStruct <Surface3DInfoStructV2>();
                        var Name       = TXMStream.SliceWithLength(TXMStream.Position + Marshal.OffsetOf(typeof(Surface3DInfoStructV2), "StringOffset").ToInt32() - sizeof(Surface3DInfoStructV2) + ImageEntry.StringOffset).ReadStringz();
                        var Entry      = new Surface3DEntryInfo(this, n, ImageEntry, Name);
                        this.Surface3DEntries[n] = Entry;
                        this.Surface3DEntriesByName[Entry.Name] = Entry;
                    }
                }
            }

            return(this);
        }
Exemple #7
0
        protected void ExtractSvo(string SvoPath)
        {
            //try
            //{
            using (var _SvoStream = File.OpenRead(SvoPath))
            {
                Stream SvoStream  = _SvoStream;
                int    Compressed = TalesCompression.DetectVersion(SvoStream.Slice().ReadBytes(16), SvoStream.Length);
                if (Compressed >= 0)
                {
                    SvoStream = TalesCompression.DecompressStream(SvoStream);
                }

                if (SvoStream.SliceWithLength().ReadString(7) == "TO8SCEL")
                {
                    var TO8SCEL = new TO8SCEL(SvoStream);

                    foreach (var Entry in TO8SCEL)
                    {
                        Console.WriteLine("{0} ... Start: {1}, End: {2}, Length: {3}", Entry.Index, Entry.EntryStruct.Offset, Entry.EntryStruct.Offset + Entry.EntryStruct.LengthCompressed, Entry.EntryStruct.LengthCompressed);
                    }
                }
                else
                {
                    var FPS4 = new FPS4(SvoStream);

                    Console.WriteLine("{0}", FPS4);

                    foreach (var Entry in FPS4)
                    {
                        Console.WriteLine("{0} ... Start: {1}, End: {2}, Length: {3}", Entry.Name, Entry.EntryStruct.Offset, Entry.EntryStruct.Offset + Entry.EntryStruct.LengthReal, Entry.EntryStruct.LengthReal);
                    }
                }
            }
        }
Exemple #8
0
        public void LoadSectionsTo(Stream MemoryStream)
        {
            Console.WriteLine("{0:X}", ExeStream.Length);

            //400-1600 -> 82000400-820015E4

            //PeStream.SliceWithLength(0).CopyToFast(MemoryStream.SliceWithLength(0x82000000));
            //return;

            //var BaseMemoryStream = MemoryStream.SliceWithLength(PeOptionalHeader.ImageBase);

            File.WriteAllBytes(@"C:\projects\csharp\cs360emu\test.bin", ExeStream.ReadAll());

            foreach (var ImageSectionHeader in ImageSectionHeaderList)
            {
                Console.WriteLine("-------------------------------------------------");
                Console.WriteLine(ImageSectionHeader.ToStringDefault());
                var FileSlice = ExeStream.SliceWithLength(ImageSectionHeader.PointerToRawData, ImageSectionHeader.SizeOfRawData);
                var MemorySlice = MemoryStream.SliceWithLength(ImageSectionHeader.VirtualAddress + PeOptionalHeader.ImageBase, ImageSectionHeader.VirtualSize);
                Console.WriteLine("Segment: {0:X}-{1:X} -> {2:X}-{3:X}", FileSlice.SliceLow, FileSlice.SliceHigh, MemorySlice.SliceLow, MemorySlice.SliceHigh);

                var Data = FileSlice.ReadAll(true);
                //Console.WriteLine(BitConverter.ToString(Data));
                MemorySlice.WriteBytes(Data);
                //FileSlice.Position = 0;
                //MemorySlice.Position = 0;
                //FileSlice.CopyToFast(MemorySlice);
            }
        }
Exemple #9
0
        public String Detect(Stream Stream)
        {
            var StartMagic = Stream.SliceWithLength(0, 4).ReadAllContentsAsString(Encoding.ASCII);

            Console.WriteLine(StartMagic);

            if (StartMagic == '\0' + "PBP") return "Pbp";
            if (StartMagic == '\0' + "PSF") return "Psf";
            if (StartMagic == '\x7F' + "ELF") return "Elf";
            if (StartMagic == "CISO") return "Cso";
            if (StartMagic == "DAX" + '\0') return "Dax";

            if (Stream.SliceWithLength(0x8000, 6).ReadAllContentsAsString() == '\x01' + "CD001") return "Iso";

            return "Unknown";
        }
        /// <summary>
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="toRead"></param>
        /// <param name="alignTo4"></param>
        /// <param name="alignPosition"></param>
        /// <param name="keepStreamPosition"></param>
        /// <returns></returns>
        public static int CountStringzBytes(this Stream stream, int toRead = -1, bool alignTo4 = false,
                                            int alignPosition = 0, bool keepStreamPosition     = true)
        {
            if (keepStreamPosition)
            {
                stream = stream.SliceWithLength(stream.Position);
            }
            if (stream.Eof())
            {
                return(0);
            }
            var continueReading = false;

            if (toRead == -1)
            {
                toRead          = 0x100;
                continueReading = true;
            }

            var startPosition = stream.Position;
            var bytes         = stream.ReadBytesUpTo(toRead);
            var zeroIndex     = Array.IndexOf(bytes, (byte)0x00);

            if (zeroIndex == -1)
            {
                if (continueReading)
                {
                    return(bytes.Length + CountStringzBytes(stream, toRead, alignTo4, keepStreamPosition: false));
                }
                return(bytes.Length);
            }

            if (alignTo4)
            {
                var bytes2 = stream.SliceWithLength(startPosition + zeroIndex, 5).ReadBytesUpTo(5);
                var n      = 0;
                for (; n < bytes2.Length; n++)
                {
                    if (bytes2[n] != 0)
                    {
                        break;
                    }
                }
                return(zeroIndex + n);
            }
            return(zeroIndex + 1);
        }
Exemple #11
0
        public SubType DetectSubType(Stream Stream)
        {
            var StartMagic = Stream.SliceWithLength(0, 4).ReadAllContentsAsString(Encoding.ASCII);

            //Console.WriteLine(StartMagic);

            if (StartMagic == '\0' + "PBP") return SubType.Pbp;
            if (StartMagic == '\0' + "PSF") return SubType.Psf;
            if (StartMagic == '\x7F' + "ELF") return SubType.Elf;
            if (StartMagic == "~PSP") return SubType.EncryptedElf;
            if (StartMagic == "CISO") return SubType.Cso;
            if (StartMagic == "DAX" + '\0') return SubType.Dax;

            if (Stream.SliceWithLength(0x8000, 6).ReadAllContentsAsString() == '\x01' + "CD001") return SubType.Iso;

            return SubType.Unknown;
        }
 /// <summary>
 /// Function that writtes all the mappings into another stream.
 /// Useful for patching a file or memory.
 /// </summary>
 /// <param name="targetStream">Stream to write the mapped contents to</param>
 public void WriteSegmentsToStream(Stream targetStream)
 {
     foreach (var streamEntry in _StreamEntries)
     {
         var sourceSliceStream = streamEntry.Stream.SliceWithLength(0, streamEntry.Length);
         var targetSliceStream = targetStream.SliceWithLength(streamEntry.Position, streamEntry.Length);
         sourceSliceStream.CopyToFast(targetSliceStream);
     }
 }
 /// <summary>
 /// Function that writtes all the mappings into another stream.
 /// Useful for patching a file or memory.
 /// </summary>
 /// <param name="TargetStream">Stream to write the mapped contents to</param>
 public void WriteSegmentsToStream(Stream TargetStream)
 {
     foreach (var StreamEntry in _StreamEntries)
     {
         var SourceSliceStream = StreamEntry.Stream.SliceWithLength(0, StreamEntry.Length);
         var TargetSliceStream = TargetStream.SliceWithLength(StreamEntry.Position, StreamEntry.Length);
         SourceSliceStream.CopyToFast(TargetSliceStream);
     }
 }
Exemple #14
0
        private void _LoadData(Stream Stream)
        {
            var Unk0       = Stream.ReadStruct <uint_be>();
            var Unk1       = Stream.ReadStruct <uint_be>();
            var Unk2       = Stream.ReadStruct <uint_be>();
            var Count      = (uint)Stream.ReadStruct <uint_be>();
            var DataStart  = Stream.ReadStruct <uint_be>();
            var Unk4       = Stream.ReadStruct <uint_be>();
            var Unk5       = Stream.ReadStruct <uint_be>();
            var DataStream = Stream.SliceWithLength(DataStart);

            for (int n = 0; n < Count; n++)
            {
                var Offset = Stream.ReadStruct <uint_be>();
                var Header = Stream.SliceWithLength(Offset).ReadStruct <XMAEntryHeaderStruct>();
                Entries[n].Header     = Header;
                Entries[n].DataStream = DataStream.SliceWithLength(Header.DataStart, Header.DataLength);
            }
        }
Exemple #15
0
 public Psf Load(Stream Stream)
 {
     EntryDictionary = new Dictionary<string, object>();
     Header = Stream.ReadStruct<HeaderStruct>();
     Entries = Stream.ReadStructVector<EntryStruct>(Header.NumberOfPairs);
     KeysStream = Stream.SliceWithLength(Header.KeyTable);
     ValuesStream = Stream.SliceWithLength(Header.ValueTable);
     foreach (var Entry in Entries)
     {
         var Key = KeysStream.ReadStringzAt(Entry.KeyOffset);
         var ValueStream = ValuesStream.SliceWithLength(Entry.ValueOffset, Entry.ValueSize);;
         switch (Entry.DataType)
         {
             case DataType.Binary: EntryDictionary[Key] = ValueStream.ReadAll(); break;
             case DataType.Int: EntryDictionary[Key] = ValueStream.ReadStruct<int>(); break;
             case DataType.Text: EntryDictionary[Key] = ValueStream.ReadStringz(-1, Encoding.UTF8); break;
             default: throw(new NotImplementedException());
         }
     }
     return this;
 }
Exemple #16
0
        public SubType DetectSubType(Stream stream)
        {
            var startMagic = stream.SliceWithLength(0, 4).ReadAllContentsAsString(Encoding.ASCII);

            //Console.WriteLine(StartMagic);

            if (startMagic == "\u0000PBP")
            {
                return(SubType.Pbp);
            }
            if (startMagic == "\u0000PSF")
            {
                return(SubType.Psf);
            }
            if (startMagic == "\u007FELF")
            {
                return(SubType.Elf);
            }
            if (startMagic == "~PSP")
            {
                return(SubType.EncryptedElf);
            }
            if (startMagic == "CISO")
            {
                return(SubType.Cso);
            }
            if (startMagic == "DAX\u0000")
            {
                return(SubType.Dax);
            }

            if (stream.SliceWithLength(0x8000, 6).ReadAllContentsAsString() == "\u0001CD001")
            {
                return(SubType.Iso);
            }

            return(SubType.Unknown);
        }
Exemple #17
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public IEnumerable <ushort> GetIplOffsets()
        {
            var stream = Stream.SliceWithLength(NandReader.BytesPerBlock * 4);

            while (true)
            {
                var result = stream.ReadStruct <ushort>();
                if (result == 0)
                {
                    break;
                }
                yield return(result);
            }
        }
Exemple #18
0
        public Pmf Load(Stream Stream)
        {
            Header = Stream.ReadStruct<HeaderStruct>();

            var Chunk = ReadChunk(Stream.SliceWithLength(0x50));
            InfoHeader = Chunk.Stream.ReadStruct<InfoHeaderStruct>();
            /*
            Console.WriteLine("0x{0:X}", (ulong)InfoHeader.FirstTimestamp);
            Console.WriteLine("0x{0:X}", (ulong)InfoHeader.LastTimestamp);
            Console.WriteLine("{0}", (ulong)InfoHeader.Width);
            Console.WriteLine("{0}", (ulong)InfoHeader.Height);
            */

            return this;
        }
Exemple #19
0
        public Pe LoadHeader(Stream _ExeStream)
        {
            ExeStream = _ExeStream;
            DosExe = new DosExe().LoadHeader(ExeStream);
            PeStream = ExeStream.SliceWithLength(DosExe.Header.OffsetToPEHeader);
            PeHeader = PeStream.ReadStruct<PeHeaderStruct>();
            OptionalHeaderStream = PeStream.ReadStream(PeHeader.SizeOfOptionalHeader);
            PeOptionalHeader = OptionalHeaderStream.ReadStruct<PeOptionalHeaderStruct>();
            ImageSectionHeaderList = new ImageSectionHeader[PeHeader.NumSections];
            for (int n = 0; n < PeHeader.NumSections; n++)
            {
                ImageSectionHeaderList[n] = PeStream.ReadStruct<ImageSectionHeader>();
            }

            return this;
        }
Exemple #20
0
		public virtual void Load(Stream FileStream, string Name)
		{
			FileStream = new MemoryStream(FileStream.ReadAll());

			this.FileStream = FileStream;

			this.Header = FileStream.ReadStruct<Elf.HeaderStruct>();
			if (this.Header.Magic != Elf.HeaderStruct.MagicEnum.ExpectedValue)
			{
				throw(new InvalidProgramException("Not an ELF File '" + Name + "'"));
			}

			if (this.Header.Machine != Elf.HeaderStruct.MachineEnum.ALLEGREX)
			{
				throw (new InvalidProgramException("Invalid Elf.Header.Machine"));
			}

			this.ProgramHeaders = FileStream.ReadStructVectorAt<Elf.ProgramHeader>(Header.ProgramHeaderOffset, Header.ProgramHeaderCount, Header.ProgramHeaderEntrySize);
			this.SectionHeaders = FileStream.ReadStructVectorAt<Elf.SectionHeader>(Header.SectionHeaderOffset, Header.SectionHeaderCount, Header.SectionHeaderEntrySize);

			this.NamesSectionHeader = this.SectionHeaders[Header.SectionHeaderStringTable];
			this.StringTable = FileStream.SliceWithLength(this.NamesSectionHeader.Offset, this.NamesSectionHeader.Size).ReadAll();

			this.SectionHeadersByName = new Dictionary<string, Elf.SectionHeader>();
			foreach (var SectionHeader in this.SectionHeaders)
			{
				var SectionHeaderName = GetStringFromStringTable(SectionHeader.Name);
				this.SectionHeadersByName[SectionHeaderName] = SectionHeader;
			}

			Console.WriteLine("ProgramHeaders:{0}", this.ProgramHeaders.Length);
			foreach (var ProgramHeader in ProgramHeaders)
			{
				Console.WriteLine("{0}", ProgramHeader.ToStringDefault());
			}

			Console.WriteLine("SectionHeaders:{0}", this.SectionHeaders.Length);
			foreach (var SectionHeader in SectionHeaders)
			{
				Console.WriteLine("{0}:{1}", GetStringFromStringTable(SectionHeader.Name), SectionHeader.ToStringDefault());
			}

			if (NeedsRelocation && this.ProgramHeaders.Length > 1)
			{
				//throw (new NotImplementedException("Not implemented several ProgramHeaders yet using relocation"));
			}
		}
Exemple #21
0
        virtual public void Load(Stream FileStream)
        {
            FileStream = new MemoryStream(FileStream.ReadAll());

            this.FileStream = FileStream;

            this.Header = FileStream.ReadStruct <Elf.HeaderStruct>();
            if (this.Header.Magic != Elf.HeaderStruct.MagicEnum.ExpectedValue)
            {
                throw(new InvalidProgramException("Not an ELF File"));
            }

            if (this.Header.Machine != Elf.HeaderStruct.MachineEnum.ALLEGREX)
            {
                throw (new InvalidProgramException("Invalid Elf.Header.Machine"));
            }

            this.ProgramHeaders = FileStream.ReadStructVectorAt <Elf.ProgramHeader>(Header.ProgramHeaderOffset, Header.ProgramHeaderCount, Header.ProgramHeaderEntrySize);
            this.SectionHeaders = FileStream.ReadStructVectorAt <Elf.SectionHeader>(Header.SectionHeaderOffset, Header.SectionHeaderCount, Header.SectionHeaderEntrySize);

            this.NamesSectionHeader = this.SectionHeaders[Header.SectionHeaderStringTable];
            this.StringTable        = FileStream.SliceWithLength(this.NamesSectionHeader.Offset, this.NamesSectionHeader.Size).ReadAll();

            this.SectionHeadersByName = new Dictionary <string, Elf.SectionHeader>();
            foreach (var SectionHeader in this.SectionHeaders)
            {
                var SectionHeaderName = GetStringFromStringTable(SectionHeader.Name);
                this.SectionHeadersByName[SectionHeaderName] = SectionHeader;
            }

            Console.WriteLine("ProgramHeaders:{0}", this.ProgramHeaders.Length);
            foreach (var ProgramHeader in ProgramHeaders)
            {
                Console.WriteLine("{0}", ProgramHeader.ToStringDefault());
            }

            Console.WriteLine("SectionHeaders:{0}", this.SectionHeaders.Length);
            foreach (var SectionHeader in SectionHeaders)
            {
                Console.WriteLine("{0}:{1}", GetStringFromStringTable(SectionHeader.Name), SectionHeader.ToStringDefault());
            }

            if (NeedsRelocation && this.ProgramHeaders.Length > 1)
            {
                //throw (new NotImplementedException("Not implemented several ProgramHeaders yet using relocation"));
            }
        }
Exemple #22
0
        public Pmf Load(Stream Stream)
        {
            this.Stream = Stream;
            Header      = Stream.ReadStruct <HeaderStruct>();

            var Chunk = ReadChunk(Stream.SliceWithLength(0x50));

            InfoHeader = Chunk.Stream.ReadStruct <InfoHeaderStruct>();

            /*
             * Console.WriteLine("0x{0:X}", (ulong)InfoHeader.FirstTimestamp);
             * Console.WriteLine("0x{0:X}", (ulong)InfoHeader.LastTimestamp);
             * Console.WriteLine("{0}", (ulong)InfoHeader.Width);
             * Console.WriteLine("{0}", (ulong)InfoHeader.Height);
             */

            return(this);
        }
Exemple #23
0
 public Stream Open()
 {
     return(SliceStream.SliceWithLength());
 }
Exemple #24
0
        public HleModuleGuest LoadModule(Stream fileStream, Stream memoryStream, MemoryPartition memoryPartition,
                                         HleModuleManager moduleManager, string gameTitle, string moduleName, bool isMainModule)
        {
            HleModuleGuest = InjectContext.NewInstance <HleModuleGuest>();

            ElfLoader     = new ElfLoader();
            ModuleManager = moduleManager;

            var magic = fileStream.SliceWithLength(0, 4).ReadString(4);

            _logger.Info("Magic: '{0}'", magic);
            if (magic == "~PSP")
            {
                try
                {
                    var decryptedData = new EncryptedPrx().Decrypt(fileStream.ReadAll(), true);
                    File.WriteAllBytes("last_decoded_prx.bin", decryptedData);
                    fileStream = new MemoryStream(decryptedData);
                }
                catch (Exception exception)
                {
                    _logger.Error(exception);
                    throw;
                }
            }

            ElfLoader.Load(fileStream, moduleName);

            ElfConfig.InfoExeHasRelocation = ElfLoader.NeedsRelocation;

            if (ElfLoader.NeedsRelocation)
            {
                var dummyPartition = memoryPartition.Allocate(0x4000, Name: "Dummy");
                BaseAddress = memoryPartition.ChildPartitions.OrderByDescending(partition => partition.Size).First()
                              .Low;
                _logger.Info("BASE ADDRESS (Try    ): 0x{0:X}", BaseAddress);
                BaseAddress = MathUtils.NextAligned(BaseAddress, 0x1000);
                _logger.Info("BASE ADDRESS (Aligned): 0x{0:X}", BaseAddress);
            }
            else
            {
                BaseAddress = 0;
            }

            ElfConfig.RelocatedBaseAddress = BaseAddress;
            ElfConfig.GameTitle            = gameTitle;

            ElfLoader.AllocateAndWrite(memoryStream, memoryPartition, BaseAddress);

            LoadModuleInfo();

            if (ElfLoader.NeedsRelocation)
            {
                RelocateFromHeaders();
            }

            LoadModuleInfo();

            //Console.WriteLine(this.ModuleInfo.ToStringDefault());

            HleModuleGuest.InitInfo = new InitInfoStruct()
            {
                Pc = ElfLoader.Header.EntryPoint + BaseAddress,
                Gp = HleModuleGuest.ModuleInfo.Gp,
            };

            UpdateModuleImports();
            UpdateModuleExports();

            moduleManager.LoadedGuestModules.Add(HleModuleGuest);

            return(HleModuleGuest);
        }
Exemple #25
0
        public HleModuleGuest LoadModule(Stream FileStream, Stream MemoryStream, MemoryPartition MemoryPartition, HleModuleManager ModuleManager, String GameTitle, string ModuleName, bool IsMainModule)
        {
            this.HleModuleGuest = new HleModuleGuest(PspEmulatorContext);

            this.ElfLoader = new ElfLoader();
            this.ModuleManager = ModuleManager;

            var Magic = FileStream.SliceWithLength(0, 4).ReadString(4);
            Logger.Info("Magic: '{0}'", Magic);
            if (Magic == "~PSP")
            {
                try
                {
                    var DecryptedData = new EncryptedPrx().Decrypt(FileStream.ReadAll(), true);
                    File.WriteAllBytes("last_decoded_prx.bin", DecryptedData);
                    FileStream = new MemoryStream(DecryptedData);
                }
                catch (Exception Exception)
                {
                    Logger.Error(Exception);
                    throw (Exception);
                }
            }

            this.ElfLoader.Load(FileStream, ModuleName);

            PspEmulatorContext.PspConfig.InfoExeHasRelocation = this.ElfLoader.NeedsRelocation;

            if (this.ElfLoader.NeedsRelocation)
            {
                var DummyPartition = MemoryPartition.Allocate(
                    0x4000,
                    Name: "Dummy"
                );
                BaseAddress = MemoryPartition.ChildPartitions.OrderByDescending(Partition => Partition.Size).First().Low;
                Logger.Info("BASE ADDRESS (Try    ): 0x{0:X}", BaseAddress);
                BaseAddress = MathUtils.NextAligned(BaseAddress, 0x1000);
                Logger.Info("BASE ADDRESS (Aligned): 0x{0:X}", BaseAddress);
            }
            else
            {
                BaseAddress = 0;
            }

            PspEmulatorContext.PspConfig.RelocatedBaseAddress = BaseAddress;
            PspEmulatorContext.PspConfig.GameTitle = GameTitle;

            this.ElfLoader.AllocateAndWrite(MemoryStream, MemoryPartition, BaseAddress);

            if (this.ElfLoader.NeedsRelocation)
            {
                RelocateFromHeaders();
            }

            if (!ElfLoader.SectionHeadersByName.ContainsKey(".rodata.sceModuleInfo"))
            {
                throw(new Exception("Can't find segment '.rodata.sceModuleInfo'"));
            }

            HleModuleGuest.ModuleInfo = ElfLoader.SectionHeaderFileStream(ElfLoader.SectionHeadersByName[".rodata.sceModuleInfo"]).ReadStruct<ElfPsp.ModuleInfo>(); ;

            //Console.WriteLine(this.ModuleInfo.ToStringDefault());

            HleModuleGuest.InitInfo = new InitInfoStruct()
            {
                PC = ElfLoader.Header.EntryPoint + BaseAddress,
                GP = HleModuleGuest.ModuleInfo.GP + BaseAddress,
            };

            UpdateModuleImports();
            UpdateModuleExports();

            ModuleManager.LoadedGuestModules.Add(HleModuleGuest);

            return HleModuleGuest;
        }
Exemple #26
0
        public void HandleTexts(Action <TextEntry> ActionTextEntry, Action <StringInfo> ActionStringInfo, bool HandleType1 = true)
        {
            uint TextId        = 0;
            int  Lang          = 0;
            int  TextType      = -1;
            var  Text1         = new StringInfo[] { };
            var  Text2         = new StringInfo[] { };
            var  Stack         = new List <dynamic>();
            bool LastSeparator = true;

            foreach (var Instruction in ReadInstructions())
            {
                //Console.WriteLine("{0:X8}: {1}", Instruction.InstructionPosition, Instruction);

                switch (Instruction.Opcode)
                {
                case Opcode.UNK_0E:
                    switch (Instruction.InstructionData & 0xFFFF)
                    {
                    case 0x07: Lang = 1; break;

                    case 0x83: Lang = 2; break;
                    }
                    break;

                case Opcode.PUSH:
                {
                    var PushInstruction = (PushInstructionNode)Instruction;
                    if (PushInstruction.ParameterType == ValueType.String)
                    {
                        var StringInfo = new StringInfo(this, PushInstruction.IntValue, CodeStream.SliceWithLength(PushInstruction.InstructionPosition + 4, 4));
                        ActionStringInfo(StringInfo);
                        if (new[] { 1, 2 }.Contains(Lang))
                        {
                            if (Lang == 1)
                            {
                                Text1 = new[] { StringInfo }
                            }
                            ;
                            if (Lang == 2)
                            {
                                Text2 = new[] { StringInfo }
                            }
                            ;
                        }
                        else
                        {
                            //ActionStringInfo(StringInfo);
                        }
                    }
                    else
                    {
                        //Console.WriteLine("{0}", PushInstruction.ValueToPush.Value);
                        Stack.Add(PushInstruction.ValueToPush.Value);
                    }
                    Lang = 0;
                }
                break;

                case Opcode.FUNCTION_START:
                {
                    // Separator
                    //Console.WriteLine("------------------------------------");
                    if (!LastSeparator)
                    {
                        ActionTextEntry(null);
                        LastSeparator = true;
                    }
                }
                break;

                case Opcode.CALL:
                {
                    var CallInstruction = (CallInstructionNode)Instruction;

                    int TextFunc = 0;

                    if ((CallInstruction.FunctionType == FunctionType.Native) && (CallInstruction.NativeFunction == 1))
                    {
                        TextFunc = 1;
                    }
                    //if ((CallInstruction.FunctionType == FunctionType.Script) && ((new uint[] { 12, 0x12e30, }).Contains(CallInstruction.ScriptFunction))) TextFunc = 2;

                    bool AddEntry = true;

                    if (TextFunc > 0)
                    {
                        if (Text1.Length > 0 || Text2.Length > 0)
                        {
                            if (Stack.Count > 0)
                            {
                                if (TextFunc == 1)
                                {
                                    //Console.WriteLine("TEXT![1]");
                                    if (!HandleType1)
                                    {
                                        continue;
                                    }
                                    //Console.WriteLine("TEXT![1]");

                                    TextId = 0;
                                    try
                                    {
                                        var TextIdStr = String.Format("{0}", Stack[0]);
                                        //Console.WriteLine("TEXT![1] : {0}", TextIdStr);
                                        TextId = uint.Parse(TextIdStr);
                                    }
                                    catch
                                    {
                                    }

                                    if (TextId < 00010001)
                                    {
                                        //Console.WriteLine("{0}", Stack.Implode(","));
                                        //continue;
                                        AddEntry = false;
                                    }
                                    //Console.WriteLine("TEXT![3]");
                                }

                                if (AddEntry)
                                {
                                    ActionTextEntry(new TextEntry()
                                        {
                                            TextType   = TextType,
                                            Id         = TextId,
                                            Id2        = TextId,
                                            Original   = Text1,
                                            Translated = Text2,
                                        });
                                    LastSeparator = false;
                                }
                            }
                            //Console.WriteLine("############  AddText {0:D8}:('{1}', '{2}')", Stack[0], Text1.EscapeString(), Text2.EscapeString());
                        }
                    }
                    Text1    = new StringInfo[0];
                    Text2    = new StringInfo[0];
                    TextType = -1;
                    Stack.Clear();
                }
                break;

                case Opcode.PUSH_ARRAY:
                {
                    var PushArrayInstruction = (PushArrayInstructionNode)Instruction;

                    // Dialog. Using PTR1.
                    if (PushArrayInstruction.ArrayNumberOfElements == 6)
                    {
                        var E  = PushArrayInstruction.Elements.Cast <string>().ToArray();
                        var IE = PushArrayInstruction.IntElements;
                        TextType = IE[0];
                        int Unk = IE[1];
                        //Console.WriteLine("Dialog {0}, {1}, {2}", E[0], E[1], E[2]);
                        //Console.WriteLine("Dialog {0}, {1}, {2}", E[3], E[4], E[5]);
                        TextId = PushArrayInstruction.ArrayPointer + this.Header.TextStart;

                        Text1 = new[] {
                            new StringInfo(this, IE[2], TextStream.SliceWithLength(PushArrayInstruction.ArrayPointer + 4 * 2, 4)),
                            new StringInfo(this, IE[3], TextStream.SliceWithLength(PushArrayInstruction.ArrayPointer + 4 * 3, 4)),
                        };
                        Text2 = new[] {
                            new StringInfo(this, IE[4], TextStream.SliceWithLength(PushArrayInstruction.ArrayPointer + 4 * 4, 4)),
                            new StringInfo(this, IE[5], TextStream.SliceWithLength(PushArrayInstruction.ArrayPointer + 4 * 5, 4)),
                        };

                        ActionTextEntry(new TextEntry()
                            {
                                TextType   = TextType,
                                Id         = TextId,
                                Id2        = PushArrayInstruction.ArrayPointer,
                                Id3        = PushArrayInstruction.InstructionPosition,
                                Original   = Text1,
                                Translated = Text2,
                            });
                        LastSeparator = false;

                        Text1    = new StringInfo[0];
                        Text2    = new StringInfo[0];
                        TextType = -1;
                        Stack.Clear();

                        /*
                         * if (TextType != 0)
                         * {
                         *      Console.WriteLine(TextType);
                         *      Console.WriteLine("{0}", Text1.Implode("."));
                         *      Console.WriteLine("{0}", Text2.Implode(","));
                         * }
                         */
                        //Console.ReadKey();
                    }
                }
                break;
                }
            }
        }
Exemple #27
0
 public Stream LoadChunk(Stream Stream, uint Offset)
 {
     return ReadChunkIncludingTheSize(Stream.SliceWithLength(Offset));
 }
Exemple #28
0
        public void Load(Stream DatStream, Stream DavStream)
        {
            if (DavStream == null)
            {
                DavStream = DatStream;
            }
            this.DatStream = DatStream;
            this.DavStream = DavStream;

            Header = DatStream.ReadStruct <HeaderStruct>();
            var Magic = Encoding.ASCII.GetString(Header.Magic);

            if (Magic != "FPS4")
            {
                throw (new Exception(String.Format("Invalid Magic '{0}'", Magic)));
            }

            if (Header.FilePos != 0)
            {
                DatStream.Position = Header.FilePos;
                OriginalFilePath   = DatStream.ReadStringz(0x100, Encoding.GetEncoding("Shift-JIS"));
            }
            else
            {
                OriginalFilePath = "";
            }

            //Console.WriteLine("{0:X8}", Stream.Position);

            if (Header.ListCount > 10000)
            {
                throw (new Exception("List too big (" + Header.ListCount + ")"));
            }

            bool UseIndices = false;

            foreach (var Pass in new[] { false, true })
            {
                DatStream.Position = Header.ListStart;
                for (uint n = 0; n < Header.ListCount; n++)
                {
                    var  EntryOffset      = DatStream.Position;
                    var  EntryStream      = DatStream.ReadStream(Header.EntrySizeof);
                    var  EntryStruct      = default(EntryStruct);
                    var  ExtraEntrySizeof = Header.EntrySizeof - 0x0C;
                    var  IndexName        = String.Format("{0}", n);
                    var  Name             = "";
                    uint MappedFileIndex  = 0;
                    uint StringOffset     = 0;

                    // @TODO: EntryFormat probably is a bitfield
                    //        or a composed enum + bit field
                    //        I don't know the bit mapping.
                    switch ((int)Header.EntryFormat)
                    {
                    case 0x8D:
                        EntryStruct.Offset     = EntryStream.ReadStruct <uint_be>();
                        EntryStruct.LengthReal = EntryStruct.LengthSectorAligned = EntryStream.ReadStruct <uint_be>();
                        Name            = EntryStream.ReadStringz(0x20);
                        MappedFileIndex = EntryStream.ReadStruct <uint_be>();
                        break;

                    case 0x47:
                    {
                        EntryStruct  = EntryStream.ReadStruct <EntryStruct>();
                        StringOffset = EntryStream.ReadStruct <uint_be>();
                        if (StringOffset != 0)
                        {
                            var NameStream = DatStream.SliceWithLength(StringOffset, 0x1000);
                            Name = NameStream.ReadStringz();
                            //File.WriteAllBytes("c:/temp/name" + StringOffset + ".bin", NameStream.Slice().ReadAll());
                            //Console.WriteLine("{0:X8}: '{1}'", StringOffset, Name);
                        }
                        else
                        {
                            if (EntryStruct.LengthReal == 0)
                            {
                                continue;
                            }
                        }
                    }
                    break;

                    case 0x4F:
                    {
                        EntryStruct     = EntryStream.ReadStruct <EntryStruct>();
                        Name            = EntryStream.ReadStringz(0x20);
                        MappedFileIndex = EntryStream.ReadStruct <uint_be>();
                    }
                    break;

                    default:
                    {
                        EntryStruct = EntryStream.ReadStruct <EntryStruct>();
                        Name        = EntryStream.ReadStringz(ExtraEntrySizeof);

                        switch (ExtraEntrySizeof)
                        {
                        case 0:
                        {
                        }
                        break;

                        case 4:
                        {
                            StringOffset = EntryStream.ReadStruct <uint>();
                            // Pointer to string name.
                            if (StringOffset != 0)
                            {
                                throw (new NotImplementedException());
                            }
                        }
                        break;

                        default:
                        {
                            EntryStream.Position = EntryStream.Length - ExtraEntrySizeof;                                                              // (0xC para common.svo y btl.svo, en los otros no sé) --- Apaño temporal
                            Name = EntryStream.ReadStringz(ExtraEntrySizeof);
                        }
                        break;
                        }

                        //Console.WriteLine("OFF:{0:X8}", EntryOffset);
                        //Console.WriteLine("STR:{0}", EntryStruct.ToStringDefault());
                        //Console.WriteLine("NAM'{0}'({1})", Name, Name.Length);
                    }
                    break;
                    }

                    //Console.WriteLine("Name: {0}", Name);

                    if (n == Header.ListCount - 1)
                    {
                        // Ignore last element with an empty name.
                        if (Name.Length == 0 && EntryStruct.LengthReal == 0)
                        {
                            continue;
                        }
                    }

                    if (IndexName.Length == 0)
                    {
                        IndexName = String.Format("{0}", n);
                    }

                    if (Name.Length == 0)
                    {
                        UseIndices = true;
                    }

                    if (UseIndices)
                    {
                        Name = IndexName;
                    }

                    //Console.WriteLine("Name: '{0}'", Encoding.UTF8.GetBytes(Name).ToStringArray());

                    if (Entries.ContainsKey(Name))
                    {
                        //Console.Error.WriteLine("Warning: Name '{0}' already contained", Name);
                        Name = n + "." + Name;
                    }

                    if (Pass)
                    {
                        var Entry = new Entry(this, EntryStruct, Name);
                        Entry.MappedFileIndex = MappedFileIndex;
                        Entry.Index           = n;
                        Entries[Name]         = Entry;
                    }
                }
            }
        }
Exemple #29
0
        public Xex LoadHeader(Stream XexStream)
        {
            Header = XexStream.ReadStruct<HeaderStruct>();
            var OptionalHeaders = XexStream.ReadStructVector<OptionalHeader>(Header.OptionalHeaderCount);
            Console.WriteLine("{0:X}", XexStream.Position);
            InfoList = new Dictionary<OptionalHeader.Ids, ulong>();
            foreach (var OptionalHeader in OptionalHeaders)
            {
                //Console.WriteLine("{0}: 0x{1:X}", OptionalHeader.Id, (uint)OptionalHeader.Data);
                //InfoList[OptionalHeader.Id] = OptionalHeader.Data;
                InfoList.Add(OptionalHeader.Id, OptionalHeader.Data);

                switch (OptionalHeader.Id)
                {
                    case Xex.OptionalHeader.Ids.OriginalPEName:
                        this.OriginalPeName = LoadChunk(XexStream, OptionalHeader.Data).ReadStringz(Encoding: Encoding.UTF8);
                        break;
                    case Xex.OptionalHeader.Ids.LANKey:
                        this.LanKey = XexStream.SliceWithLength(OptionalHeader.Data, 0x10).ReadAll();
                        break;
                    case Xex.OptionalHeader.Ids.DefaultStackSize:
                        this.DefaultStackSize = OptionalHeader.Data;
                        break;
                    case Xex.OptionalHeader.Ids.ChecksumTimestamp:
                        this.ChecksumTimestamp = XexStream.SliceWithLength(OptionalHeader.Data).ReadStruct<ChecksumTimestampStruct>();
                        break;
                    case Xex.OptionalHeader.Ids.ImageBaseAddress:
                        this.ImageBaseAddress = OptionalHeader.Data;
                        break;
                    case Xex.OptionalHeader.Ids.EntryPoint:
                        this.EntryPoint = OptionalHeader.Data;
                        break;
                    case Xex.OptionalHeader.Ids.StaticLibraries:
                        this.StaticLibs = LoadChunk(XexStream, OptionalHeader.Data).ReadStructVectorUntilTheEndOfStream<StaticLib>();
                        foreach (var StaticLib in StaticLibs)
                        {
                            Console.WriteLine("StaticLib: {0}", StaticLib.ToStringDefault());
                        }
                        break;
                    case Xex.OptionalHeader.Ids.ImportLibraries:
                        {
                            var ImportLibrariesStream = LoadChunk(XexStream, OptionalHeader.Data);
                            var TextLength = (uint)ImportLibrariesStream.ReadStruct<uint_be>();
                            var LibraryCount = (uint)ImportLibrariesStream.ReadStruct<uint_be>();
                            var TextStream = ImportLibrariesStream.ReadStream(TextLength);

                            var LibraryNames = new String[LibraryCount];
                            for (int n = 0; n < LibraryCount; n++)
                            {
                                LibraryNames[n] = TextStream.ReadStringz(AllowEndOfStream: false);
                                Console.WriteLine("ImportLib: {0}", LibraryNames[n]);
                            }

                            var ChunkUnk1 = ReadChunkIncludingTheSize(ImportLibrariesStream);
                            var ImportAddressList = ReadChunkIncludingTheSize(ImportLibrariesStream);
                            Console.Error.WriteLine("@TODO: Xex.OptionalHeader.Ids.ImportLibraries");
                        }
                        break;
                    case Xex.OptionalHeader.Ids.TLSInfo:
                        {
                            this.TLSInfo = XexStream.SliceWithLength(OptionalHeader.Data).ReadStruct<TLSInfoStruct>();
                        }
                        break;
                    default:
                        Console.WriteLine("{0}: 0x{1:X}", OptionalHeader.Id, (uint)OptionalHeader.Data);
                        break;
                }
            }
            PeStream = XexStream.SliceWithLength(Header.PeDataOffset);
            Pe = new Pe().LoadHeader(PeStream);

            Console.WriteLine("SecurityInfoOffset: {0:X}", (uint)Header.SecurityInfoOffset);
            var SecurityStream = LoadChunk(XexStream, Header.SecurityInfoOffset);
            var NumberOfSections = (ushort)SecurityStream.ReadStruct<ushort_be>();
            Console.WriteLine("NumberOfSections: {0:X}", NumberOfSections);

            return this;
        }
Exemple #30
0
		/// <summary>
		/// Function that writtes all the mappings into another stream.
		/// Useful for patching a file or memory.
		/// </summary>
		/// <param name="TargetStream">Stream to write the mapped contents to</param>
		public void WriteSegmentsToStream(Stream TargetStream)
		{
			foreach (var StreamEntry in _StreamEntries)
			{
				var SourceSliceStream = StreamEntry.Stream.SliceWithLength(0, StreamEntry.Length);
				var TargetSliceStream = TargetStream.SliceWithLength(StreamEntry.Position, StreamEntry.Length);
				SourceSliceStream.CopyToFast(TargetSliceStream);
			}
		}