public Packfile(Stream stream, bool isStr2)
        {
            IsStr2 = isStr2;
            stream.Seek(0, SeekOrigin.Begin);
            FileData = stream.ReadStruct<PackfileFileData>();

            m_Files = new List<IPackfileEntry>();

            uint runningPosition = 0;
            List<PackfileEntryFileData> entryFileData = new List<PackfileEntryFileData>();
            for (int i = 0; i < FileData.NumFiles; i++)
            {
                PackfileEntryFileData data = stream.ReadStruct<PackfileEntryFileData>();

                if (IsCondensed && IsCompressed)
                {
                    data.Flags = 0;
                    data.Start = runningPosition;
                    runningPosition += data.Size;
                }
                else if (IsCondensed)
                {
                    data.Start = runningPosition;
                    runningPosition += data.Size.Align(16);
                }

                entryFileData.Add(data);
            }

            for (int i = 0; i < FileData.NumFiles; i++)
            {
                stream.Align(2);
                string filename = stream.ReadAsciiNullTerminatedString();
                stream.Seek(1, SeekOrigin.Current);
                m_Files.Add(new PackfileEntry(this, entryFileData[i], filename));
                stream.Align(2);
            }

            if (IsCondensed && IsCompressed)
            {
                DataOffset = 0;
                byte[] compressedData = new byte[FileData.CompressedDataSize];
                stream.Read(compressedData, 0, (int)FileData.CompressedDataSize);
                using (MemoryStream tempStream = new MemoryStream(compressedData))
                {
                    using (Stream s = new ZlibStream(tempStream, CompressionMode.Decompress, true))
                    {
                        byte[] uncompressedData = new byte[FileData.DataSize];
                        s.Read(uncompressedData, 0, (int)FileData.DataSize);
                        DataStream = new MemoryStream(uncompressedData);
                    }
                }
                
            }
            else
            {
                DataStream = stream;
                DataOffset = stream.Position;
            }
        }
        public Packfile(Stream stream)
        {
            DataStream = stream;

            stream.Seek(0, SeekOrigin.Begin);
            FileData = stream.ReadStruct <PackfileFileData>();

            m_Files = new List <IPackfileEntry>();

            stream.Seek(GetEntryDataOffset(), SeekOrigin.Begin);

            List <PackfileEntryFileData> entryFileData = new List <PackfileEntryFileData>();

            for (int i = 0; i < FileData.IndexCount; i++)
            {
                var fileData = stream.ReadStruct <PackfileEntryFileData>();
                entryFileData.Add(fileData);
            }

            List <string> fileNames = new List <string>();

            for (int i = 0; i < FileData.IndexCount; i++)
            {
                var fileData = entryFileData[i];
                stream.Seek(CalculateEntryNamesOffset() + fileData.FilenameOffset, SeekOrigin.Begin);
                string name = stream.ReadAsciiNullTerminatedString();

                stream.Seek(CalculateExtensionsOffset() + fileData.ExtensionOffset, SeekOrigin.Begin);
                string extension = stream.ReadAsciiNullTerminatedString();

                m_Files.Add(new PackfileEntry(this, fileData, name + "." + extension));
            }
        }
        public Packfile(Stream stream)
        {
            DataStream = stream;

            stream.Seek(0, SeekOrigin.Begin);
            FileData = stream.ReadStruct<PackfileFileData>();

            m_Files = new List<IPackfileEntry>();

            stream.Seek(GetEntryDataOffset(), SeekOrigin.Begin);

            List<PackfileEntryFileData> entryFileData = new List<PackfileEntryFileData>();

            for (int i = 0; i < FileData.IndexCount; i++)
            {
                var fileData = stream.ReadStruct<PackfileEntryFileData>();
                entryFileData.Add(fileData);
            }

            List<string> fileNames = new List<string>();
            for (int i = 0; i < FileData.IndexCount; i++)
            {
                var fileData = entryFileData[i];
                stream.Seek(CalculateEntryNamesOffset() + fileData.FilenameOffset, SeekOrigin.Begin);
                string name = stream.ReadAsciiNullTerminatedString();

                stream.Seek(CalculateExtensionsOffset() + fileData.ExtensionOffset, SeekOrigin.Begin);
                string extension = stream.ReadAsciiNullTerminatedString();

                m_Files.Add(new PackfileEntry(this, fileData, name + "." + extension));
            }
        }
        public Packfile(Stream stream, bool isStr2)
        {
            IsStr2 = isStr2;
            stream.Seek(0, SeekOrigin.Begin);
            FileData = stream.ReadStruct <PackfileFileData>();

            m_Files = new List <IPackfileEntry>();

            uint runningPosition = 0;
            List <PackfileEntryFileData> entryFileData = new List <PackfileEntryFileData>();

            for (int i = 0; i < FileData.NumFiles; i++)
            {
                PackfileEntryFileData data = stream.ReadStruct <PackfileEntryFileData>();

                if (IsCondensed && IsCompressed)
                {
                    data.Flags       = 0;
                    data.Start       = runningPosition;
                    runningPosition += data.Size;
                }
                else if (IsCondensed)
                {
                    data.Start       = runningPosition;
                    runningPosition += data.Size.Align(16);
                }

                entryFileData.Add(data);
            }

            for (int i = 0; i < FileData.NumFiles; i++)
            {
                stream.Align(2);
                string filename = stream.ReadAsciiNullTerminatedString();
                stream.Seek(1, SeekOrigin.Current);
                m_Files.Add(new PackfileEntry(this, entryFileData[i], filename));
                stream.Align(2);
            }

            if (IsCondensed && IsCompressed)
            {
                DataOffset = 0;
                byte[] compressedData = new byte[FileData.CompressedDataSize];
                stream.Read(compressedData, 0, (int)FileData.CompressedDataSize);
                using (MemoryStream tempStream = new MemoryStream(compressedData))
                {
                    using (Stream s = new ZlibStream(tempStream, CompressionMode.Decompress, true))
                    {
                        byte[] uncompressedData = new byte[FileData.DataSize];
                        s.Read(uncompressedData, 0, (int)FileData.DataSize);
                        DataStream = new MemoryStream(uncompressedData);
                    }
                }
            }
            else
            {
                DataStream = stream;
                DataOffset = stream.Position;
            }
        }
        public StreamingSoundbank(Stream s)
        {
            DataStream = new MemoryStream();
            s.CopyTo(DataStream);

            DataStream.Seek(0, SeekOrigin.Begin);

            Header = DataStream.ReadStruct <SoundbankHeader>();

            if (Header.Signature != 0x42535756)
            {
                throw new InvalidDataException("File is not a streaming soundbank.");
            }

            for (int i = 0; i < Header.NumFiles; i++)
            {
                var fileInfo = DataStream.ReadStruct <SoundbankEntryInfo>();

                if ((fileInfo.MetadataLength % 2048) != 0)
                {
                    throw new Exception();
                }

                if ((fileInfo.Offset % 2048) != 0)
                {
                    throw new Exception();
                }

                var entry = new SoundbankEntry(this, fileInfo);
                Files.Add(entry);
            }
        }
Example #6
0
        public bool IsFatxDevice()
        {
            Stream.Position = 0;
            var devkitTable = Stream.ReadStruct <FATX_DEVKIT_PARTITION_TABLE>();

            devkitTable.EndianSwap();
            if (devkitTable.IsValid)
            {
                return(true);
            }
            foreach (var partition in kXboxPartitions)
            {
                if (DriveSize <= partition.Item2)
                {
                    continue;
                }

                Stream.Seek(partition.Item2, SeekOrigin.Begin);
                var fatxHeader = Stream.ReadStruct <FAT_VOLUME_METADATA>();
                if (fatxHeader.IsValid)
                {
                    return(true);
                }
            }

            return(false);
        }
        public AudioMetadata(Stream stream, IGameInstance instance)
        {
            Instance = instance;

            Header = stream.ReadStruct<AudioMetadataHeader>();
            
            if (Header.LipsyncSize > 0)
            {
                stream.Seek(0x24 + Header.LipsyncOffset, SeekOrigin.Begin);
                LipsyncData = new byte[Header.LipsyncSize];
                stream.Read(LipsyncData, 0, LipsyncData.Length);
            }

            if (Header.SubtitleSize > 0)
            {
                stream.Seek(0x24 + Header.SubtitleOffset, SeekOrigin.Begin);
                SubtitleHeader = stream.ReadStruct<AudioMetadataSubtitleHeader>();

                long subtitleOffset = stream.Position;
               
                for (int i = 0; i < SubtitleHeader.LocalizedVoiceSubtitleHeaders.Length; i++)
                {
                    LocalizedVoiceSubtitleHeader localizedVoiceSubtitleHeader = SubtitleHeader.LocalizedVoiceSubtitleHeaders[i];
                    Language language = (Language)i;

                    if (localizedVoiceSubtitleHeader.Length == 0)
                    {
                        Subtitles.Add(language, "");

                        continue;
                    }

                    long offset = subtitleOffset + localizedVoiceSubtitleHeader.Offset;
                    stream.Seek(offset, SeekOrigin.Begin);
                    byte[] subtitleData = new byte[localizedVoiceSubtitleHeader.Length];
                    stream.Read(subtitleData, 0, (int)localizedVoiceSubtitleHeader.Length);

                    var map = LanguageUtility.GetDecodeCharMap(instance, language);

                    StringBuilder subtitleBuilder = new StringBuilder();
                    for (int pos = 0; pos < subtitleData.Length; pos+=2)
                    {
                        char src = BitConverter.ToChar(subtitleData, pos);

                        char value = src;
                        if (map.ContainsKey(src))
                            value = map[src];

                        if (value == 0x00)
                            continue;

                        subtitleBuilder.Append(value);
                    }

                    string subtitle = subtitleBuilder.ToString();
                    Subtitles.Add(language, subtitle);
                }
            }
        }
Example #8
0
        public ClothSimulationFile(Stream s)
        {
            Header = s.ReadStruct <ClothSimulationHeader>();

            Nodes               = new List <SimulatedNodeInfo>();
            NodeLinks           = new List <SimulatedNodeLinkInfo>();
            Ropes               = new List <ClothSimRopeInfo>();
            RopeNodes           = new List <List <uint> >();
            RopeLinks           = new List <List <uint> >();
            CollisionPrimitives = new List <ClothSimCollisionPrimitiveInfo>();

            for (int i = 0; i < Header.NumNodes; i++)
            {
                SimulatedNodeInfo sni = s.ReadStruct <SimulatedNodeInfo>();
                Nodes.Add(sni);
            }

            for (int i = 0; i < Header.NumNodeLinks; i++)
            {
                SimulatedNodeLinkInfo snli = s.ReadStruct <SimulatedNodeLinkInfo>();
                NodeLinks.Add(snli);
            }

            for (int i = 0; i < Header.NumRopes; i++)
            {
                ClothSimRopeInfo csri = s.ReadStruct <ClothSimRopeInfo>();
                Ropes.Add(csri);
            }

            for (int i = 0; i < Header.NumRopes; i++)
            {
                ClothSimRopeInfo csri      = Ropes[i];
                List <UInt32>    ropeNodes = new List <uint>();

                for (int j = 0; j < csri.NumNodes; j++)
                {
                    uint ropeNode = s.ReadUInt32();
                    ropeNodes.Add(ropeNode);
                }

                RopeNodes.Add(ropeNodes);

                List <UInt32> ropeLinks = new List <uint>();

                for (int j = 0; j < csri.NumLinks; j++)
                {
                    uint ropeLink = s.ReadUInt32();
                    ropeLinks.Add(ropeLink);
                }

                RopeLinks.Add(ropeLinks);
            }

            for (int i = 0; i < Header.NumColliders; i++)
            {
                ClothSimCollisionPrimitiveInfo cscpi = s.ReadStruct <ClothSimCollisionPrimitiveInfo>();
                CollisionPrimitives.Add(cscpi);
            }
        }
Example #9
0
 public override void Deserialize(Stream stream, GameStateSerializer serializer)
 {
     animationCountdown       = stream.ReadStruct <Counter>();
     animationIndex           = stream.ReadStruct <Counter>();
     directionChangeCountdown = stream.ReadStruct <Counter>();
     currentOrientation       = stream.ReadStruct <ObjectOrientation>();
     headingOrientation       = stream.ReadStruct <ObjectOrientation>();
     base.Deserialize(stream, serializer);
 }
Example #10
0
 public override void Deserialize(Stream stream, GameStateSerializer serializer)
 {
     spawnCooldown                  = stream.ReadStruct <Counter>();
     surfingSpawnCooldown           = stream.ReadStruct <Counter>();
     surfingSpawnCooldownNonRounded = stream.ReadFloat();
     penguinDurationBonus           = stream.ReadFloat();
     penguinDestroyBonus            = stream.ReadFloat();
     base.Deserialize(stream, serializer);
 }
Example #11
0
        // Ref 16 bit:  https://blogs.msdn.microsoft.com/oldnewthing/20040618-00/?p=38803
        // Ref 32 bit: https://blogs.msdn.microsoft.com/oldnewthing/20040621-00/?p=38793
        public static byte[] ConvertDialogTemplate(Stream strm)
        {
            var ms = new MemoryStream();

            // Convert header
            var header16 = strm.ReadStruct <Win16.DLGHEADER>();

            header16.x  = (ushort)(header16.x * 118 / 100);
            header16.cx = (ushort)(header16.cx * 118 / 100);
            ms.WriteStruct(header16.Convert());

            // Convert strings
            ms.WriteResourceString32(strm.ReadResourceString16());      // Menu name
            ms.WriteResourceString32(strm.ReadResourceString16());      // Class name
            ms.WriteResourceString32(strm.ReadResourceString16());      // Title

            // Font?
            if ((header16.dwStyle & Win16.DS_SETFONT) != 0)
            {
                ms.WriteUInt16(strm.ReadUInt16());                      // Point size
                ms.WriteUnicodeString(strm.ReadNullTerminatedString()); // Font name
            }

            // Convert all controls
            for (int i = 0; i < header16.cItems; i++)
            {
                ms.Pad(4);

                // Common header
                var item16 = strm.ReadStruct <Win16.DLGITEMHEADER>();
                item16.x  = (ushort)(item16.x * 118 / 100);
                item16.cx = (ushort)(item16.cx * 118 / 100);
                ms.WriteStruct(item16.Convert());

                // Class name
                ms.WriteResourceString32(strm.ReadResourceString16(true), true);

                // Control text
                ms.WriteResourceString32(strm.ReadResourceString16(), true);

                // Extra data
                var byteCount = strm.ReadByte();
                ms.WriteUInt16((ushort)byteCount);
                if (byteCount > 0)
                {
                    var buf = new byte[byteCount];
                    strm.Read(buf, 0, buf.Length);
                    ms.Write(buf, 0, buf.Length);
                }
            }

            var data = ms.ToArray();

            System.IO.File.WriteAllBytes("dlg.bin", data);
            return(data);
        }
Example #12
0
        public static Win16.GroupIcon LoadIconOrCursorGroup(Stream strm)
        {
            var g = new Win16.GroupIcon();

            g.Directory = strm.ReadStruct <Win16.GRPICONDIR>();
            for (int i = 0; i < g.Directory.idCount; i++)
            {
                var de = strm.ReadStruct <Win16.GRPICONDIRENTRY>();
                g.Entries.Add(de);
            }
            return(g);
        }
Example #13
0
 public BattleBinFileHeader ReadHeader()
 {
     _header = _input.ReadStruct <BattleBinFileHeader>();
     if (_header.Count != 8)
     {
         throw new Exception();
     }
     if (_header.DescriptorOffset != 0x30)
     {
         throw new NotSupportedException();
     }
     return(_header);
 }
Example #14
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);
        }
Example #15
0
        /// <summary>
        /// Decompresses and copies a segment of zsize bytes from a stream to another stream
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="outStream"></param>
        /// <param name="zSize"></param>
        /// <param name="size"></param>
        /// <exception cref="Exception"></exception>
        /// <exception cref="DecompressionException"></exception>
        public static void DecompressAndCopySegment(this Stream stream, Stream outStream, uint zSize, uint size)
        {
            if (zSize == size)
            {
                stream.CopyToWithLength(outStream, (int)zSize);
            }
            else
            {
                var oodleCompression = stream.ReadStruct <uint>();
                if (oodleCompression == KARK)
                {
                    var headerSize = stream.ReadStruct <uint>();
                    if (headerSize != size)
                    {
                        throw new Exception($"Buffer size doesn't match size in info table. {headerSize} vs {size}");
                    }

                    var inputBuffer = new byte[(int)zSize - 8];
                    stream.Read(inputBuffer);
                    var outputBuffer = new byte[size];

                    long unpackedSize = OodleHelper.Decompress(inputBuffer, outputBuffer);

                    if (unpackedSize != size)
                    {
                        throw new DecompressionException(
                                  $"Unpacked size {unpackedSize} doesn't match real size {size}.");
                    }

                    outStream.Write(outputBuffer);

                    // try
                    // {
                    //
                    // }
                    // catch (DecompressionException)
                    // {
                    //     //logger.LogString(e.Message, Logtype.Error);
                    //     //logger.LogString(
                    //     //    $"Unable to decompress file {hash.ToString()}. Exporting uncompressed file",
                    //     //    Logtype.Error);
                    //     stream.CopyTo(outStream);
                    // }
                }
                else
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.CopyToWithLength(outStream, (int)zSize);
                }
            }
        }
        public static RpmPackage Read(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!stream.CanSeek)
            {
                throw new ArgumentOutOfRangeException(nameof(stream), "A stream which backs a RPM package must be seekable");
            }

            RpmPackage package = new RpmPackage();

            package.Stream = stream;

            package.Lead = stream.ReadStruct <RpmLead>();

            package.Signature = ReadSection <SignatureTag>(stream, h => (SignatureTag)h.Tag);

            if (stream.Position % 8 != 0)
            {
                stream.Position += 8 - (stream.Position % 8);
            }

            package.HeaderOffset = stream.Position;
            package.Header       = ReadSection <IndexTag>(stream, h => (IndexTag)h.Tag);

            package.PayloadOffset = stream.Position;

            return(package);
        }
        public Container(Stream stream)
        {
            UInt16 stringLength = stream.ReadUInt16();
            Name = stream.ReadAsciiString(stringLength);
            ContainerType = stream.ReadUInt8();
            Flags = (ContainerFlags)stream.ReadUInt16();
            PrimitiveCount = stream.ReadUInt16();
            PackfileBaseOffset = stream.ReadUInt32();
            CompressionType = stream.ReadUInt8();
            stringLength = stream.ReadUInt16();
            StubContainerParentName = stream.ReadAsciiString(stringLength);
            Int32 auxDataSize = stream.ReadInt32();
            AuxData = new byte[auxDataSize];
            stream.Read(AuxData, 0, auxDataSize);
            TotalCompressedPackfileReadSize = stream.ReadInt32();

            Primitives = new List<Primitive>();
            PrimitiveSizes = new List<WriteTimeSizes>();

            for (UInt16 i = 0; i < PrimitiveCount; i++)
            {
                var sizes = stream.ReadStruct<WriteTimeSizes>();
                PrimitiveSizes.Add(sizes);
            }

            for (UInt16 i = 0; i < PrimitiveCount; i++)
            {
                Primitive primitive = new Primitive(stream);
                Primitives.Add(primitive);
            }
        }
Example #18
0
        public static ObjectsTable ReadObjectsTable(Stream data)
        {
            /*var baseArcHeader = archiveHeader is BaseHeader
             *  ? (BaseHeader) archiveHeader
             *  : ((DX11Header) archiveHeader).baseHeader;*/
            ObjectsTable result = new ObjectsTable();

            result.header                 = data.ReadStruct <ObjectsTable.Header>();
            result.typeDescriptors        = data.ReadStructArray <ObjectsTable.TypeDescriptor>(result.header.typeCount).ToArray();
            result.classDescriptors       = data.ReadStructArray <ObjectsTable.ClassDescriptor>(result.header.classCount).ToArray();
            result.classMemberDescriptors = data.ReadStructArray <ObjectsTable.ClassMemberDescriptor>(result.header.classMemberCount).ToArray();
            result.stringTable            = data.ReadBytes((int)result.header.stringTableSize);

            var s0 = Marshal.SizeOf <ObjectsTable.Header>();
            var s1 = Marshal.SizeOf <ObjectsTable.TypeDescriptor>() * result.header.typeCount;
            var s2 = Marshal.SizeOf <ObjectsTable.ClassDescriptor>() * result.header.classCount;
            var s3 = Marshal.SizeOf <ObjectsTable.ClassMemberDescriptor>() * result.header.classMemberCount;
            var s4 = result.header.stringTableSize;

            var paddingSize = result.header.size - (s0 + s1 + s2 + s3 + s4);

            if (paddingSize != 0)
            {
                data.ReadBytes((int)paddingSize);
            }
            return(result);
        }
Example #19
0
        public static object ReadHeader(Stream data)
        {
            var baseHeader = data.ReadStruct <BaseHeader>();
            var baseSize   = Marshal.SizeOf <BaseHeader>();

            if (baseHeader.size < baseSize)
            {
                throw new Exception("Unexpected header size");
            }

            if (baseHeader.size == baseSize)
            {
                return(baseHeader);
            }

            if (baseHeader.platformId.Value == 0x44583131)
            {
                //dx11 platform
                var         dx11Size        = Marshal.SizeOf <DX11Header>();
                var         extraBytesCount = dx11Size - baseSize;
                var         extraBytes      = data.ReadBytes(extraBytesCount);
                var         baseBytes       = MemoryUtils.StructToBytes(baseHeader);
                List <byte> dx11Bytes       = new List <byte>();
                dx11Bytes.AddRange(baseBytes);
                dx11Bytes.AddRange(extraBytes);
                return(MemoryUtils.BytesToStruct <DX11Header>(dx11Bytes.ToArray()));
            }
            throw new Exception("Unknown platform");
        }
Example #20
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);
        }
Example #21
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;
        }
Example #22
0
        public static Sprite Read(Stream stream)
        {
            ShpHeader header = stream.ReadStruct <ShpHeader>();

            ShpOffset[] offsets = new ShpOffset[2 + header.nframes];
            for (uint i = 0; i < offsets.Length; i++)
            {
                offsets[i] = stream.ReadStruct <ShpOffset>();
            }

            int frame_w = header.width;
            int frame_h = header.height;

            byte[][] frames = Decode(stream, offsets, frame_w, frame_h, header.nframes);

            return(new Sprite(frames, frame_w, frame_h));
        }
Example #23
0
        public static TimHeader Read(Stream input)
        {
            TimHeader result = input.ReadStruct <TimHeader>();

            result.Validate();

            return(result);
        }
Example #24
0
        public static ResourceEntry Load(Stream stream)
        {
            var entry = new ResourceEntry();

            entry.Header = stream.ReadStruct <LfdHeader>();
            entry.LoadData(stream);
            return(entry);
        }
        public StreamingSoundbank(Stream s)
        {
            DataStream = new MemoryStream();
            s.CopyTo(DataStream);

            DataStream.Seek(0, SeekOrigin.Begin);

            Header = DataStream.ReadStruct<SoundbankHeader>();

            if (Header.Signature != 0x42535756)
                throw new InvalidDataException("File is not a streaming soundbank.");

            for (int i = 0; i < Header.NumFiles; i++)
            {
                var fileInfo = DataStream.ReadStruct<SoundbankEntryInfo>();
                var entry = new SoundbankEntry(this, fileInfo);
                Files.Add(entry);
            }
        }
Example #26
0
        /*
         *
         * Programming Guide for DDS
         * https://msdn.microsoft.com/en-us/library/windows/desktop/bb943991(v=vs.85).aspx#File_Layout1
         *
         * File Structure
         *
         * DWORD               dwMagic;
         * DDS_HEADER          header;
         *
         * If the DDS_PIXELFORMAT dwFlags is set to DDPF_FOURCC and dwFourCC is set to "DX10" an additional DDS_HEADER_DXT10
         *
         * DDS_HEADER_DXT10    header10;
         *
         * A pointer to an array of bytes that contains the main surface data.
         *
         * BYTE bdata[]
         *
         * BYTE bdata2[]
         *
         */
        public static DDS read(Stream stream)
        {
            var dds = new DDS();

            int readIndex = 0;

            // Read headers

            DDS_Magic fileMagicData;

            readIndex += stream.ReadStruct(out fileMagicData);

            readIndex += stream.ReadStruct(out dds.ddsHeader);

            // Only read the ddsHeaderDXT10 when the FOURCC.DX10 is set
            if (dds.ddsHeader.ddspf.dwFourCC == DDS_PIXELFORMAT.FOURCC.DX10)
            {
                readIndex += stream.ReadStruct(out dds.ddsHeaderDXT10);
            }

            if (dds.ddsHeader.ddspf.dwFourCC != DDS_PIXELFORMAT.FOURCC.DXT1 ||
               (dds.ddsHeader.dwFlags & DDS_HEADER.Flags.DDSD_LINEARSIZE) == 0)
            {
                throw new NotImplementedException("Format not implemented");
            }

            // Initialize and read DXT1 blocks

            var size = dds.height * dds.width;

            dds.blocks = new DXT1Block[size];

            for (uint i = 0; i < size; i++)
            {
                DDS_DXT1Block block;
                readIndex += stream.ReadStruct(out block);

                dds.blocks[i] = block;
            }

            return dds;
        }
Example #27
0
 public Chunk ReadChunk(Stream Stream)
 {
     var ChunkSize = (uint)Stream.ReadStruct<uint_be>();
     //var ChunkType = (ushort)Stream.ReadStruct<ushort_be>();
     var ChunkStream = Stream.ReadStream(ChunkSize);
     return new Chunk()
     {
         Size = ChunkSize,
         //Type = ChunkType,
         Stream = ChunkStream,
     };
 }
Example #28
0
 public void Load(Stream Stream)
 {
     Entries = new Dictionary<string, Entry>();
     Stream.Position = 8;
     while (Stream.Position < Stream.Length)
     {
         var Entry = Stream.ReadStruct<Entry>();
         if (Entry.ImageId != 0)
         {
             Entries.Add(Entry.Name, Entry);
         }
     }
 }
Example #29
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;
        }
Example #30
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"));
			}
		}
        public SaveFile(Stream s)
        {
            MainHeader = s.ReadStruct<SaveGameMainHeader>();

            while (s.Position < s.Length)
            {
                long sectionStart = s.Position;
                Section section = new Section(s);
                if (section.Size == 0 && section.Version == 0)
                    break;
                
                Console.WriteLine("Got {0} ({4:X2}) at {3:X4}. Version {1:X2}, {2:X4} bytes.", section.SectionId, section.Version, section.Size, sectionStart, (uint)section.SectionId);
                Sections.Add(section.SectionId, section);
            }

            Player = new PlayerSection(Sections[SectionId.GSSI_PLAYER]);
        }
Example #32
0
		public Pbp Load(Stream Stream)
		{
			this.Stream = Stream;
			this.Header = Stream.ReadStruct<HeaderStruct>();
			this.Files = new Dictionary<string, Stream>();

			if (Header.Magic != HeaderStruct.MagicEnum.ExpectedValue)
			{
				throw(new Exception("Not a PBP file"));
			}

			var Offsets = Header.Offsets.Concat(new[] { (uint)Stream.Length }).ToArray();

			for (int n = 0; n < 8; n++)
			{
				Files[Names[n]] = Stream.SliceWithBounds(Offsets[n + 0], Offsets[n + 1]);
			}

			return this;
		}
Example #33
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;
 }
        public Stream2File(Stream stream)
        {
            Header = stream.ReadStruct<ContainerFileHeader>();

            uint allocatorTypeCount = stream.ReadUInt32();
            for (uint i = 0; i < allocatorTypeCount; i++)
            {
                UInt16 stringLength = stream.ReadUInt16();
                string name = stream.ReadAsciiString(stringLength);
                byte id = stream.ReadUInt8();
                AllocatorTypes.Add(id, name);
            }

            uint primitiveTypeCount = stream.ReadUInt32();
            for (uint i = 0; i < primitiveTypeCount; i++)
            {
                UInt16 stringLength = stream.ReadUInt16();
                string name = stream.ReadAsciiString(stringLength);
                byte id = stream.ReadUInt8();
                PrimitiveTypes.Add(id, name);
            }

            uint containerTypeCount = stream.ReadUInt32();
            for (uint i = 0; i < containerTypeCount; i++)
            {
                UInt16 stringLength = stream.ReadUInt16();
                string name = stream.ReadAsciiString(stringLength);
                byte id = stream.ReadUInt8();
                ContainerTypes.Add(id, name);
            }

            for (uint i = 0; i < Header.NumContainers; i++)
            {
                Container container = new Container(stream);
                Containers.Add(container);
            }
        }
Example #35
0
 public CodeNode Read(Stream stream)
 {
     return new CodeNode
     {
         stream.ReadStruct(out Length, nameof(Length)),
         stream.ReadAnything(out Data, StreamExtensions.ReadByteArray((int)Length), nameof(Data)),
     };
 }
Example #36
0
 public Section(Stream s)
 {
     Header = s.ReadStruct<SaveGameSectionHeader>();
     Data = new byte[Header.Size];
     s.Read(Data, 0, (int)Header.Size);
 }
Example #37
0
        public PGF Load(Stream FileStream)
        {
            this.Header = FileStream.ReadStruct<HeaderStruct>();

            if (this.Header.Revision >= 3)
            {
                this.HeaderExtraRevision3 = FileStream.ReadStruct<HeaderRevision3Struct>();
            }

            FileStream.ReadStructVector(ref DimensionTable, Header.TableDimLength);
            FileStream.ReadStructVector(ref XAdjustTable, Header.TableXAdjustLength);
            FileStream.ReadStructVector(ref YAdjustTable, Header.TableYAdjustLength);
            FileStream.ReadStructVector(ref AdvanceTable, Header.TableAdvanceLength);

            PackedShadowCharMap = FileStream.ReadBytes(BitsToBytesHighAligned(Header.TableShadowMapLength * Header.TableShadowMapBpe));

            if (Header.Revision == 3)
            {
                FileStream.ReadStructVector(ref CharmapCompressionTable1, HeaderExtraRevision3.TableCompCharMapLength1);
                FileStream.ReadStructVector(ref CharmapCompressionTable2, HeaderExtraRevision3.TableCompCharMapLength2);
            }

            PackedCharMap = FileStream.ReadBytes(BitsToBytesHighAligned(Header.TableCharMapLength * Header.TableCharMapBpe));
            PackedCharPointerTable = FileStream.ReadBytes(BitsToBytesHighAligned(Header.TableCharPointerLength * Header.TableCharPointerBpe));

            /*
            int BytesLeft = (int)(FileStream.Length - FileStream.Position);
            charData = new byte[BytesLeft];
            FileStream.Read(charData, 0, BytesLeft);
            */

            CharData = FileStream.ReadBytes((int)(FileStream.Length - FileStream.Position));

            var NumberOfCharacters = Header.TableCharPointerLength;

            CharMap = new int[Header.FirstGlyph + Header.LastGlyph + 1];
            CharPointer = new int[NumberOfCharacters];
            Glyphs = new Glyph[NumberOfCharacters];
            ReverseCharMap = new Dictionary<int, int>();
            ShadowCharMap = new Dictionary<int, int>();
            ReverseShadowCharMap = new Dictionary<int, int>();

            foreach (var Pair in BitReader.FixedBitReader(PackedShadowCharMap, Header.TableShadowMapBpe))
            {
                var UnicodeIndex = (int)Pair.Key + Header.FirstGlyph;
                var GlyphIndex = (int)Pair.Value;
                ShadowCharMap[UnicodeIndex] = GlyphIndex;
                ReverseShadowCharMap[GlyphIndex] = UnicodeIndex;
            }

            foreach (var Pair in BitReader.FixedBitReader(PackedCharMap, Header.TableCharMapBpe))
            {
                var UnicodeIndex = (int)Pair.Key + Header.FirstGlyph;
                var GlyphIndex = (int)Pair.Value;
                CharMap[UnicodeIndex] = GlyphIndex;
                ReverseCharMap[GlyphIndex] = UnicodeIndex;
            }

            foreach (var Pair in BitReader.FixedBitReader(PackedCharPointerTable, Header.TableCharPointerBpe))
            {
                CharPointer[Pair.Key] = (int)Pair.Value;
            }

            /*
            for (int n = 0; n < NumberOfCharacters; n++)
            {
                Glyphs[n] = new Glyph().Read(this, n);
            }
            */

            Console.WriteLine(this.Header.FontName);

            /*
            Console.WriteLine(this.header.fontName);
            for (int n = 0; n < 300; n++)
            {
                Console.WriteLine(GetGlyphId((char)n));
            }
            */

            return this;
        }
Example #38
0
        public DosExe LoadHeader(Stream ExeStream)
        {
            this.Header = ExeStream.ReadStruct<DosExe.HeaderStruct>();

            return this;
        }
Example #39
0
        public static BMP read(Stream stream)
        {
            var image = new BMP();

            int readIndex = 0;

            // Read headers
            readIndex += stream.ReadStruct(out image.fileHeader);

            readIndex += stream.ReadStruct(out image.infoHeader);

            if (image.infoHeader.biBitCount != 24 ||
                image.infoHeader.biCompression != BITMAPINFOHEADER.CompressionMode.BI_RGB)
            {
                throw new NotImplementedException("Format not implemented");
            }

            // Ensure we jump to the offset
            int seek = (int)image.fileHeader.bfOffBits - readIndex;

            stream.Seek(seek, SeekOrigin.Current);

            uint _height = image.uheight;
            uint _width = image.width;
            uint _size = _height * _width;

            // Initialize pixel matrix
            image.pixels = new BGR[_size];

            uint imagePadding = image.padding;

            // Optimize loop if there is no padding
            if (imagePadding > 0)
            {
                uint index = 0;
                for (uint i = 0; i < _height; i++)
                {
                    for (uint j = 0; j < _width; j++, index++)
                    {
                        BGR color;

                        readIndex += stream.ReadStruct(out color);

                        image[index] = color;
                    }

                    if (imagePadding > 0)
                    {
                        stream.Seek(imagePadding, SeekOrigin.Current);
                    }
                }
            }
            else
            {
                for (uint i = 0; i < _size; i++)
                {
                    BGR color;

                    readIndex += stream.ReadStruct(out color);

                    image[i] = color;
                }
            }

            return image;
        }
        protected void PreloadStrings(Stream input)
        {
            try
            {
                if (Strings.Count > 0) Strings.Clear();

                _bundleFileHeader = input.ReadStruct<FileHeaderStruct>();
                if (_bundleFileHeader.Magic != GETTEXT_MAGIC)
                    throw new IOException("Invalid MAGIC");

                var originalHeaders = ReadStringHeaders(input, _bundleFileHeader.OriginalTableOffset,
                                                        _bundleFileHeader.NumberOfStrings);
                var translationHeaders = ReadStringHeaders(input, _bundleFileHeader.TranslationTableOffset,
                                                           _bundleFileHeader.NumberOfStrings);

                var originals = new string[_bundleFileHeader.NumberOfStrings][];
                var translations = new string[_bundleFileHeader.NumberOfStrings][];
                for (var x = 0; x < _bundleFileHeader.NumberOfStrings; x++)
                    originals[x] = ReadTextEntry(input, originalHeaders[x].Offset, originalHeaders[x].Length);
                for (var x = 0; x < _bundleFileHeader.NumberOfStrings; x++)
                    translations[x] = ReadTextEntry(input, translationHeaders[x].Offset, translationHeaders[x].Length);

                for (var x = 0; x < _bundleFileHeader.NumberOfStrings; x++)
                {
                    switch (originals[x].Length)
                    {
                        case 1:
                            Strings.TryAdd(originals[x][0], translations[x]);
                            break;
                        case 2:
                            Strings.TryAdd(originals[x][0], new[] {translations[x][0]});
                            Strings.TryAdd(originals[x][1], translations[x]);
                            break;
                    }
                }
            }
            finally
            {
                _headerMsg = new HeaderMsg(GetString(string.Empty));
            }
        }
Example #41
0
    public CodeNode Read(Stream stream)
    {
        Node = new CodeNode
        {
            stream.ReadStruct(out Offset, nameof(Offset)),
            stream.ReadStruct(out Flags, nameof(Flags)),
            stream.ReadClass(ref Name, nameof(Name)),
            stream.ReadClass(ref Implementation, nameof(Implementation)),
        };

        Section section = Singletons.Instance.TildeStream.Section;
        section.ReadNode(strm =>
        {
            section.Reposition(strm, section.CLIHeader.Resources.RVA + Offset);

            ResourceEntry entry = null;
            return stream.ReadClass(ref entry);
        });

        return Node;
    }
Example #42
0
        public void Load(Stream Stream, ThreadContext ThreadContext)
        {
            var Memory = ThreadContext.CpuContext.Memory;

            var DosHeader = Stream.ReadStruct<IMAGE_DOS_HEADER>();

            Stream.Position = DosHeader.AddressOfNewExeHeader;

            var NtHeader = Stream.ReadStruct<IMAGE_NT_HEADERS>();

            int len = NtHeader.OptionalHeader.NumberOfRvaAndSizes;

            if (len >= 1) Export = Stream.ReadStruct<DATA_DIR>();
            if (len >= 2) Import = Stream.ReadStruct<DATA_DIR>();
            if (len >= 3) Resource = Stream.ReadStruct<DATA_DIR>();
            if (len >= 4) Exception = Stream.ReadStruct<DATA_DIR>();
            if (len >= 5) Security = Stream.ReadStruct<DATA_DIR>();
            if (len >= 6) BaseRelocationTable = Stream.ReadStruct<DATA_DIR>();
            if (len >= 7) DebugDirectory = Stream.ReadStruct<DATA_DIR>();
            if (len >= 8) CopyrightOrArchitectureSpecificData = Stream.ReadStruct<DATA_DIR>();
            if (len >= 9) GlobalPtr = Stream.ReadStruct<DATA_DIR>();
            if (len >= 10) TLSDirectory = Stream.ReadStruct<DATA_DIR>();
            if (len >= 11) LoadConfigurationDirectory = Stream.ReadStruct<DATA_DIR>();
            if (len >= 12) BoundImportDirectory = Stream.ReadStruct<DATA_DIR>();
            if (len >= 13) ImportAddressTable = Stream.ReadStruct<DATA_DIR>();
            if (len >= 14) DelayLoadImportDescriptors = Stream.ReadStruct<DATA_DIR>();
            if (len >= 15) COMRuntimedescriptor = Stream.ReadStruct<DATA_DIR>();
            if (len >= 16) Reserved = Stream.ReadStruct<DATA_DIR>();

            var Sections = new List<IMAGE_SECTION_HEADER>();

            for (int n = 0; n < NtHeader.FileHeader.NumberOfSections; n++)
            {
                Sections.Add(Stream.ReadStruct<IMAGE_SECTION_HEADER>());
            }

            var ImageBase = NtHeader.OptionalHeader.ImageBase;

            foreach (var Section in Sections)
            {
                Stream.Position = Section.PointerToRawData;
                var Data = new byte[Section.VirtualSize];
                Stream.Read(Data, 0, Data.Length);
                Memory.Write(ImageBase + Section.VirtualAddress, Data);
            }

            ThreadContext.PC = ImageBase + NtHeader.OptionalHeader.AddressOfEntryPoint;
            ThreadContext.ESP = (uint)(Memory.AllocStack(NtHeader.OptionalHeader.SizeOfStackReserve) + NtHeader.OptionalHeader.SizeOfStackReserve);

            var VirtualStream = Memory.GetStream().SliceWithLength(ImageBase);

            VirtualStream.Position = Import.VirtualAddress;
            var ImportDirectoryCount = Import.Size / Marshal.SizeOf(typeof(IMPORT_DIRECTORY_TABLE));
            for (int n = 0; n < ImportDirectoryCount; n++)
            {
                var ImportDirectory = VirtualStream.ReadStruct<IMPORT_DIRECTORY_TABLE>();
                if (ImportDirectory.NameRVA != 0)
                {
                    var DllName = VirtualStream.SliceWithLength(ImportDirectory.NameRVA).ReadStringz();
                    var Imports = VirtualStream.SliceWithLength(ImportDirectory.ImportLookupTableRVA);
                    var ImportsReader = new BinaryReader(Imports);
                    uint POS = ImportDirectory.ImportAddressTableRVA;

                    uint JumpAddress = 0x100;

                    while (true)
                    {
                        var ImportLookupAddress = ImportsReader.ReadUInt32();
                        if (ImportLookupAddress == 0) break;
                        var ImportLookupStream = VirtualStream.SliceWithLength(ImportLookupAddress);
                        ImportLookupStream.ReadByte();
                        ImportLookupStream.ReadByte();
                        var Name = ImportLookupStream.ReadStringz();

                        //Console.WriteLine("{0} : 0x{1:X} : {2} <-- 0x{3:X}", DllName, POS, Name, JumpAddress);
                        new BinaryWriter(VirtualStream.SliceWithLength(POS)).Write((uint)JumpAddress);
                        var JumpStream = new BinaryWriter(Memory.GetStream().SliceWithLength(JumpAddress));
                        JumpStream.Write(new byte[] { 0xCD, 0x01 });
                        JumpStream.Write((uint)JumpAddress);

                        ThreadContext.CpuContext.NativeMethodInfoList[JumpAddress] = CreateNativeMethodInfo(DllName, Name);
                        POS += 4;
                        JumpAddress += 6;
                    }
                }
            }

            //Console.WriteLine(DosHeader.Magic);
            //BinaryFormatter BinaryFormatter = new BinaryFormatter();
            //var Header = (IMAGE_DOS_HEADER)BinaryFormatter.Deserialize(Stream);
            //Marshal.StructureToPtr
        }
 private static StringHeaderStruct[] ReadStringHeaders(Stream input, uint offset, uint count)
 {
     var headers = new StringHeaderStruct[count];
     input.Seek(offset, SeekOrigin.Begin);
     for (var x = 0; x < count; x++)
         headers[x] = input.ReadStruct<StringHeaderStruct>();
     return (headers);
 }
Example #44
0
    public CodeNode Read(Stream stream)
    {
        CodeNode rva;

        Node = new CodeNode
        {
            (rva = stream.ReadStruct(out RVA, nameof(RVA))),
            stream.ReadClass(ref ImplFlags, nameof(ImplFlags)),
            stream.ReadClass(ref Flags, nameof(Flags)),
            stream.ReadClass(ref Name, nameof(Name)),
            stream.ReadClass(ref Signature, nameof(Signature)),
            stream.ReadClass(ref ParamList, nameof(ParamList)),
        };

        rva.DelayedValueNode = () => new DefaultValueNode(
            rva.Value,
            RVA > 0 ? Singletons.Instance.MethodsByRVA[RVA].Node : null);

        return Node;
    }
Example #45
0
        public static int Play(Stream Stream, Stream OutStream)
        {
            var strt = Stream.ReadString(3);
            Stream.Position = 0;

            ushort bztmp = 0;
            if (strt == "ea3")
            {
                //we get ea3 header
                Console.WriteLine("ea3 header\n");
                Stream.Position = 0x6;
                var tmp = Stream.ReadBytes(4);
                int skipbytes = 0;
                for (int a0 = 0; a0 < 4; a0++)
                {
                    skipbytes <<= 7;
                    skipbytes += tmp[a0] & 0x7F;
                }
                Stream.Skip(skipbytes);
            }

            if (strt == "RIF") //RIFF
            {
                //we get RIFF header
                Console.WriteLine("RIFF header\n");
                Stream.Position = 0x10;
                var fmt_size = Stream.ReadStruct<int>();
                var fmt = Stream.ReadStruct<ushort>();
                if (fmt != 0xFFFE)
                {
                    Console.WriteLine("RIFF File fmt error\n");
                    return -1;
                }
                Stream.Skip(0x28);
                bztmp = Stream.ReadStruct<ushort_be>();
                Stream.Skip(fmt_size - 0x2c);

                //search the data chunk
                for (int a0 = 0; a0 < 0x100; a0++)
                {
                    if (Stream.ReadString(4) == "atad") break;
                }
                int tmpr = Stream.ReadStruct<int>();
            }
            else
            {
                //EA3 block that contains at3+ stream
                Console.WriteLine("EA3 header");
                Stream.Skip(0x22);

                Console.WriteLine("{0:X}", Stream.Position);
                bztmp = (ushort)Stream.ReadStruct<ushort_be>();
                Stream.Skip(0x3c);
            }
            int blocksz = bztmp & 0x3FF;

            var buf0 = new byte[0x3000];
            fixed (byte* buf0_ptr = buf0)
            {
                //calculate the frame block size here
                int block_size = blocksz * 8 + 8;

                Console.WriteLine("frame_block_size 0x{0:X}\n", block_size);

                //Console.ReadKey();

                //so we make a new at3+ frame decoder
                MaiAT3PlusFrameDecoder d2 = new MaiAT3PlusFrameDecoder();

                Stream.Read(buf0, 0, block_size);
                int chns = 0;
                short[] p_buf;
                int rs;
                //decode the first frame and get channel num
                //for (int n = 0; n < block_size; n++) Console.Write(buf0[n]);
                if ((rs = d2.decodeFrame(buf0_ptr, block_size, out chns, out p_buf)) != 0) Console.WriteLine("decode error {0}", rs);
                Console.WriteLine("channels: {0}\n", chns);
                if (chns > 2) Console.WriteLine("warning: waveout doesn't support {0} chns\n", chns);

                //just waveout
                //MaiWaveOutI *mwo0 = new MaiWaveOutI(chns, 44100, 16);

                //mwo0.play();
                while (!Stream.Eof())
                {
                    Stream.Read(buf0, 0, block_size);

                    //decode frame and get sample data
                    if ((rs = d2.decodeFrame(buf0_ptr, block_size, out chns, out p_buf)) != 0) Console.WriteLine("decode error {0}", rs);
                    //play it

                    OutStream.WriteStructVector(p_buf, 0x800 * chns);

                    //mwo0.enqueue((Mai_I8*)p_buf, 0x800 * chns * 2);
                }

                //while (mwo0.getRemainBufSize()) Mai_Sleep(1);
                return 0;
            }
        }
Example #46
0
        /// <summary>
        /// Decodes the TGA file header.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="offset">The offset in the stream at which the data starts.</param>
        /// <param name="convFlags">The conversion flags.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="stream"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidDataException">
        /// Invalid data.
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// The specified format is not supported.
        /// </exception>
        private static TextureDescription DecodeTGAHeader(Stream stream, out int offset, out ConversionFlags convFlags)
        {
            if (stream == null)
            throw new ArgumentNullException("stream");

              TextureDescription description = new TextureDescription
              {
            Dimension = TextureDimension.Texture2D,
            Format = DataFormat.R8G8B8A8_UNORM,
              };

              offset = 0;
              convFlags = ConversionFlags.None;

              long size = stream.Length - stream.Position;
              int sizeOfTGAHeader = Marshal.SizeOf(typeof(Header));
              if (size < sizeOfTGAHeader)
            throw new InvalidDataException("The TGA file is corrupt.");

              var header = stream.ReadStruct<Header>();
              if (header.ColorMapType != 0 || header.ColorMapLength != 0)
            throw new NotSupportedException("TGA files with color maps are not supported.");

              if ((header.Descriptor & (DescriptorFlags.Interleaved2Way | DescriptorFlags.Interleaved4Way)) != 0)
            throw new NotSupportedException("TGA files with interleaved images are not supported.");

              if (header.Width == 0 || header.Height == 0)
            throw new NotSupportedException("The TGA file is corrupt. Width and height are invalid.");

              switch (header.ImageType)
              {
            case ImageType.TrueColor:
            case ImageType.TrueColorRLE:
              switch (header.BitsPerPixel)
              {
            case 16:
              description.Format = DataFormat.B5G5R5A1_UNORM;
              break;
            case 24:
              description.Format = DataFormat.R8G8B8A8_UNORM;
              convFlags |= ConversionFlags.Expand;
              // We could use DXGI_FORMAT_B8G8R8X8_UNORM, but we prefer DXGI 1.0 formats
              break;
            case 32:
              description.Format = DataFormat.R8G8B8A8_UNORM;
              // We could use DXGI.Format.B8G8R8A8_UNORM, but we prefer DXGI 1.0 formats
              break;
              }

              if (header.ImageType == ImageType.TrueColorRLE)
            convFlags |= ConversionFlags.RLE;
              break;

            case ImageType.BlackAndWhite:
            case ImageType.BlackAndWhiteRLE:
              switch (header.BitsPerPixel)
              {
            case 8:
              description.Format = DataFormat.R8_UNORM;
              break;
            default:
              throw new NotSupportedException("The black-and-white format used by the TGA file is not supported. Only 8-bit black-and-white images are supported.");
              }

              if (header.ImageType == ImageType.BlackAndWhiteRLE)
            convFlags |= ConversionFlags.RLE;
              break;

            case ImageType.NoImage:
            case ImageType.ColorMapped:
            case ImageType.ColorMappedRLE:
              throw new NotSupportedException("The image format used by the TGA file is not supported.");
            default:
              throw new InvalidDataException("Unknown image format used by the TGA file.");
              }

              description.Width = header.Width;
              description.Height = header.Height;
              description.Depth = 1;
              description.MipLevels = 1;
              description.ArraySize = 1;

              if ((header.Descriptor & DescriptorFlags.InvertX) != 0)
            convFlags |= ConversionFlags.InvertX;

              if ((header.Descriptor & DescriptorFlags.InvertY) != 0)
            convFlags |= ConversionFlags.InvertY;

              offset = sizeOfTGAHeader;
              if (header.IDLength != 0)
            offset += header.IDLength;
              return description;
        }
Example #47
0
 public Stream ReadChunk(Stream ChunkStream, bool IncludeTheSize = false)
 {
     var ChunkLength = (int)(uint)ChunkStream.ReadStruct<uint_be>();
     return ChunkStream.ReadStream(ChunkLength - (IncludeTheSize ? 4 : 0));
 }
Example #48
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;
        }