internal override uint BinarySize()
            {
                uint local_count = (uint)locals.Length;
                long body_size   = LEB128.SizeOf(local_count) + (uint)locals.Select(x => (long)x.BinarySize()).Sum() + code.Length;

                return(LEB128.SizeOf((uint)body_size) + LEB128.SizeOf(local_count) + (uint)locals.Select(x => (long)x.BinarySize()).Sum() + (uint)code.Length);
            }
            public FunctionBody(BinaryReader reader)
            {
                // Bit of a hack, but we use positions in this method, so we need to ensure it works
                if (!reader.BaseStream.CanSeek)
                {
                    throw new NotSupportedException("Stream passed does not support seeking.");
                }

                uint body_size = LEB128.ReadUInt32(reader);

                var before_pos = reader.BaseStream.Position;

                uint local_count = LEB128.ReadUInt32(reader);

                if (local_count > int.MaxValue)
                {
                    throw new NotImplementedException($"Count larger than {int.MaxValue} bytes not supported.");
                }
                locals = new LocalEntry[local_count];

                for (uint i = 0; i < local_count; i++)
                {
                    locals[i] = new LocalEntry(reader);
                }

                var after_pos = reader.BaseStream.Position;

                code = reader.ReadBytes((int)(body_size - (after_pos - before_pos)));

                if (code[code.Length - 1] != (byte)WebAssemblyOpcode.END)
                {
                    throw new Exception($"File is invalid. Expected byte {WebAssemblyOpcode.END}, received {code[code.Length-1]}.");
                }
            }
 internal override void SaveAsWASM(BinaryWriter writer)
 {
     LEB128.WriteUInt32(writer, memory_index);
     offset.SaveAsWASM(writer);
     LEB128.WriteUInt32(writer, (uint)data.Length);
     writer.Write(data);
 }
            internal override uint BinarySize()
            {
                var module_len = Encoding.UTF8.GetByteCount(module_str);
                var field_len  = Encoding.UTF8.GetByteCount(field_str);

                uint size = LEB128.SizeOf(module_len) + LEB128.SizeOf(field_len) + (uint)module_len + (uint)field_len + sizeof(byte);

                switch (kind)
                {
                case WebAssemblyExternalKind.Function:
                    size += LEB128.SizeOf((uint)type);
                    break;

                case WebAssemblyExternalKind.Table:
                    size += ((TableType)type).BinarySize();
                    break;

                case WebAssemblyExternalKind.Memory:
                    size += ((MemoryType)type).BinarySize();
                    break;

                case WebAssemblyExternalKind.Global:
                    size += ((GlobalType)type).BinarySize();
                    break;
                }

                return(size);
            }
            internal override void SaveAsWASM(BinaryWriter writer)
            {
                var module = Encoding.UTF8.GetBytes(module_str);
                var field  = Encoding.UTF8.GetBytes(field_str);

                LEB128.WriteUInt32(writer, (uint)module.Length);
                writer.Write(module);
                LEB128.WriteUInt32(writer, (uint)field.Length);
                writer.Write(field);
                writer.Write((byte)kind);

                switch (kind)
                {
                case WebAssemblyExternalKind.Function:
                    LEB128.WriteUInt32(writer, (uint)type);
                    break;

                case WebAssemblyExternalKind.Table:
                    ((TableType)type).SaveAsWASM(writer);
                    break;

                case WebAssemblyExternalKind.Memory:
                    ((MemoryType)type).SaveAsWASM(writer);
                    break;

                case WebAssemblyExternalKind.Global:
                    ((GlobalType)type).SaveAsWASM(writer);
                    break;
                }
            }
 internal override void SaveAsWASM(BinaryWriter writer)
 {
     base.SaveAsWASM(writer);
     LEB128.WriteUInt32(writer, (uint)entries.Length);
     foreach (var entry in entries)
     {
         entry.SaveAsWASM(writer);
     }
 }
 internal override void SaveAsWASM(BinaryWriter writer)
 {
     LEB128.WriteUInt7(writer, (byte)(maximum != null ? 1 : 0));
     LEB128.WriteUInt32(writer, initial);
     if (maximum != null)
     {
         LEB128.WriteUInt32(writer, (uint)maximum);
     }
 }
Exemple #8
0
            internal override void SaveAsWASM(BinaryWriter writer)
            {
                var field = Encoding.UTF8.GetBytes(field_str);

                LEB128.WriteUInt32(writer, (uint)field.Length);
                writer.Write(field);
                writer.Write((byte)kind);
                LEB128.WriteUInt32(writer, index);
            }
Exemple #9
0
        private static bool LoadSprites(ChunkReader chunkIO, ChunkId idOuter, Wad2 wad, ref Dictionary <long, WadSprite> outSprites)
        {
            if (idOuter != Wad2Chunks.Sprites)
            {
                return(false);
            }

            var  sprites       = new Dictionary <long, WadSprite>();
            long obsoleteIndex = 0; // Move this into each chunk once we got rid of old style *.wad2 files.

            chunkIO.ReadChunks((id, chunkSize) =>
            {
                if (id != Wad2Chunks.Sprite)
                {
                    return(false);
                }

                int width          = LEB128.ReadInt(chunkIO.Raw);
                int height         = LEB128.ReadInt(chunkIO.Raw);
                byte[] imageData   = null;
                RectangleInt2 rect = new RectangleInt2();

                chunkIO.ReadChunks((id2, chunkSize2) =>
                {
                    if (id2 == Wad2Chunks.SpriteIndex)
                    {
                        obsoleteIndex = chunkIO.ReadChunkLong(chunkSize2);
                    }
                    else if (id2 == Wad2Chunks.SpriteData)
                    {
                        imageData = chunkIO.ReadChunkArrayOfBytes(chunkSize2);
                    }
                    else if (id2 == Wad2Chunks.SpriteSides)
                    {
                        rect.X0 = chunkIO.Raw.ReadInt32();
                        rect.Y0 = chunkIO.Raw.ReadInt32();
                        rect.X1 = chunkIO.Raw.ReadInt32();
                        rect.Y1 = chunkIO.Raw.ReadInt32();
                    }
                    else
                    {
                        return(false);
                    }
                    return(true);
                });

                sprites.Add(obsoleteIndex++, new WadSprite {
                    Texture   = new WadTexture(ImageC.FromByteArray(imageData, width, height)),
                    Alignment = rect
                })
                ;
                return(true);
            });

            outSprites = sprites;
            return(true);
        }
Exemple #10
0
 internal override void SaveAsWASM(BinaryWriter writer)
 {
     LEB128.WriteUInt32(writer, table_index);
     offset.SaveAsWASM(writer);
     LEB128.WriteUInt32(writer, (uint)function_index.Length);
     foreach (var elem in function_index)
     {
         LEB128.WriteUInt32(writer, elem);
     }
 }
            internal override void SaveAsWASM(BinaryWriter writer)
            {
                base.SaveAsWASM(writer);

                byte[] name_bytes = Encoding.UTF8.GetBytes(name);

                LEB128.WriteUInt32(writer, (uint)name_bytes.Length);
                writer.Write(name_bytes);
                writer.Write(payload_data);
            }
            public TableType(BinaryReader reader)
            {
                sbyte type = LEB128.ReadInt7(reader);

                if (type != (int)WebAssemblyType.anyfunc)
                {
                    throw new Exception($"File is invalid. Expected byte '{WebAssemblyType.anyfunc}', received '{type}'.");
                }
                element_type = WebAssemblyType.anyfunc;
                limits       = new ResizeLimit(reader);
            }
            public DataSegment(BinaryReader reader)
            {
                memory_index = LEB128.ReadUInt32(reader);
                offset       = new InitExpr(reader);
                uint count = LEB128.ReadUInt32(reader);

                if (count > int.MaxValue)
                {
                    throw new NotImplementedException($"Count larger than {int.MaxValue} bytes not supported.");
                }
                data = reader.ReadBytes((int)count);
            }
Exemple #14
0
            public ElementSegment(BinaryReader reader)
            {
                table_index = LEB128.ReadUInt32(reader);
                offset      = new InitExpr(reader);
                uint num_elem = LEB128.ReadUInt32(reader);

                function_index = new uint[num_elem];

                for (uint i = 0; i < num_elem; i++)
                {
                    function_index[i] = LEB128.ReadUInt32(reader);
                }
            }
            public LocalEntry(BinaryReader reader)
            {
                count = LEB128.ReadUInt32(reader);

                var tmp_type = reader.ReadByte();

                if (!Enum.IsDefined(typeof(WebAssemblyType), tmp_type))
                {
                    throw new Exception($"File is invalid. Expected WebAssemblyType, received '{tmp_type}'.");
                }

                type = (WebAssemblyType)tmp_type;
            }
            internal override void SaveAsWASM(BinaryWriter writer)
            {
                uint local_count = (uint)locals.Length;
                uint body_size   = LEB128.SizeOf(local_count) + (uint)locals.Select(x => (long)x.BinarySize()).Sum() + (uint)code.Length;

                LEB128.WriteUInt32(writer, body_size);
                LEB128.WriteUInt32(writer, local_count);
                foreach (var local in locals)
                {
                    local.SaveAsWASM(writer);
                }
                writer.Write(code);
            }
        public void SizeOfTest()
        {
            // sizeof(Int7) is always 1 byte
            Assert.AreEqual(LEB128.SizeOf((byte)0), 1u);
            Assert.AreEqual(LEB128.SizeOf((byte)255), 1u);
            Assert.AreEqual(LEB128.SizeOf((sbyte)-1), 1u);
            Assert.AreEqual(LEB128.SizeOf((sbyte)127), 1u);

            Assert.AreEqual(LEB128.SizeOf(0), 1u);
            Assert.AreEqual(LEB128.SizeOf(0u), 1u);
            Assert.AreEqual(LEB128.SizeOf(int.MaxValue), 5u);
            Assert.AreEqual(LEB128.SizeOf(int.MinValue), 5u);
            Assert.AreEqual(LEB128.SizeOf(uint.MaxValue), 5u);
        }
            public CustomSection(string name, byte[] payload_data) : base(WebAssemblyModuleID.Custom)
            {
                if (payload_data.LongLength > int.MaxValue)
                {
                    throw new NotImplementedException($"Payload longer than {int.MaxValue} bytes not supported.");
                }

                this.name         = name;
                this.payload_data = payload_data;

                uint name_bytes = (uint)Encoding.UTF8.GetByteCount(name);

                payload_len = LEB128.SizeOf(name_bytes) + name_bytes + (uint)payload_data.Length;
            }
            public ImportEntry(BinaryReader reader)
            {
                uint module_len = LEB128.ReadUInt32(reader);

                if (module_len > int.MaxValue)
                {
                    throw new NotImplementedException($"String longer than {int.MaxValue} bytes not supported.");
                }
                module_str = Encoding.UTF8.GetString(reader.ReadBytes((int)module_len));

                uint field_len = LEB128.ReadUInt32(reader);

                if (field_len > int.MaxValue)
                {
                    throw new NotImplementedException($"String longer than {int.MaxValue} bytes not supported.");
                }
                field_str = Encoding.UTF8.GetString(reader.ReadBytes((int)field_len));

                byte tmp_kind = reader.ReadByte();

                if (!Enum.IsDefined(typeof(WebAssemblyExternalKind), tmp_kind))
                {
                    throw new Exception($"File is invalid. Expected 0, 1, 2, or 3, received '{tmp_kind}'.");
                }

                kind = (WebAssemblyExternalKind)tmp_kind;

                switch (kind)
                {
                case WebAssemblyExternalKind.Function:
                    type = LEB128.ReadUInt32(reader);
                    break;

                case WebAssemblyExternalKind.Table:
                    var table_tmp = new TableType(reader);
                    type = table_tmp;
                    break;

                case WebAssemblyExternalKind.Memory:
                    var memory_tmp = new MemoryType(reader);
                    type = memory_tmp;
                    break;

                case WebAssemblyExternalKind.Global:
                    var global_tmp = new GlobalType(reader);
                    type = global_tmp;
                    break;
                }
            }
Exemple #20
0
 private static void WriteTextures(ChunkWriter chunkIO, List <WadTexture> textureTable)
 {
     chunkIO.WriteChunkWithChildren(Wad2Chunks.Textures, () =>
     {
         foreach (var texture in textureTable)
         {
             chunkIO.WriteChunkWithChildren(Wad2Chunks.Texture, () =>
             {
                 LEB128.Write(chunkIO.Raw, texture.Image.Width);
                 LEB128.Write(chunkIO.Raw, texture.Image.Height);
                 chunkIO.WriteChunkArrayOfBytes(Wad2Chunks.TextureData, texture.Image.ToByteArray());
             });
         }
     });
 }
            public CustomSection(BinaryReader reader) : base(reader)
            {
                uint name_len = LEB128.ReadUInt32(reader);

                name = Encoding.UTF8.GetString(reader.ReadBytes((int)name_len));

                uint payload_size = payload_len - (LEB128.SizeOf(name_len) + name_len);

                if (payload_size > int.MaxValue)
                {
                    throw new NotImplementedException($"Payload longer than {int.MaxValue} bytes not supported.");
                }

                payload_data = reader.ReadBytes((int)payload_size);
            }
Exemple #22
0
            public CodeSection(BinaryReader reader) : base(reader)
            {
                uint count = LEB128.ReadUInt32(reader);

                if (count > int.MaxValue)
                {
                    throw new NotImplementedException($"Count larger than {int.MaxValue} bytes not supported.");
                }
                bodies = new FunctionBody[count];

                for (uint i = 0; i < count; i++)
                {
                    bodies[i] = new FunctionBody(reader);
                }
            }
            public DataSection(BinaryReader reader) : base(reader)
            {
                uint count = LEB128.ReadUInt32(reader);

                if (count > int.MaxValue)
                {
                    throw new NotImplementedException($"Count larger than {int.MaxValue} bytes not supported.");
                }
                entries = new DataSegment[count];

                for (uint i = 0; i < count; i++)
                {
                    entries[i] = new DataSegment(reader);
                }
            }
Exemple #24
0
            public GlobalSection(BinaryReader reader) : base(reader)
            {
                uint count = LEB128.ReadUInt32(reader);

                if (count > int.MaxValue)
                {
                    throw new NotImplementedException($"Count larger than {int.MaxValue} bytes not supported.");
                }
                globals = new GlobalVariable[count];

                for (uint i = 0; i < count; i++)
                {
                    globals[i] = new GlobalVariable(reader);
                }
            }
        public void ReadTest(MemoryStream stream)
        {
            BinaryReader reader = new BinaryReader(stream);

            Assert.AreEqual(LEB128.ReadUInt32(reader), 0xFF00FF00u);
            Assert.AreEqual(LEB128.ReadUInt32(reader), 0xAABBAAu);
            Assert.AreEqual(LEB128.ReadUInt32(reader), 0xCCu);
            Assert.AreEqual(LEB128.ReadUInt7(reader), 0x11u);
            Assert.AreEqual(LEB128.ReadUInt7(reader), 0x7Fu);
            Assert.AreEqual(LEB128.ReadInt32(reader), 0x7F00FF00);
            Assert.AreEqual(LEB128.ReadInt32(reader), 0xAABBAA);
            Assert.AreEqual(LEB128.ReadInt32(reader), 0xCC);
            Assert.AreEqual(LEB128.ReadInt32(reader), -1);
            Assert.AreEqual(LEB128.ReadInt7(reader), 0x11);
            Assert.AreEqual(LEB128.ReadInt7(reader), -1);
        }
Exemple #26
0
        //public static TimeSpan ReadDiffTimeMcsAsTimeSpan(Stream stream)
        //{
        //  var microseconds = ReadDiffTimeMcs(stream);
        //  var ticks = (long)microseconds * 10;
        //  return new TimeSpan( ticks );
        //}

        public static string ReadString(Stream stream)
        {
            var        sz      = LEB128.ReadULEB128(stream);
            const long MAX_STR = 128 * 1024;

            if (sz > MAX_STR)
            {
                throw new FinancialException(StringConsts.SECDB_STREAM_CORRUPTED_ERROR + "ReadString(): sz={0}>max={1}".Args(sz, MAX_STR));
            }

            var buf = new byte[sz];

            readFromStream(stream, buf, (int)sz);

            return(Encoding.UTF8.GetString(buf));
        }
        public void WriteTest(MemoryStream stream)
        {
            BinaryWriter writer = new BinaryWriter(stream);

            LEB128.WriteUInt32(writer, 0xFF00FF00);
            LEB128.WriteUInt32(writer, 0xAABBAA);
            LEB128.WriteUInt32(writer, 0xCC);
            LEB128.WriteUInt7(writer, 0x11);
            LEB128.WriteUInt7(writer, 0x7F);
            LEB128.WriteInt32(writer, 0x7F00FF00);
            LEB128.WriteInt32(writer, 0xAABBAA);
            LEB128.WriteInt32(writer, 0xCC);
            LEB128.WriteInt32(writer, -1);
            LEB128.WriteInt7(writer, 0x11);
            LEB128.WriteInt7(writer, -1);
        }
Exemple #28
0
        private static bool LoadTextures(ChunkReader chunkIO, ChunkId idOuter, Wad2 wad, ref Dictionary <long, WadTexture> outTextures)
        {
            if (idOuter != Wad2Chunks.Textures)
            {
                return(false);
            }

            Dictionary <long, WadTexture> textures = new Dictionary <long, WadTexture>();
            long obsoleteIndex = 0; // Move this into each chunk once we got rid of old style *.wad2 files.

            chunkIO.ReadChunks((id, chunkSize) =>
            {
                if (id != Wad2Chunks.Texture)
                {
                    return(false);
                }

                var width          = LEB128.ReadInt(chunkIO.Raw);
                var height         = LEB128.ReadInt(chunkIO.Raw);
                byte[] textureData = null;
                chunkIO.ReadChunks((id2, chunkSize2) =>
                {
                    if (id2 == Wad2Chunks.TextureIndex)
                    {
                        obsoleteIndex = chunkIO.ReadChunkLong(chunkSize2);
                    }
                    if (id2 == Wad2Chunks.TextureData)
                    {
                        textureData = chunkIO.ReadChunkArrayOfBytes(chunkSize2);
                    }
                    else
                    {
                        return(false);
                    }
                    return(true);
                });

                var texture = ImageC.FromByteArray(textureData, width, height);
                texture.ReplaceColor(new ColorC(255, 0, 255, 255), new ColorC(0, 0, 0, 0));

                textures.Add(obsoleteIndex++, new WadTexture(texture));
                return(true);
            });

            outTextures = textures;
            return(true);
        }
Exemple #29
0
 private static void WriteSpriteSequences(ChunkWriter chunkIO, Wad2 wad, List <WadSprite> spriteTable)
 {
     chunkIO.WriteChunkWithChildren(Wad2Chunks.SpriteSequences, () =>
     {
         foreach (var sequence in wad.SpriteSequences.Values)
         {
             chunkIO.WriteChunkWithChildren(Wad2Chunks.SpriteSequence, () =>
             {
                 LEB128.Write(chunkIO.Raw, sequence.Id.TypeId);
                 foreach (var spr in sequence.Sprites)
                 {
                     chunkIO.WriteChunkInt(Wad2Chunks.SpriteSequenceSpriteIndex, spriteTable.IndexOf(spr));
                 }
             });
         }
     });
 }
Exemple #30
0
        private static void WriteStatics(ChunkWriter chunkIO, Wad2 wad, List <WadTexture> textureTable)
        {
            chunkIO.WriteChunkWithChildren(Wad2Chunks.Statics, () =>
            {
                foreach (var staticMesh in wad.Statics)
                {
                    chunkIO.WriteChunkWithChildren(Wad2Chunks.Static, () =>
                    {
                        var s = staticMesh.Value;

                        LEB128.Write(chunkIO.Raw, s.Id.TypeId);
                        LEB128.Write(chunkIO.Raw, s.Flags);
                        LEB128.Write(chunkIO.Raw, (short)s.LightingType);

                        WriteMesh(chunkIO, s.Mesh, textureTable);

                        chunkIO.WriteChunkInt(Wad2Chunks.StaticAmbientLight, s.AmbientLight);

                        foreach (var light in s.Lights)
                        {
                            chunkIO.WriteChunkWithChildren(Wad2Chunks.StaticLight, () =>
                            {
                                chunkIO.WriteChunkVector3(Wad2Chunks.StaticLightPosition, light.Position);
                                chunkIO.WriteChunkFloat(Wad2Chunks.StaticLightRadius, light.Radius);
                                chunkIO.WriteChunkFloat(Wad2Chunks.StaticLightIntensity, light.Intensity);
                            });
                        }

                        chunkIO.WriteChunkWithChildren(Wad2Chunks.StaticVisibilityBox, () =>
                        {
                            chunkIO.WriteChunkVector3(Wad2Chunks.MeshBoundingBoxMin, s.VisibilityBox.Minimum);
                            chunkIO.WriteChunkVector3(Wad2Chunks.MeshBoundingBoxMax, s.VisibilityBox.Maximum);
                        });

                        chunkIO.WriteChunkWithChildren(Wad2Chunks.StaticCollisionBox, () =>
                        {
                            chunkIO.WriteChunkVector3(Wad2Chunks.MeshBoundingBoxMin, s.CollisionBox.Minimum);
                            chunkIO.WriteChunkVector3(Wad2Chunks.MeshBoundingBoxMax, s.CollisionBox.Maximum);
                        });

                        //chunkIO.WriteChunkString(Wad2Chunks.StaticName, s.Name);
                    });
                }
            });
        }