Example #1
0
    public static void ChangePositionViaPointer()
    {
        byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 127, 255 };
        unsafe
        {
            fixed (byte* bytePtr = data)
            {
                using (var stream = new UnmanagedMemoryStream(bytePtr, data.Length, data.Length, FileAccess.ReadWrite))
                {
                    // Make sure the position pointer is where we set it to be
                    Assert.Equal(expected: (IntPtr)bytePtr, actual: (IntPtr)stream.PositionPointer);

                    // Make sure that moving earlier than the beginning of the stream throws
                    Assert.Throws<IOException>(() => {
                        stream.PositionPointer = stream.PositionPointer - 1;
                    });

                    // Make sure that moving later than the length can be done but then
                    // fails appropriately during reads and writes, and that the stream's
                    // data is still intact after the fact
                    stream.PositionPointer = bytePtr + data.Length;
                    VerifyNothingCanBeReadOrWritten(stream, data);
                    CheckStreamIntegrity(stream, data);
                }
            } // fixed
        }
    }
        private static void SelfTest()
        {
            UnmanagedMemoryStream ms1 = new UnmanagedMemoryStream();
            BinaryStreamBase ms = ms1.CreateBinaryStream();
            Random rand = new Random();
            int seed = rand.Next();
            rand = new Random(seed);
            byte[] data = new byte[255];
            rand.NextBytes(data);

            while (ms.Position < 1000000)
            {
                ms.Write(data, 0, rand.Next(256));
            }

            byte[] data2 = new byte[255];
            rand = new Random(seed);
            rand.NextBytes(data2);
            ms.Position = 0;
            Compare(data, data2, 255);
            while (ms.Position < 1000000)
            {
                int length = rand.Next(256);
                ms.ReadAll(data2, 0, length);
                Compare(data, data2, length);
            }
            ms.Dispose();
            ms1.Dispose();
        }
Example #3
0
        public static void OneByteStreamRead()
        {
            using (var manager = new UmsManager(FileAccess.Read, new byte[] { 100 }))
            {
                UnmanagedMemoryStream stream = manager.Stream;
                UmsTests.ReadUmsInvariants(stream);

                var position = stream.Position;
                Assert.Equal(stream.ReadByte(), 100);
                Assert.Equal(stream.Position, position + 1);

                position = stream.Position;
                Assert.Equal(stream.ReadByte(), -1); // end of stream
                Assert.Equal(stream.Position, position);
            }

            using (HGlobalSafeBuffer buffer = new HGlobalSafeBuffer(1))
            using (var stream = new UnmanagedMemoryStream(buffer, 0, 1, FileAccess.ReadWrite))
            {
                buffer.Write(0, (byte)100);

                var position = stream.Position;
                Assert.Equal(stream.ReadByte(), 100);
                Assert.Equal(stream.Position, position + 1);

                Assert.Equal(stream.ReadByte(), -1); // end of stream
                Assert.Equal(stream.Position, position + 1);
            }
        }
Example #4
0
 internal static void ReadWriteUmsInvariants(UnmanagedMemoryStream stream)
 {
     UmsInvariants(stream);
     Assert.True(stream.CanRead);
     Assert.True(stream.CanWrite);
     Assert.True(stream.CanSeek);
 }
Example #5
0
 internal static void ReadUmsInvariants(UnmanagedMemoryStream stream)
 {
     UmsInvariants(stream);
     Assert.True(stream.CanRead);
     Assert.False(stream.CanWrite);
     Assert.True(stream.CanSeek);
     Assert.Throws<NotSupportedException>(() => stream.SetLength(1000));
 }
 public void Test()
 {
     MemoryPoolTest.TestMemoryLeak();
     SelfTest();
     UnmanagedMemoryStream ms = new UnmanagedMemoryStream();
     BinaryStreamTest.Test(ms);
     Assert.IsTrue(true);
     ms.Dispose();
     MemoryPoolTest.TestMemoryLeak();
 }
Example #7
0
        public static unsafe void PointerCtor()
        {
            int someInt32 = 42;
            int* pInt32 = &someInt32;
            byte* pByte = (byte*)pInt32;

            using (var stream = new UnmanagedMemoryStream(pByte, 0))
            {
                Assert.True(stream.CanRead);
                Assert.True(stream.CanSeek);
                Assert.False(stream.CanWrite);
                Assert.False(stream.CanTimeout);

                Assert.Equal(0, stream.Length);
                Assert.Equal(0, stream.Capacity);
                Assert.Equal(0, stream.Position);

                Assert.Throws<InvalidOperationException>(() => stream.ReadTimeout);
                Assert.Throws<InvalidOperationException>(() => stream.ReadTimeout = 42);
                Assert.Throws<InvalidOperationException>(() => stream.WriteTimeout);
                Assert.Throws<InvalidOperationException>(() => stream.WriteTimeout = 42);

                Assert.True(stream.PositionPointer == pByte);
            }

            using (var stream = new DerivedUnmanagedMemoryStream())
            {
                Assert.False(stream.CanRead);
                Assert.False(stream.CanSeek);
                Assert.False(stream.CanWrite);
                Assert.False(stream.CanTimeout);

                Assert.Throws<ArgumentOutOfRangeException>(() => stream.Initialize(pByte, -1, 4, FileAccess.Read));
                Assert.Throws<ArgumentOutOfRangeException>(() => stream.Initialize(pByte, 1, -4, FileAccess.Read));
                Assert.Throws<ArgumentOutOfRangeException>(() => stream.Initialize(pByte, 5, 4, FileAccess.Read));
                Assert.Throws<ArgumentOutOfRangeException>(() => stream.Initialize(pByte, 1, 4, (FileAccess)12345));
                stream.Initialize(pByte, 1, 4, FileAccess.ReadWrite);
                Assert.Throws<InvalidOperationException>(() => stream.Initialize(pByte, 1, 4, FileAccess.ReadWrite));

                Assert.True(stream.CanRead);
                Assert.True(stream.CanSeek);
                Assert.True(stream.CanWrite);

                Assert.Equal(1, stream.Length);
                Assert.Equal(4, stream.Capacity);
                Assert.Equal(0, stream.Position);

                Assert.Throws<InvalidOperationException>(() => stream.ReadTimeout);
                Assert.Throws<InvalidOperationException>(() => stream.ReadTimeout = 42);
                Assert.Throws<InvalidOperationException>(() => stream.WriteTimeout);
                Assert.Throws<InvalidOperationException>(() => stream.WriteTimeout = 42);

                Assert.True(stream.PositionPointer == pByte);
            }
        }
Example #8
0
 public unsafe UmsManager(FileAccess access, byte[] seedData)
 {
     int memorySizeInBytes = seedData.Length;
     _memory = Marshal.AllocHGlobal(memorySizeInBytes);
     byte* destination = (byte*)_memory.ToPointer();
     fixed (byte* source = seedData)
     {
         Buffer.MemoryCopy(source, destination, memorySizeInBytes, memorySizeInBytes);
     }
     _stream = new UnmanagedMemoryStream(destination, memorySizeInBytes, memorySizeInBytes, access);
 }
Example #9
0
    static void VerifyNothingCanBeReadOrWritten(UnmanagedMemoryStream stream, Byte[] data)
    {
        // No Read
        int count = stream.Read(data, 0, data.Length);
        Assert.Equal(0, count);
        Assert.Equal(-1, stream.ReadByte());

        // No write
        Assert.Throws<NotSupportedException>(() => stream.Write(data, 0, data.Length)); // Stream does not support writing.
        Assert.Throws<NotSupportedException>(() => stream.WriteByte(Byte.MaxValue)); // Stream does not support writing.
    }
Example #10
0
    public static void CheckStreamIntegrity(UnmanagedMemoryStream stream, Byte[] originalData)
    {
        stream.Position = 0;
        Byte[] streamData = new Byte[originalData.Length];
        int value = stream.Read(streamData, 0, streamData.Length);

        Assert.Equal(originalData.Length, value);
        Assert.Equal(originalData, streamData, ArrayHelpers.Comparer<byte>());

        stream.Position = 0;
    }
Example #11
0
    public static void CheckStreamIntegrity(UnmanagedMemoryStream stream, Byte[] originalData)
    {
        stream.Position = 0;
        Byte[] streamData = new Byte[originalData.Length];
        int value = stream.Read(streamData, 0, streamData.Length);
        Assert.Equal(originalData.Length, value);

        for (int i = 0; i < originalData.Length; i++)
            Assert.Equal(originalData[i], streamData[i]);

        stream.Position = 0;
    }
Example #12
0
 public unsafe UmsManager(FileAccess access, int capacity)
 {
     int memorySizeInBytes = capacity;
     _memory = Marshal.AllocHGlobal(memorySizeInBytes);
     byte* bytes = (byte*)_memory.ToPointer();
     byte* currentByte = bytes;
     for (int index = 0; index < memorySizeInBytes; index++)
     {
         *currentByte = 0;
         currentByte++;
     }
     _stream = new UnmanagedMemoryStream(bytes, memorySizeInBytes, memorySizeInBytes, access);
 }
Example #13
0
        public static void CannotReadFromWriteStream()
        {
            using (var manager = new UmsManager(FileAccess.Write, 100))
            {
                Stream stream = manager.Stream;
                Assert.Throws<NotSupportedException>(() => stream.ReadByte());
            }

            using (HGlobalSafeBuffer buffer = new HGlobalSafeBuffer(100))
            using (var stream = new UnmanagedMemoryStream(buffer, 0, 100, FileAccess.Write))
            {
                Assert.Throws<NotSupportedException>(() => stream.ReadByte());
            }
        }
Example #14
0
 public unsafe UmsManager(FileAccess access, byte[] seedData)
 {
     _memorySizeInBytes = seedData.Length;
     unsafe
     {
         _memory = Marshal.AllocHGlobal(_memorySizeInBytes);
         byte* bytes = (byte*)_memory.ToPointer();
         byte* currentByte = bytes;
         for (int index = 0; index < _memorySizeInBytes; index++)
         {
             *currentByte = seedData[index];
         }
         _stream = new UnmanagedMemoryStream(bytes, _memorySizeInBytes, _memorySizeInBytes, access);
     }
 }
Example #15
0
    public static unsafe void Main()
    {
        int prot = 0x1 | 0x2 | 0x4; //PROT_READ | PROT_WRITE | PROT_EXEC
        int flags = 0x1000 | 0x0002; //MAP_ANON | MAP_PRIVATE
        var res = mmap (IntPtr.Zero, (IntPtr)4096, prot , flags, 0);
        var mem = new UnmanagedMemoryStream ((byte*)res, 4096, 4096, FileAccess.ReadWrite);
        var asm = new Assembler (mem);

        asm.Push (EBP);
        asm.Mov (EBP, ESP);
        asm.Mov (EAX, 10);
        asm.Leave ();
        asm.Ret ();

        NoArgsReturnInt dele = (NoArgsReturnInt)Marshal.GetDelegateForFunctionPointer (res, typeof (NoArgsReturnInt));

        Console.WriteLine (dele ());
    }
Example #16
0
        public static unsafe void CtorsThatFail()
        {
            Assert.Throws<ArgumentNullException>(() => { var ums = new UnmanagedMemoryStream(null, 0); });

            TestSafeBuffer nullBuffer = null;
            FakeSafeBuffer fakeBuffer = new FakeSafeBuffer(99);
            Assert.Throws<ArgumentNullException>(() => new UnmanagedMemoryStream(nullBuffer, 0, 1));

            Assert.Throws<ArgumentOutOfRangeException>(() => new UnmanagedMemoryStream(fakeBuffer, 2, -1));
            Assert.Throws<ArgumentOutOfRangeException>(() => new UnmanagedMemoryStream(fakeBuffer, -1, 1));
            Assert.Throws<ArgumentOutOfRangeException>(() => new UnmanagedMemoryStream(fakeBuffer, 1, 2, (FileAccess)(-1)));
            Assert.Throws<ArgumentOutOfRangeException>(() => new UnmanagedMemoryStream(fakeBuffer, 1, 2, (FileAccess)42));

            Assert.Throws<ArgumentException>(() => new UnmanagedMemoryStream(fakeBuffer, 2, 999));
            Assert.Throws<ArgumentException>(() => new UnmanagedMemoryStream(fakeBuffer, 999, 9));
            Assert.Throws<ArgumentException>(() => new UnmanagedMemoryStream(fakeBuffer, 1, 100));

            Assert.Throws<ArgumentException>(() => new UnmanagedMemoryStream(fakeBuffer, Int32.MaxValue, 1));
        }
Example #17
0
        public static void EmptyStreamRead()
        {
            using (var manager = new UmsManager(FileAccess.Read, 0))
            {
                UnmanagedMemoryStream stream = manager.Stream;
                UmsTests.ReadUmsInvariants(stream);

                var position = stream.Position;
                Assert.Equal(manager.Stream.ReadByte(), -1); // end of stream
                Assert.Equal(stream.Position, position);
            }

            using (HGlobalSafeBuffer buffer = new HGlobalSafeBuffer(1))
            using (var stream = new UnmanagedMemoryStream(buffer, 0, 0))
            {
                var position = stream.Position;
                Assert.Equal(stream.ReadByte(), -1); // end of stream
                Assert.Equal(stream.Position, position);
            }
        }
Example #18
0
        public static void PointerCtor()
        {
            int someInt32 = 42;
            unsafe
            {
                int* pInt32 = &someInt32;
                byte* pByte = (byte*)pInt32;
                using (var stream = new UnmanagedMemoryStream(pByte, 0))
                {
                    Assert.True(stream.CanRead);
                    Assert.True(stream.CanSeek);
                    Assert.False(stream.CanWrite);

                    Assert.Equal(0, stream.Length);
                    Assert.Equal(0, stream.Capacity);
                    Assert.Equal(0, stream.Position);

                    if (stream.PositionPointer != pByte)
                    {
                        Assert.True(false);
                    }
                }
            }
        }
Example #19
0
        protected unsafe void InitDna(byte[] bdnaOrg)
        {
            if (_dna != IntPtr.Zero)
            {
                return;
            }

            _dnaLength = bdnaOrg.Length;
            _dna       = Marshal.AllocHGlobal(bdnaOrg.Length);
            Marshal.Copy(bdnaOrg, 0, _dna, _dnaLength);

            Stream       stream = new UnmanagedMemoryStream((byte *)_dna.ToPointer(), _dnaLength);
            BinaryReader reader = new BinaryReader(stream);

            // SDNA
            byte[] code  = reader.ReadBytes(8);
            string codes = ASCIIEncoding.ASCII.GetString(code);

            // NAME
            if (!codes.Equals("SDNANAME"))
            {
                throw new InvalidDataException();
            }
            int dataLen = reader.ReadInt32();

            _names = new Dna.NameInfo[dataLen];
            for (int i = 0; i < dataLen; i++)
            {
                List <byte> name = new List <byte>();
                byte        ch   = reader.ReadByte();
                while (ch != 0)
                {
                    name.Add(ch);
                    ch = reader.ReadByte();
                }

                _names[i] = new Dna.NameInfo(ASCIIEncoding.ASCII.GetString(name.ToArray()));
            }
            stream.Position = (stream.Position + 3) & ~3;

            // TYPE
            code  = reader.ReadBytes(4);
            codes = ASCIIEncoding.ASCII.GetString(code);
            if (!codes.Equals("TYPE"))
            {
                throw new InvalidDataException();
            }
            dataLen = reader.ReadInt32();
            _types  = new Dna.TypeDecl[dataLen];
            for (int i = 0; i < dataLen; i++)
            {
                List <byte> name = new List <byte>();
                byte        ch   = reader.ReadByte();
                while (ch != 0)
                {
                    name.Add(ch);
                    ch = reader.ReadByte();
                }
                string type = ASCIIEncoding.ASCII.GetString(name.ToArray());
                _types[i] = new Dna.TypeDecl(type);
            }
            stream.Position = (stream.Position + 3) & ~3;

            // TLEN
            code  = reader.ReadBytes(4);
            codes = ASCIIEncoding.ASCII.GetString(code);
            if (!codes.Equals("TLEN"))
            {
                throw new InvalidDataException();
            }
            for (int i = 0; i < _types.Length; i++)
            {
                _types[i].Length = reader.ReadInt16();
            }
            stream.Position = (stream.Position + 3) & ~3;

            // STRC
            code  = reader.ReadBytes(4);
            codes = ASCIIEncoding.ASCII.GetString(code);
            if (!codes.Equals("STRC"))
            {
                throw new InvalidDataException();
            }
            dataLen  = reader.ReadInt32();
            _structs = new Dna.StructDecl[dataLen];
            long shtPtr = stream.Position;

            for (int i = 0; i < dataLen; i++)
            {
                Dna.StructDecl structDecl = new Dna.StructDecl();
                _structs[i] = structDecl;
                if (!BitConverter.IsLittleEndian)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    short typeNr = reader.ReadInt16();
                    structDecl.Type        = _types[typeNr];
                    structDecl.Type.Struct = structDecl;
                    int numElements = reader.ReadInt16();
                    structDecl.Elements = new Dna.ElementDecl[numElements];
                    for (int j = 0; j < numElements; j++)
                    {
                        typeNr = reader.ReadInt16();
                        short nameNr = reader.ReadInt16();
                        structDecl.Elements[j] = new Dna.ElementDecl(_types[typeNr], _names[nameNr]);
                    }
                }
            }

            reader.Dispose();
            stream.Dispose();

            // build reverse lookups
            _structReverse = new Dictionary <string, Dna.StructDecl>(_structs.Length);
            foreach (Dna.StructDecl s in _structs)
            {
                _structReverse.Add(s.Type.Name, s);
            }
        }
 protected override void Write(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
 stream.WriteAsync(new Memory <byte>(array, offset, count)).GetAwaiter().GetResult();
Example #21
0
 private static DataBox CreateDataBox(SafeUnmanagedArray array, UnmanagedMemoryStream input, Int32 rowPitch, Int32 depthPitch)
 {
     return(new DataBox(new IntPtr(array.DangerousGetHandle().ToInt64() + input.Position), rowPitch, depthPitch));
 }
 protected override int Read(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
 stream.Read(new Span <byte>(array, offset, count));
Example #23
0
 protected abstract int Read(UnmanagedMemoryStream stream, byte[] array, int offset, int count);
        public static void CopyToTest()
        {
            byte[] testData = ArrayHelpers.CreateByteArray(8192);

            using (var manager = new UmsManager(FileAccess.Read, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.ReadUmsInvariants(ums);
                MemoryStream destination = new MemoryStream();

                destination.Position = 0;
                ums.CopyTo(destination);
                Assert.Equal(testData, destination.ToArray());

                destination.Position = 0;
                ums.CopyTo(destination, 1);
                Assert.Equal(testData, destination.ToArray());
            }

            // copy to disposed stream should throw
            using (var manager = new UmsManager(FileAccess.Read, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.ReadUmsInvariants(ums);

                MemoryStream destination = new MemoryStream();
                destination.Dispose();

                Assert.Throws <ObjectDisposedException>(() => ums.CopyTo(destination));
            }

            // copy from disposed stream should throw
            using (var manager = new UmsManager(FileAccess.Read, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.ReadUmsInvariants(ums);
                ums.Dispose();

                MemoryStream destination = new MemoryStream();

                Assert.Throws <ObjectDisposedException>(() => ums.CopyTo(destination));
            }

            // copying to non-writable stream should throw
            using (var manager = new UmsManager(FileAccess.Read, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.ReadUmsInvariants(ums);

                MemoryStream destination = new MemoryStream(new byte[0], false);

                Assert.Throws <NotSupportedException>(() => ums.CopyTo(destination));
            }

            // copying from non-readable stream should throw
            using (var manager = new UmsManager(FileAccess.Write, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.WriteUmsInvariants(ums);

                MemoryStream destination = new MemoryStream(new byte[0], false);

                Assert.Throws <NotSupportedException>(() => ums.CopyTo(destination));
            }
        }
Example #25
0
        public static unsafe byte[] ConvertDDS(Stream ddsSteam, DXGI_FORMAT targetFormat, ImageFormat imageFormat, int frame)
        {
            try {
                CoInitializeEx(IntPtr.Zero, CoInit.MultiThreaded | CoInit.SpeedOverMemory);

                byte[] data = new byte[ddsSteam.Length];
                ddsSteam.Read(data, 0, data.Length);
                ScratchImage scratch = null;
                try
                {
                    fixed(byte *dataPin = data)
                    {
                        scratch = TexHelper.Instance.LoadFromDDSMemory((IntPtr)dataPin, data.Length, DDS_FLAGS.NONE);
                        TexMetadata info = scratch.GetMetadata();

                        if (TexHelper.Instance.IsCompressed(info.Format))
                        {
                            ScratchImage temp = scratch.Decompress(frame, DXGI_FORMAT.UNKNOWN);
                            scratch.Dispose();
                            scratch = temp;
                        }

                        info = scratch.GetMetadata();

                        if (info.Format != targetFormat)
                        {
                            ScratchImage temp = scratch.Convert(targetFormat, TEX_FILTER_FLAGS.DEFAULT, 0.5f);
                            scratch.Dispose();
                            scratch = temp;
                        }

                        UnmanagedMemoryStream stream = null;

                        if (imageFormat == ImageFormat.TGA)
                        {
                            stream = scratch.SaveToTGAMemory(frame < 0 ? 0 : frame);
                        }
                        else
                        {
                            WICCodecs codec        = WICCodecs.PNG;
                            bool      isMultiFrame = false;
                            switch (imageFormat)
                            {
                            case ImageFormat.BMP:
                                codec = WICCodecs.BMP;
                                break;

                            case ImageFormat.GIF:
                                codec        = WICCodecs.GIF;
                                isMultiFrame = true;
                                break;

                            case ImageFormat.JPEG:
                                codec = WICCodecs.JPEG;
                                break;

                            case ImageFormat.PNG:
                                codec = WICCodecs.PNG;
                                break;

                            case ImageFormat.TIF:
                                codec        = WICCodecs.TIFF;
                                isMultiFrame = true;
                                break;

                            case ImageFormat.TGA:
                                break;

                            default:
                                throw new ArgumentOutOfRangeException(nameof(imageFormat), imageFormat, null);
                            }

                            if (frame < 0)
                            {
                                if (!isMultiFrame)
                                {
                                    frame = 0;
                                }
                                else
                                {
                                    stream = scratch.SaveToWICMemory(0, info.ArraySize, WIC_FLAGS.ALL_FRAMES, TexHelper.Instance.GetWICCodec(codec));
                                }
                            }

                            if (frame >= 0)
                            {
                                stream = scratch.SaveToWICMemory(frame, WIC_FLAGS.NONE, TexHelper.Instance.GetWICCodec(codec));
                            }
                        }

                        if (stream == null)
                        {
                            return(null);
                        }

                        byte[] tex = new byte[stream.Length];
                        stream.Read(tex, 0, tex.Length);
                        scratch.Dispose();
                        return(tex);
                    }
                } catch {
                    if (scratch != null && scratch.IsDisposed == false)
                    {
                        scratch.Dispose();
                    }
                }
            } catch {
                // ignored
            }

            return(null);
        }
        private object DeserializeObject(int typeIndex)
        {
            Type type = FindType(typeIndex);

            if (_assumeBinaryFormatter)
            {
                return(ReadBinaryFormattedObject());
            }

            // read type
            SerializationFormat format = (SerializationFormat)_store.Read7BitEncodedInt();

            object value;

            // read data
            switch (format)
            {
            case SerializationFormat.BinaryFormatter:
            {
                // read length
                int length = _store.Read7BitEncodedInt();
                if (length < 0)
                {
                    throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length));
                }

                long originalPosition = _store.BaseStream.Position;

                value = ReadBinaryFormattedObject();

                if (type == typeof(UnknownType))
                {
                    // type information was omitted at the time of writing
                    // allow the payload to define the type
                    type = value.GetType();
                }

                long bytesRead = _store.BaseStream.Position - originalPosition;

                // Ensure BF read what we expected.
                if (bytesRead != length)
                {
                    throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length));
                }
                break;
            }

            case SerializationFormat.TypeConverterByteArray:
            {
                // read length
                int length = _store.Read7BitEncodedInt();
                if (length < 0)
                {
                    throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length));
                }

                byte[] data = _store.ReadBytes(length);

                TypeConverter converter = TypeDescriptor.GetConverter(type);

                if (converter == null)
                {
                    throw new TypeLoadException(SR.Format(SR.TypeLoadException_CannotLoadConverter, type));
                }

                value = converter.ConvertFrom(data);
                break;
            }

            case SerializationFormat.TypeConverterString:
            {
                string stringData = _store.ReadString();

                TypeConverter converter = TypeDescriptor.GetConverter(type);

                if (converter == null)
                {
                    throw new TypeLoadException(SR.Format(SR.TypeLoadException_CannotLoadConverter, type));
                }

                value = converter.ConvertFromInvariantString(stringData);
                break;
            }

            case SerializationFormat.ActivatorStream:
            {
                // read length
                int length = _store.Read7BitEncodedInt();
                if (length < 0)
                {
                    throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length));
                }
                Stream stream;

                if (_store.BaseStream is UnmanagedMemoryStream ums)
                {
                    // For the case that we've memory mapped in the .resources
                    // file, just return a Stream pointing to that block of memory.
                    unsafe
                    {
                        stream = new UnmanagedMemoryStream(ums.PositionPointer, length, length, FileAccess.Read);
                    }
                }
                else
                {
                    byte[] bytes = _store.ReadBytes(length);
                    // Lifetime of memory == lifetime of this stream.
                    stream = new MemoryStream(bytes, false);
                }

                value = Activator.CreateInstance(type, new object[] { stream });
                break;
            }

            default:
                throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch);
            }

            // Make sure we deserialized the type that we expected.
            // This protects against bad typeconverters or bad binaryformatter payloads.
            if (value.GetType() != type)
            {
                throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResType_SerBlobMismatch, type.FullName, value.GetType().FullName));
            }

            return(value);
        }
Example #27
0
 public KeysSoundEffects(ILog log, UnmanagedMemoryStream key1Sound, UnmanagedMemoryStream key2Sound, UnmanagedMemoryStream crtlSound, UnmanagedMemoryStream shiftSound, UnmanagedMemoryStream winSound,
                         UnmanagedMemoryStream rightAltSound, UnmanagedMemoryStream leftAltSound = null)
 {
     logger           = log;
     FirstKeySound    = key1Sound;
     SecondKeySound   = key2Sound;
     CrtlActionSound  = crtlSound;
     ShiftActionSound = shiftSound;
     WinActionSound   = winSound;
     AltActionSound   = rightAltSound;
 }
        public static void SeekTests()
        {
            const int length = 1000;

            using (var manager = new UmsManager(FileAccess.ReadWrite, length))
            {
                UnmanagedMemoryStream stream = manager.Stream;
                UmsTests.ReadWriteUmsInvariants(stream);

                Assert.Throws <IOException>(() => stream.Seek(unchecked (int.MaxValue + 1), SeekOrigin.Begin));
                Assert.Throws <IOException>(() => stream.Seek(long.MinValue, SeekOrigin.End));
                AssertExtensions.Throws <ArgumentException>(null, () => stream.Seek(0, (SeekOrigin)7)); // Invalid seek origin

                stream.Seek(10, SeekOrigin.Begin);
                Assert.Equal(10, stream.Position);

                Assert.Throws <IOException>(() => stream.Seek(-1, SeekOrigin.Begin)); // An attempt was made to move the position before the beginning of the stream
                Assert.Equal(10, stream.Position);

                Assert.Throws <IOException>(() => stream.Seek(-(stream.Position + 1), SeekOrigin.Current)); // An attempt was made to move the position before the beginning of the stream
                Assert.Equal(10, stream.Position);

                Assert.Throws <IOException>(() => stream.Seek(-(stream.Length + 1), SeekOrigin.End)); //  "An attempt was made to move the position before the beginning of the stream."
                Assert.Equal(10, stream.Position);

                // Seek from SeekOrigin.Begin
                stream.Seek(0, SeekOrigin.Begin);
                for (int position = 0; position < stream.Length; position++)
                {
                    stream.Seek(position, SeekOrigin.Begin);
                    Assert.Equal(position, stream.Position);
                }

                for (int position = (int)stream.Length; position >= 0; position--)
                {
                    stream.Seek(position, SeekOrigin.Begin);
                    Assert.Equal(position, stream.Position);
                }

                stream.Seek(0, SeekOrigin.Begin);
                // Seek from SeekOrigin.End
                for (int position = 0; position < stream.Length; position++)
                {
                    stream.Seek(-position, SeekOrigin.End);
                    Assert.Equal(length - position, stream.Position);
                }

                for (int position = (int)stream.Length; position >= 0; position--)
                {
                    stream.Seek(-position, SeekOrigin.End);
                    Assert.Equal(length - position, stream.Position);
                }

                // Seek from SeekOrigin.Current
                stream.Seek(0, SeekOrigin.Begin);
                for (int position = 0; position < stream.Length; position++)
                {
                    stream.Seek(1, SeekOrigin.Current);
                    Assert.Equal(position + 1, stream.Position);
                }

                for (int position = (int)stream.Length; position > 0; position--)
                {
                    stream.Seek(-1, SeekOrigin.Current);
                    Assert.Equal(position - 1, stream.Position);
                }
            }
        }
        public static async Task CopyToAsyncTest()
        {
            byte[] testData = ArrayHelpers.CreateByteArray(8192);

            using (var manager = new UmsManager(FileAccess.Read, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.ReadUmsInvariants(ums);
                MemoryStream destination = new MemoryStream();

                destination.Position = 0;
                await ums.CopyToAsync(destination);

                Assert.Equal(testData, destination.ToArray());

                destination.Position = 0;
                await ums.CopyToAsync(destination, 2);

                Assert.Equal(testData, destination.ToArray());

                destination.Position = 0;
                await ums.CopyToAsync(destination, 0x1000, new CancellationTokenSource().Token);

                Assert.Equal(testData, destination.ToArray());

                await Assert.ThrowsAnyAsync <OperationCanceledException>(() => ums.CopyToAsync(destination, 0x1000, new CancellationToken(true)));
            }

            // copy to disposed stream should throw
            using (var manager = new UmsManager(FileAccess.Read, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.ReadUmsInvariants(ums);

                MemoryStream destination = new MemoryStream();
                destination.Dispose();

                await Assert.ThrowsAsync <ObjectDisposedException>(() => ums.CopyToAsync(destination));
            }

            // copy from disposed stream should throw
            using (var manager = new UmsManager(FileAccess.Read, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.ReadUmsInvariants(ums);
                ums.Dispose();

                MemoryStream destination = new MemoryStream();

                await Assert.ThrowsAsync <ObjectDisposedException>(() => ums.CopyToAsync(destination));
            }

            // copying to non-writable stream should throw
            using (var manager = new UmsManager(FileAccess.Read, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.ReadUmsInvariants(ums);

                MemoryStream destination = new MemoryStream(new byte[0], false);

                await Assert.ThrowsAsync <NotSupportedException>(() => ums.CopyToAsync(destination));
            }

            // copying from non-readable stream should throw
            using (var manager = new UmsManager(FileAccess.Write, testData))
            {
                UnmanagedMemoryStream ums = manager.Stream;
                UmsTests.WriteUmsInvariants(ums);

                MemoryStream destination = new MemoryStream(new byte[0], false);

                await Assert.ThrowsAsync <NotSupportedException>(() => ums.CopyToAsync(destination));
            }
        }
Example #30
0
 /// <summary>
 /// Decodes a jpeg image
 /// </summary>
 /// <param name="jpeg">The stream that contains the jpeg data</param>
 public void Decode(UnmanagedMemoryStream jpeg)
 {
     Decode(jpeg.PositionPointer, (int)jpeg.Length, false);
 }
Example #31
0
    public static unsafe void Initialize()
    {
        Module mod = typeof(AntiTamperJIT).Module;
        IntPtr modPtr = Marshal.GetHINSTANCE(mod);
        s = (ulong)modPtr.ToInt64();
        if (modPtr == (IntPtr)(-1)) Environment.FailFast(null);
        string fq = mod.FullyQualifiedName;
        bool mapped = fq[0] != '<'; //<Unknown>
        Stream stream;
        stream = new UnmanagedMemoryStream((byte*)modPtr.ToPointer(), 0xfffffff, 0xfffffff, FileAccess.ReadWrite);

        byte[] buff;
        int checkSumOffset;
        ulong checkSum;
        byte[] iv;
        byte[] dats;
        int sn;
        int snLen;
        using (BinaryReader rdr = new BinaryReader(stream))
        {
            stream.Seek(0x3c, SeekOrigin.Begin);
            uint offset = rdr.ReadUInt32();
            stream.Seek(offset, SeekOrigin.Begin);
            stream.Seek(0x6, SeekOrigin.Current);
            uint sections = rdr.ReadUInt16();
            stream.Seek(0xC, SeekOrigin.Current);
            uint optSize = rdr.ReadUInt16();
            stream.Seek(offset = offset + 0x18, SeekOrigin.Begin);  //Optional hdr
            bool pe32 = (rdr.ReadUInt16() == 0x010b);
            stream.Seek(0x3e, SeekOrigin.Current);
            checkSumOffset = (int)stream.Position;
            uint md = rdr.ReadUInt32() ^ (uint)Mutation.Key0I;
            if (md == (uint)Mutation.Key0I)
                return;

            stream.Seek(offset = offset + optSize, SeekOrigin.Begin);  //sect hdr
            uint datLoc = 0;
            for (int i = 0; i < sections; i++)
            {
                int h = 0;
                for (int j = 0; j < 8; j++)
                {
                    byte chr = rdr.ReadByte();
                    if (chr != 0) h += chr;
                }
                uint vSize = rdr.ReadUInt32();
                uint vLoc = rdr.ReadUInt32();
                uint rSize = rdr.ReadUInt32();
                uint rLoc = rdr.ReadUInt32();
                if (h == Mutation.Key1I)
                    datLoc = mapped ? vLoc : rLoc;

                if (!mapped && md > vLoc && md < vLoc + vSize)
                    md = md - vLoc + rLoc;

                if (mapped && vSize + vLoc > l) l = vSize + vLoc;
                else if (rSize + rLoc > l) l = rSize + rLoc;

                stream.Seek(0x10, SeekOrigin.Current);
            }

            stream.Seek(md, SeekOrigin.Begin);
            using (MemoryStream str = new MemoryStream())
            {
                stream.Position += 12;
                stream.Position += rdr.ReadUInt32() + 4;
                stream.Position += 2;

                ushort streams = rdr.ReadUInt16();

                for (int i = 0; i < streams; i++)
                {
                    uint pos = rdr.ReadUInt32() + md;
                    uint size = rdr.ReadUInt32();

                    int c = 0;
                    while (rdr.ReadByte() != 0) c++;
                    long ori = stream.Position += (((c + 1) + 3) & ~3) - (c + 1);

                    stream.Position = pos;
                    str.Write(rdr.ReadBytes((int)size), 0, (int)size);
                    stream.Position = ori;
                }

                buff = str.ToArray();
            }

            stream.Seek(datLoc, SeekOrigin.Begin);
            checkSum = rdr.ReadUInt64() ^ (ulong)Mutation.Key0L;
            sn = rdr.ReadInt32();
            snLen = rdr.ReadInt32();
            iv = rdr.ReadBytes(rdr.ReadInt32() ^ Mutation.Key2I);
            dats = rdr.ReadBytes(rdr.ReadInt32() ^ Mutation.Key3I);
        }

        byte[] md5 = MD5.Create().ComputeHash(buff);
        ulong tCs = BitConverter.ToUInt64(md5, 0) ^ BitConverter.ToUInt64(md5, 8);
        ulong* msg = stackalloc ulong[2];
        msg[0] = 0x6574707572726f43;    //Corrupte
        msg[1] = 0x0021656c69662064;    //d file!.
        if (tCs != checkSum)
            Environment.FailFast(new string((sbyte*)msg));

        byte[] b = Decrypt(buff, iv, dats);
        Buffer.BlockCopy(new byte[buff.Length], 0, buff, 0, buff.Length);
        if (b[0] != 0xd6 || b[1] != 0x6f)
            Environment.FailFast(new string((sbyte*)msg));
        byte[] dat = new byte[b.Length - 2];
        Buffer.BlockCopy(b, 2, dat, 0, dat.Length);

        data = dat;
        Hook();
        //AppDomain.CurrentDomain.ProcessExit += Dispose;
    }
        private static sbyte[] calculateRSECC(sbyte[] codewords, sbyte rsEccCodewords, sbyte[] rsBlockOrder, int maxDataCodewords, int maxCodewords)
        {
            sbyte[][] rsCalTableArray = new sbyte[256][];
            for (int i = 0; i < 256; i++)
            {
                rsCalTableArray[i] = new sbyte[rsEccCodewords];
            }
            try
            {
                //String filename = QRCODE_DATA_PATH + @"\rsc" + rsEccCodewords.ToString() + ".dat";
                //StreamReader reader = new StreamReader(filename);
                String fileName = "rsc" + rsEccCodewords.ToString();
                UnmanagedMemoryStream memoryStream = Resources.ResourceManager.GetStream(fileName);
                BufferedStream        bis          = new BufferedStream(memoryStream);
                for (int i = 0; i < 256; i++)
                {
                    SystemUtils.ReadInput(bis, rsCalTableArray[i], 0, rsCalTableArray[i].Length);
                }
                bis.Close();
                //reader.Close();
                memoryStream.Close();
            }
            catch (Exception e)
            {
                SystemUtils.WriteStackTrace(e, Console.Error);
            }


            /* ---- RS-ECC prepare */

            int i2            = 0;
            int j             = 0;
            int rsBlockNumber = 0;

            byte dim2 = Convert.ToByte((rsBlockOrder[rsBlockNumber] & 0xFF) - rsEccCodewords);

            sbyte[][] rsTemp = new sbyte[rsBlockOrder.Length][];

            /*(
             * for (int i = 0; i < rsBlockOrder.Length; i++)
             * {
             *  rsTemp[i] = new sbyte[rsBlockOrder.Length];
             * }
             */
            sbyte[] res = new sbyte[maxCodewords];
            Array.Copy(codewords, 0, res, 0, codewords.Length);

            i2 = 0;
            while (i2 < rsBlockOrder.Length)
            {
                rsTemp[i2] = new sbyte[(rsBlockOrder[i2] & 0xFF) - rsEccCodewords];
                i2++;
            }
            i2 = 0;
            while (i2 < maxDataCodewords)
            {
                rsTemp[rsBlockNumber][j] = codewords[i2];
                j++;
                if (j >= (rsBlockOrder[rsBlockNumber] & 0xFF) - rsEccCodewords)
                {
                    j = 0;
                    rsBlockNumber++;
                }
                i2++;
            }

            /* ---  RS-ECC main --- */

            rsBlockNumber = 0;
            while (rsBlockNumber < rsBlockOrder.Length)
            {
                sbyte[] rsTempData;
                rsTempData = new sbyte[rsTemp[rsBlockNumber].Length];
                rsTemp[rsBlockNumber].CopyTo(rsTempData, 0);

                int rsCodewords     = (rsBlockOrder[rsBlockNumber] & 0xFF);
                int rsDataCodewords = rsCodewords - rsEccCodewords;

                j = rsDataCodewords;
                while (j > 0)
                {
                    sbyte first = rsTempData[0];
                    if (first != 0)
                    {
                        sbyte[] leftChr = new sbyte[rsTempData.Length - 1];
                        Array.Copy(rsTempData, 1, leftChr, 0, rsTempData.Length - 1);
                        sbyte[] cal = rsCalTableArray[(first & 0xFF)];
                        rsTempData = calculateByteArrayBits(leftChr, cal, "xor");
                    }
                    else
                    {
                        if (rsEccCodewords < rsTempData.Length)
                        {
                            sbyte[] rsTempNew = new sbyte[rsTempData.Length - 1];
                            Array.Copy(rsTempData, 1, rsTempNew, 0, rsTempData.Length - 1);
                            rsTempData = new sbyte[rsTempNew.Length];
                            rsTempNew.CopyTo(rsTempData, 0);
                        }
                        else
                        {
                            sbyte[] rsTempNew = new sbyte[rsEccCodewords];
                            Array.Copy(rsTempData, 1, rsTempNew, 0, rsTempData.Length - 1);
                            rsTempNew[rsEccCodewords - 1] = 0;
                            rsTempData = new sbyte[rsTempNew.Length];
                            rsTempNew.CopyTo(rsTempData, 0);
                        }
                    }
                    j--;
                }

                Array.Copy(rsTempData, 0, res, codewords.Length + rsBlockNumber * rsEccCodewords, (byte)rsEccCodewords);
                rsBlockNumber++;
            }
            return(res);
        }
 internal static void UmsInvariants(UnmanagedMemoryStream stream)
 {
     Assert.False(stream.CanTimeout);
 }
Example #34
0
    public static unsafe void Initalize()
    {
        Module mod = typeof(AntiTamperMem).Module;
        IntPtr modPtr = Marshal.GetHINSTANCE(mod);
        if (modPtr == (IntPtr)(-1)) Environment.FailFast("Module error");
        bool mapped = mod.FullyQualifiedName[0] != '<'; //<Unknown>
        Stream stream;
        stream = new UnmanagedMemoryStream((byte*)modPtr.ToPointer(), 0xfffffff, 0xfffffff, FileAccess.ReadWrite);

        byte[] buff;
        int checkSumOffset;
        ulong checkSum;
        byte[] iv;
        byte[] dats;
        int sn;
        int snLen;
        using (BinaryReader rdr = new BinaryReader(stream))
        {
            stream.Seek(0x3c, SeekOrigin.Begin);
            uint offset = rdr.ReadUInt32();
            stream.Seek(offset, SeekOrigin.Begin);
            stream.Seek(0x6, SeekOrigin.Current);
            uint sections = rdr.ReadUInt16();
            stream.Seek(0xC, SeekOrigin.Current);
            uint optSize = rdr.ReadUInt16();
            stream.Seek(offset = offset + 0x18, SeekOrigin.Begin);  //Optional hdr
            bool pe32 = (rdr.ReadUInt16() == 0x010b);
            stream.Seek(0x3e, SeekOrigin.Current);
            checkSumOffset = (int)stream.Position;
            uint md = rdr.ReadUInt32() ^ (uint)Mutation.Key0I;
            if (md == (uint)Mutation.Key0I)
                Environment.FailFast("Broken file");

            stream.Seek(offset = offset + optSize, SeekOrigin.Begin);  //sect hdr
            uint datLoc = 0;
            for (int i = 0; i < sections; i++)
            {
                int h = 0;
                for (int j = 0; j < 8; j++)
                {
                    byte chr = rdr.ReadByte();
                    if (chr != 0) h += chr;
                }
                uint vSize = rdr.ReadUInt32();
                uint vLoc = rdr.ReadUInt32();
                uint rSize = rdr.ReadUInt32();
                uint rLoc = rdr.ReadUInt32();
                if (h == Mutation.Key1I)
                    datLoc = mapped ? vLoc : rLoc;
                if (!mapped && md > vLoc && md < vLoc + vSize)
                    md = md - vLoc + rLoc;
                stream.Seek(0x10, SeekOrigin.Current);
            }

            stream.Seek(md, SeekOrigin.Begin);
            using (MemoryStream str = new MemoryStream())
            {
                stream.Position += 12;
                stream.Position += rdr.ReadUInt32() + 4;
                stream.Position += 2;

                ushort streams = rdr.ReadUInt16();

                for (int i = 0; i < streams; i++)
                {
                    uint pos = rdr.ReadUInt32() + md;
                    uint size = rdr.ReadUInt32();

                    int c = 0;
                    while (rdr.ReadByte() != 0) c++;
                    long ori = stream.Position += (((c + 1) + 3) & ~3) - (c + 1);

                    stream.Position = pos;
                    str.Write(rdr.ReadBytes((int)size), 0, (int)size);
                    stream.Position = ori;
                }

                buff = str.ToArray();
            }

            stream.Seek(datLoc, SeekOrigin.Begin);
            checkSum = rdr.ReadUInt64() ^ (ulong)Mutation.Key0L;
            sn = rdr.ReadInt32();
            snLen = rdr.ReadInt32();
            iv = rdr.ReadBytes(rdr.ReadInt32() ^ Mutation.Key2I);
            dats = rdr.ReadBytes(rdr.ReadInt32() ^ Mutation.Key3I);
        }

        byte[] md5 = MD5.Create().ComputeHash(buff);
        ulong tCs = BitConverter.ToUInt64(md5, 0) ^ BitConverter.ToUInt64(md5, 8);
        if (tCs != checkSum)
            Environment.FailFast("Broken file");

        byte[] b = Decrypt(buff, iv, dats);
        Buffer.BlockCopy(new byte[buff.Length], 0, buff, 0, buff.Length);
        if (b[0] != 0xd6 || b[1] != 0x6f)
            Environment.FailFast("Broken file");
        byte[] tB = new byte[b.Length - 2];
        Buffer.BlockCopy(b, 2, tB, 0, tB.Length);
        using (BinaryReader rdr = new BinaryReader(new MemoryStream(tB)))
        {
            uint len = rdr.ReadUInt32();
            int[] codeLens = new int[len];
            IntPtr[] ptrs = new IntPtr[len];
            for (int i = 0; i < len; i++)
            {
                uint pos = rdr.ReadUInt32() ^ (uint)Mutation.Key4I;
                if (pos == 0) continue;
                uint rva = rdr.ReadUInt32() ^ (uint)Mutation.Key5I;
                byte[] cDat = rdr.ReadBytes(rdr.ReadInt32());
                uint old;
                IntPtr ptr = (IntPtr)((uint)modPtr + (mapped ? rva : pos));
                VirtualProtect(ptr, (uint)cDat.Length, 0x04, out old);
                Marshal.Copy(cDat, 0, ptr, cDat.Length);
                VirtualProtect(ptr, (uint)cDat.Length, old, out old);
                codeLens[i] = cDat.Length;
                ptrs[i] = ptr;
            }
            //for (int i = 0; i < len; i++)
            //{
            //    if (codeLens[i] == 0) continue;
            //    RuntimeHelpers.PrepareMethod(mod.ModuleHandle.GetRuntimeMethodHandleFromMetadataToken(0x06000000 + i + 1));
            //}
            //for (int i = 0; i < len; i++)
            //{
            //    if (codeLens[i] == 0) continue;
            //    uint old;
            //    VirtualProtect(ptrs[i], (uint)codeLens[i], 0x04, out old);
            //    Marshal.Copy(new byte[codeLens[i]], 0, ptrs[i], codeLens[i]);
            //    VirtualProtect(ptrs[i], (uint)codeLens[i], old, out old);
            //}
        }
    }
Example #35
0
        public static void ReadWriteByteSafeBuffer()
        {
            const int length = 1000;
            using (var buffer = new TestSafeBuffer(length))
            {
                var stream = new UnmanagedMemoryStream(buffer, 0, (long)buffer.ByteLength, FileAccess.ReadWrite);
                Assert.Equal(stream.Length, length);

                var bytes = ArrayHelpers.CreateByteArray(length);
                for (int index = 0; index < length; index++)
                {
                    stream.WriteByte(bytes[index]);
                }

                stream.Position = 0;
                for (int index = 0; index < length; index++)
                {
                    int value = stream.ReadByte();
                    Assert.Equal(bytes[index], (byte)value);
                }

                var memory = buffer.ToArray();
                Assert.Equal(bytes, memory, ArrayHelpers.Comparer<byte>());
            }
        }
Example #36
0
 protected abstract void Write(UnmanagedMemoryStream stream, byte[] array, int offset, int count);
Example #37
0
 private static DataRectangle CreateDataRectangle(SafeUnmanagedArray array, UnmanagedMemoryStream input, Int32 pitch)
 {
     return(new DataRectangle(new IntPtr(array.DangerousGetHandle().ToInt64() + input.Position), pitch));
 }
Example #38
0
        private static unsafe MD5Hash Hash(byte *ptr, int length)
        {
            var stream = new UnmanagedMemoryStream(ptr, length);

            return(Hash(stream));
        }
        public virtual bool[][] calQrcode(byte[] qrcodeData)
        {
            int dataLength;
            int dataCounter = 0;

            dataLength = qrcodeData.Length;

            int[]   dataValue = new int[dataLength + 32];
            sbyte[] dataBits  = new sbyte[dataLength + 32];

            if (dataLength <= 0)
            {
                bool[][] ret = new bool[][] { new bool[] { false } };
                return(ret);
            }

            if (qrcodeStructureappendN > 1)
            {
                dataValue[0] = 3;
                dataBits[0]  = 4;

                dataValue[1] = qrcodeStructureappendM - 1;
                dataBits[1]  = 4;

                dataValue[2] = qrcodeStructureappendN - 1;
                dataBits[2]  = 4;

                dataValue[3] = qrcodeStructureappendParity;
                dataBits[3]  = 8;

                dataCounter = 4;
            }
            dataBits[dataCounter] = 4;

            /*  --- determine encode mode --- */

            int[] codewordNumPlus;
            int   codewordNumCounterValue;

            switch (qrcodeEncodeMode)
            {
            /* ---- alphanumeric mode ---  */
            case ENCODE_MODE.ALPHA_NUMERIC:

                codewordNumPlus = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 };

                dataValue[dataCounter] = 2;
                dataCounter++;
                dataValue[dataCounter]  = dataLength;
                dataBits[dataCounter]   = 9;
                codewordNumCounterValue = dataCounter;

                dataCounter++;
                for (int i = 0; i < dataLength; i++)
                {
                    char  chr      = (char)qrcodeData[i];
                    sbyte chrValue = 0;
                    if (chr >= 48 && chr < 58)
                    {
                        chrValue = (sbyte)(chr - 48);
                    }
                    else
                    {
                        if (chr >= 65 && chr < 91)
                        {
                            chrValue = (sbyte)(chr - 55);
                        }
                        else
                        {
                            if (chr == 32)
                            {
                                chrValue = 36;
                            }
                            if (chr == 36)
                            {
                                chrValue = 37;
                            }
                            if (chr == 37)
                            {
                                chrValue = 38;
                            }
                            if (chr == 42)
                            {
                                chrValue = 39;
                            }
                            if (chr == 43)
                            {
                                chrValue = 40;
                            }
                            if (chr == 45)
                            {
                                chrValue = 41;
                            }
                            if (chr == 46)
                            {
                                chrValue = 42;
                            }
                            if (chr == 47)
                            {
                                chrValue = 43;
                            }
                            if (chr == 58)
                            {
                                chrValue = 44;
                            }
                        }
                    }
                    if ((i % 2) == 0)
                    {
                        dataValue[dataCounter] = chrValue;
                        dataBits[dataCounter]  = 6;
                    }
                    else
                    {
                        dataValue[dataCounter] = dataValue[dataCounter] * 45 + chrValue;
                        dataBits[dataCounter]  = 11;
                        if (i < dataLength - 1)
                        {
                            dataCounter++;
                        }
                    }
                }
                dataCounter++;
                break;

            /* ---- numeric mode ---- */

            case ENCODE_MODE.NUMERIC:

                codewordNumPlus = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 };

                dataValue[dataCounter] = 1;
                dataCounter++;
                dataValue[dataCounter] = dataLength;

                dataBits[dataCounter]   = 10;                       /* #version 1-9*/
                codewordNumCounterValue = dataCounter;

                dataCounter++;
                for (int i = 0; i < dataLength; i++)
                {
                    if ((i % 3) == 0)
                    {
                        dataValue[dataCounter] = (int)(qrcodeData[i] - 0x30);
                        dataBits[dataCounter]  = 4;
                    }
                    else
                    {
                        dataValue[dataCounter] = dataValue[dataCounter] * 10 + (int)(qrcodeData[i] - 0x30);

                        if ((i % 3) == 1)
                        {
                            dataBits[dataCounter] = 7;
                        }
                        else
                        {
                            dataBits[dataCounter] = 10;
                            if (i < dataLength - 1)
                            {
                                dataCounter++;
                            }
                        }
                    }
                }
                dataCounter++;
                break;

            /* ---- 8bit byte ---- */

            default:

                codewordNumPlus        = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 };
                dataValue[dataCounter] = 4;
                dataCounter++;
                dataValue[dataCounter]  = dataLength;
                dataBits[dataCounter]   = 8;                       /* #version 1-9 */
                codewordNumCounterValue = dataCounter;

                dataCounter++;

                for (int i = 0; i < dataLength; i++)
                {
                    dataValue[i + dataCounter] = (qrcodeData[i] & 0xFF);
                    dataBits[i + dataCounter]  = 8;
                }
                dataCounter += dataLength;

                break;
            }

            int totalDataBits = 0;

            for (int i = 0; i < dataCounter; i++)
            {
                totalDataBits += dataBits[i];
            }

            int ec;

            switch (qrcodeErrorCorrect)
            {
            case ERROR_CORRECTION.L:
                ec = 1;
                break;

            case ERROR_CORRECTION.Q:
                ec = 3;
                break;

            case ERROR_CORRECTION.H:
                ec = 2;
                break;

            default:
                ec = 0;
                break;
            }


            int[][] maxDataBitsArray = new int[][] { new int[] { 0, 128, 224, 352, 512, 688, 864, 992, 1232, 1456, 1728, 2032, 2320, 2672, 2920, 3320, 3624, 4056, 4504, 5016, 5352, 5712, 6256, 6880, 7312, 8000, 8496, 9024, 9544, 10136, 10984, 11640, 12328, 13048, 13800, 14496, 15312, 15936, 16816, 17728, 18672 }, new int[] { 0, 152, 272, 440, 640, 864, 1088, 1248, 1552, 1856, 2192, 2592, 2960, 3424, 3688, 4184, 4712, 5176, 5768, 6360, 6888, 7456, 8048, 8752, 9392, 10208, 10960, 11744, 12248, 13048, 13880, 14744, 15640, 16568, 17528, 18448, 19472, 20528, 21616, 22496, 23648 }, new int[] { 0, 72, 128, 208, 288, 368, 480, 528, 688, 800, 976, 1120, 1264, 1440, 1576, 1784, 2024, 2264, 2504, 2728, 3080, 3248, 3536, 3712, 4112, 4304, 4768, 5024, 5288, 5608, 5960, 6344, 6760, 7208, 7688, 7888, 8432, 8768, 9136, 9776, 10208 }, new int[] { 0, 104, 176, 272, 384, 496, 608, 704, 880, 1056, 1232, 1440, 1648, 1952, 2088, 2360, 2600, 2936, 3176, 3560, 3880, 4096, 4544, 4912, 5312, 5744, 6032, 6464, 6968, 7288, 7880, 8264, 8920, 9368, 9848, 10288, 10832, 11408, 12016, 12656, 13328 } };

            int maxDataBits = 0;

            if (qrcodeVersion == 0)
            {
                /* auto version select */

                qrcodeVersion = 1;
                for (int i = 1; i <= 40; i++)
                {
                    if ((maxDataBitsArray[ec][i]) >= totalDataBits + codewordNumPlus[qrcodeVersion])
                    {
                        maxDataBits = maxDataBitsArray[ec][i];
                        break;
                    }
                    qrcodeVersion++;
                }
            }
            else
            {
                maxDataBits = maxDataBitsArray[ec][qrcodeVersion];
            }
            totalDataBits += codewordNumPlus[qrcodeVersion];
            dataBits[codewordNumCounterValue] = (sbyte)(dataBits[codewordNumCounterValue] + codewordNumPlus[qrcodeVersion]);

            int[] maxCodewordsArray = new int[] { 0, 26, 44, 70, 100, 134, 172, 196, 242, 292, 346, 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085, 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185, 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706 };

            int maxCodewords    = maxCodewordsArray[qrcodeVersion];
            int maxModules1side = 17 + (qrcodeVersion << 2);

            int[] matrixRemainBit = new int[] { 0, 0, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0 };

            /* ---- read version ECC data file */

            int byte_num = matrixRemainBit[qrcodeVersion] + (maxCodewords << 3);

            sbyte[] matrixX             = new sbyte[byte_num];
            sbyte[] matrixY             = new sbyte[byte_num];
            sbyte[] maskArray           = new sbyte[byte_num];
            sbyte[] formatInformationX2 = new sbyte[15];
            sbyte[] formatInformationY2 = new sbyte[15];
            sbyte[] rsEccCodewords      = new sbyte[1];
            sbyte[] rsBlockOrderTemp    = new sbyte[128];

            try
            {
                //String filename = QRCODE_DATA_PATH + @"\qrv" + System.Convert.ToString(qrcodeVersion) + "_" + System.Convert.ToString(ec) + ".dat";
                //StreamReader reader = new StreamReader(filename);
                //BufferedStream bis = new BufferedStream(reader.BaseStream);

                String fileName = "qrv" + Convert.ToString(qrcodeVersion) + "_" + Convert.ToString(ec);
                UnmanagedMemoryStream memoryStream = Resources.ResourceManager.GetStream(fileName);
                BufferedStream        bis          = new BufferedStream(memoryStream);

                SystemUtils.ReadInput(bis, matrixX, 0, matrixX.Length);
                SystemUtils.ReadInput(bis, matrixY, 0, matrixY.Length);
                SystemUtils.ReadInput(bis, maskArray, 0, maskArray.Length);
                SystemUtils.ReadInput(bis, formatInformationX2, 0, formatInformationX2.Length);
                SystemUtils.ReadInput(bis, formatInformationY2, 0, formatInformationY2.Length);
                SystemUtils.ReadInput(bis, rsEccCodewords, 0, rsEccCodewords.Length);
                SystemUtils.ReadInput(bis, rsBlockOrderTemp, 0, rsBlockOrderTemp.Length);

                bis.Close();
                memoryStream.Close();

                // reader.Close();

                /*
                 * fis.Close();
                 */
            }
            catch (Exception e)
            {
                SystemUtils.WriteStackTrace(e, Console.Error);
            }

            sbyte rsBlockOrderLength = 1;

            for (sbyte i = 1; i < 128; i++)
            {
                if (rsBlockOrderTemp[i] == 0)
                {
                    rsBlockOrderLength = i;
                    break;
                }
            }
            sbyte[] rsBlockOrder = new sbyte[rsBlockOrderLength];
            Array.Copy(rsBlockOrderTemp, 0, rsBlockOrder, 0, (byte)rsBlockOrderLength);


            sbyte[] formatInformationX1 = new sbyte[] { 0, 1, 2, 3, 4, 5, 7, 8, 8, 8, 8, 8, 8, 8, 8 };
            sbyte[] formatInformationY1 = new sbyte[] { 8, 8, 8, 8, 8, 8, 8, 8, 7, 5, 4, 3, 2, 1, 0 };

            int maxDataCodewords = maxDataBits >> 3;

            /* -- read frame data  -- */

            int modules1Side    = 4 * qrcodeVersion + 17;
            int matrixTotalBits = modules1Side * modules1Side;

            sbyte[] frameData = new sbyte[matrixTotalBits + modules1Side];

            try
            {
                //String filename = QRCODE_DATA_PATH + "/qrvfr" + System.Convert.ToString(qrcodeVersion) + ".dat";
                //StreamReader reader = new StreamReader(filename);

                String fileName = "qrvfr" + Convert.ToString(qrcodeVersion);
                UnmanagedMemoryStream memoryStream = Resources.ResourceManager.GetStream(fileName);

                BufferedStream bis = new BufferedStream(memoryStream);
                SystemUtils.ReadInput(bis, frameData, 0, frameData.Length);
                bis.Close();
                memoryStream.Close();
                //reader.Close();
                //fis.Close();
            }
            catch (Exception e)
            {
                SystemUtils.WriteStackTrace(e, Console.Error);
            }

            /*  --- set terminator */

            if (totalDataBits <= maxDataBits - 4)
            {
                dataValue[dataCounter] = 0;
                dataBits[dataCounter]  = 4;
            }
            else
            {
                if (totalDataBits < maxDataBits)
                {
                    dataValue[dataCounter] = 0;
                    dataBits[dataCounter]  = (sbyte)(maxDataBits - totalDataBits);
                }
                else
                {
                    if (totalDataBits > maxDataBits)
                    {
                        System.Console.Out.WriteLine("overflow");
                    }
                }
            }
            sbyte[] dataCodewords = divideDataBy8Bits(dataValue, dataBits, maxDataCodewords);
            sbyte[] codewords     = calculateRSECC(dataCodewords, rsEccCodewords[0], rsBlockOrder, maxDataCodewords, maxCodewords);

            /* ---- flash matrix */

            sbyte[][] matrixContent = new sbyte[modules1Side][];
            for (int i2 = 0; i2 < modules1Side; i2++)
            {
                matrixContent[i2] = new sbyte[modules1Side];
            }

            for (int i = 0; i < modules1Side; i++)
            {
                for (int j = 0; j < modules1Side; j++)
                {
                    matrixContent[j][i] = 0;
                }
            }

            /* --- attach data */
            for (int i = 0; i < maxCodewords; i++)
            {
                sbyte codeword_i = codewords[i];
                for (int j = 7; j >= 0; j--)
                {
                    int codewordBitsNumber = (i * 8) + j;

                    matrixContent[matrixX[codewordBitsNumber] & 0xFF][matrixY[codewordBitsNumber] & 0xFF] = (sbyte)((255 * (codeword_i & 1)) ^ maskArray[codewordBitsNumber]);

                    codeword_i = (sbyte)(SystemUtils.URShift((codeword_i & 0xFF), 1));
                }
            }

            for (int matrixRemain = matrixRemainBit[qrcodeVersion]; matrixRemain > 0; matrixRemain--)
            {
                int remainBitTemp = matrixRemain + (maxCodewords * 8) - 1;
                matrixContent[matrixX[remainBitTemp] & 0xFF][matrixY[remainBitTemp] & 0xFF] = (sbyte)(255 ^ maskArray[remainBitTemp]);
            }

            /* --- mask select --- */
            sbyte maskNumber  = selectMask(matrixContent, matrixRemainBit[qrcodeVersion] + maxCodewords * 8);
            sbyte maskContent = (sbyte)(1 << maskNumber);

            /* --- format information --- */

            sbyte formatInformationValue = (sbyte)(ec << 3 | maskNumber);

            String[] formatInformationArray = new String[] { "101010000010010", "101000100100101", "101111001111100", "101101101001011", "100010111111001", "100000011001110", "100111110010111", "100101010100000", "111011111000100", "111001011110011", "111110110101010", "111100010011101", "110011000101111", "110001100011000", "110110001000001", "110100101110110", "001011010001001", "001001110111110", "001110011100111", "001100111010000", "000011101100010", "000001001010101", "000110100001100", "000100000111011", "011010101011111", "011000001101000", "011111100110001", "011101000000110", "010010010110100", "010000110000011", "010111011011010", "010101111101101" };

            for (int i = 0; i < 15; i++)
            {
                sbyte content = (sbyte)System.SByte.Parse(formatInformationArray[formatInformationValue].Substring(i, (i + 1) - (i)));

                matrixContent[formatInformationX1[i] & 0xFF][formatInformationY1[i] & 0xFF] = (sbyte)(content * 255);
                matrixContent[formatInformationX2[i] & 0xFF][formatInformationY2[i] & 0xFF] = (sbyte)(content * 255);
            }

            bool[][] out_Renamed = new bool[modules1Side][];
            for (int i3 = 0; i3 < modules1Side; i3++)
            {
                out_Renamed[i3] = new bool[modules1Side];
            }

            int c = 0;

            for (int i = 0; i < modules1Side; i++)
            {
                for (int j = 0; j < modules1Side; j++)
                {
                    if ((matrixContent[j][i] & maskContent) != 0 || frameData[c] == (char)49)
                    {
                        out_Renamed[j][i] = true;
                    }
                    else
                    {
                        out_Renamed[j][i] = false;
                    }
                    c++;
                }
                c++;
            }

            return(out_Renamed);
        }
Example #40
0
    unsafe public static void Main()
    {
        // foo_1
        {
            Console.WriteLine("call native: foo_1");
            foo_1();
            Console.WriteLine("================================");
        }

        // foo_2
        {
            Console.WriteLine("call native: foo_2");
            foo_2(123, "Hello World!");
            Console.WriteLine("================================");
        }

        // foo_3
        {
            Console.WriteLine("call native: foo_3");
            foo_3(new managed(){a=1,b=2,c=3});
            Console.WriteLine("================================");
        }

        // foo_4
        {
            Console.WriteLine("call native: foo_4");
            byte[] face = new byte[]
            {
                0x30,0x2e,0x30,
                0x20,0x2d,0x20,
            };

            IntPtr dataPtr = Marshal.AllocHGlobal(32);
            Marshal.Copy(face, 0, dataPtr, face.Length);

            foo_4(dataPtr, face.Length);

            Marshal.FreeHGlobal(dataPtr);
            Console.WriteLine("================================");
        }

        // foo_5
        {
            Console.WriteLine("call native: foo_5");
            IntPtr dataPtr;
            int length = 0;

            foo_5(out dataPtr, out length);

            byte[] face = new byte[length];
            Marshal.Copy(dataPtr, face, 0, length);

            for (int i=0; i<2; ++i)
            {
                for (int j=0; j<3; ++j)
                {
                    Console.Write((char)face[i*3+j]);
                    Console.Write(" ");
                }
                Console.Write("\n");
            }
            Console.WriteLine("================================");
        }

        // foo_6
        {
            Console.WriteLine("call native: foo_6");
            IntPtr dataPtr;
            int length = 0;

            foo_6(out dataPtr, out length);

            using (var stream = new UnmanagedMemoryStream((Byte*)dataPtr, length))
            {
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(stream);
                    Console.WriteLine(doc.InnerXml);
                }
                catch (System.Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            Console.WriteLine("================================");
        }

        int count = 1000000000;

        // empty
        {
            Console.WriteLine("call empty");
            DateTime t0 = DateTime.Now;
            for (int i=0; i<count; ++i)
            {

            }
            DateTime t1 = DateTime.Now;
            TimeSpan t = t1-t0;
            Console.WriteLine("count: " + count + ", time: " + t.TotalMilliseconds + " ms.");
            Console.WriteLine("================================");
        }

        // foo_7
        {
            Console.WriteLine("call native: foo_7");
            DateTime t0 = DateTime.Now;
            for (int i=0; i<count; ++i)
            {
                foo_7(i);
            }
            DateTime t1 = DateTime.Now;
            TimeSpan t = t1-t0;
            Console.WriteLine("count: " + count + ", time: " + t.TotalMilliseconds + " ms.");
            Console.WriteLine("================================");
        }

        // foo_8
        {
            Console.WriteLine("call native: foo_8");
            DateTime t0 = DateTime.Now;
            for (int i=0; i<count; ++i)
            {
                foo_8("Hello World!");
            }
            DateTime t1 = DateTime.Now;
            TimeSpan t = t1-t0;
            Console.WriteLine("count: " + count + ", time: " + t.TotalMilliseconds + " ms.");
            Console.WriteLine("================================");
        }

        // foo_9
        {
            Console.WriteLine("call native: foo_9");
            DateTime t0 = DateTime.Now;
            IntPtr dataPtr = Marshal.AllocHGlobal(32);
            int length = 32;
            for (int i=0; i<count; ++i)
            {
                foo_9(dataPtr, length);
            }
            DateTime t1 = DateTime.Now;
            TimeSpan t = t1-t0;
            Console.WriteLine("count: " + count + ", time: " + t.TotalMilliseconds + " ms.");
            Console.WriteLine("================================");
        }

        // foo_10
        {
            Console.WriteLine("call native: foo_10");
            DateTime t0 = DateTime.Now;
            IntPtr dataPtr;
            int length = 0;
            for (int i=0; i<count; ++i)
            {
                foo_10(out dataPtr, out length);

            }
            DateTime t1 = DateTime.Now;
            TimeSpan t = t1-t0;
            Console.WriteLine("count: " + count + ", time: " + t.TotalMilliseconds + " ms.");
            Console.WriteLine("================================");
        }
    }
Example #41
0
 public common(UnmanagedMemoryStream stream_, int offset_)
 {
     Data   = stream_;
     offset = offset_;
 }
Example #42
0
 internal static void UmsInvariants(UnmanagedMemoryStream stream)
 {
     Assert.False(stream.CanTimeout);
 }
Example #43
0
 public common(UnmanagedMemoryStream stream_)
 {
     Data   = stream_;
     offset = 0;
 }
Example #44
0
        // internal for testing
        internal static unsafe NativeHeapMemoryBlock DecodeEmbeddedPortablePdbDebugDirectoryData(AbstractMemoryBlock block)
        {
            NativeHeapMemoryBlock?decompressed;

            var headerReader = block.GetReader();

            if (headerReader.ReadUInt32() != PortablePdbVersions.DebugDirectoryEmbeddedSignature)
            {
                throw new BadImageFormatException(SR.UnexpectedEmbeddedPortablePdbDataSignature);
            }

            int decompressedSize = headerReader.ReadInt32();

            try
            {
                decompressed = new NativeHeapMemoryBlock(decompressedSize);
            }
            catch
            {
                throw new BadImageFormatException(SR.DataTooBig);
            }

            bool success = false;

            try
            {
                var compressed = new ReadOnlyUnmanagedMemoryStream(headerReader.CurrentPointer, headerReader.RemainingBytes);
                var deflate    = new DeflateStream(compressed, CompressionMode.Decompress, leaveOpen: true);

                if (decompressedSize > 0)
                {
                    int actualLength;

                    try
                    {
#if NETCOREAPP
                        actualLength = deflate.TryReadAll(new Span <byte>(decompressed.Pointer, decompressed.Size));
#else
                        using var decompressedStream = new UnmanagedMemoryStream(decompressed.Pointer, decompressed.Size, decompressed.Size, FileAccess.Write);
                        deflate.CopyTo(decompressedStream);
                        actualLength = (int)decompressedStream.Position;
#endif
                    }
                    catch (Exception e)
                    {
                        throw new BadImageFormatException(e.Message, e.InnerException);
                    }

                    if (actualLength != decompressed.Size)
                    {
                        throw new BadImageFormatException(SR.SizeMismatch);
                    }
                }

                // Check that there is no more compressed data left,
                // in case the decompressed size specified in the header is smaller
                // than the actual decompressed size of the data.
                if (deflate.ReadByte() != -1)
                {
                    throw new BadImageFormatException(SR.SizeMismatch);
                }

                success = true;
            }
            finally
            {
                if (!success)
                {
                    decompressed.Dispose();
                }
            }

            return(decompressed);
        }
 protected override void Write(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
 stream.Write(new Span <byte>(array, offset, count));
Example #46
0
        public static unsafe void ReadFromBufferBackedStream()
        {
            const int length = 8192;
            byte[] data = new byte[length];

            using (HGlobalSafeBuffer buffer = new HGlobalSafeBuffer(length))
            {
                for (ulong i = 0; i < length; i++)
                    buffer.Write(i, (byte)i);

                Action validateData = () => {
                    for (int i = 0; i < length; i++)
                        Assert.Equal((byte)i, data[i]);
                };

                using (var stream = new UnmanagedMemoryStream(buffer, 0, length, FileAccess.Read))
                {
                    stream.Position = 0;
                    Assert.Equal(length, stream.Read(data, 0, length));
                    validateData();
                    Array.Clear(data, 0, data.Length);

                    stream.Position = 0;
                    Assert.Equal(length / 2, stream.Read(data, 0, length / 2));
                    Assert.Equal(length / 2, stream.Read(data, length / 2, length / 2));
                    validateData();
                    Array.Clear(data, 0, data.Length);

                    Assert.True(stream.ReadAsync(data, 0, data.Length, new CancellationToken(true)).IsCanceled);

                    stream.Position = 0;
                    Task<int> t = stream.ReadAsync(data, 0, length / 4);
                    Assert.True(t.Status == TaskStatus.RanToCompletion);
                    Assert.Equal(length / 4, t.Result);
                    t = stream.ReadAsync(data, length / 4, length / 4);
                    Assert.True(t.Status == TaskStatus.RanToCompletion);
                    Assert.Equal(length / 4, t.Result);
                    t = stream.ReadAsync(data, length / 2, length / 2);
                    Assert.True(t.Status == TaskStatus.RanToCompletion);
                    Assert.Equal(length / 2, t.Result);
                    validateData();
                    Array.Clear(data, 0, data.Length);
                }
            }
        }
Example #47
0
        void SendEmbeddedResource(HttpContext context, out EmbeddedResource res, out Assembly assembly)
        {
            HttpRequest         request     = context.Request;
            NameValueCollection queryString = request.QueryString;

            // val is URL-encoded, which means every + has been replaced with ' ', we
            // need to revert that or the base64 conversion will fail.
            string d = queryString ["d"];

            if (!String.IsNullOrEmpty(d))
            {
                d = d.Replace(' ', '+');
            }

            AssemblyEmbeddedResources entry;

            res = DecryptAssemblyResource(d, out entry);
            WebResourceAttribute wra = res != null ? res.Attribute : null;

            if (wra == null)
            {
                throw new HttpException(404, "Resource not found");
            }

            if (entry.AssemblyName == "s")
            {
                assembly = currAsm;
            }
            else
            {
                assembly = Assembly.Load(entry.AssemblyName);
            }

            long atime;

            if (HasCacheControl(request, queryString, out atime))
            {
                if (atime == File.GetLastWriteTimeUtc(assembly.Location).Ticks)
                {
                    RespondWithNotModified(context);
                    return;
                }
            }

            DateTime modified;

            if (HasIfModifiedSince(request, out modified))
            {
                if (File.GetLastWriteTimeUtc(assembly.Location) <= modified)
                {
                    RespondWithNotModified(context);
                    return;
                }
            }

            HttpResponse response = context.Response;

            response.ContentType = wra.ContentType;

            DateTime utcnow = DateTime.UtcNow;

            response.Headers.Add("Last-Modified", utcnow.ToString("r"));
            response.ExpiresAbsolute = utcnow.AddYears(1);
            response.CacheControl    = "public";

            Stream s = assembly.GetManifestResourceStream(res.Name);

            if (s == null)
            {
                throw new HttpException(404, "Resource " + res.Name + " not found");
            }

            if (wra.PerformSubstitution)
            {
                using (StreamReader r = new StreamReader(s)) {
                    TextWriter w = response.Output;
                    new PerformSubstitutionHelper(assembly).PerformSubstitution(r, w);
                }
            }
            else if (response.OutputStream is HttpResponseStream)
            {
                UnmanagedMemoryStream st      = (UnmanagedMemoryStream)s;
                HttpResponseStream    hstream = (HttpResponseStream)response.OutputStream;
                unsafe {
                    hstream.WritePtr(new IntPtr(st.PositionPointer), (int)st.Length);
                }
            }
            else
            {
                byte [] buf    = new byte [1024];
                Stream  output = response.OutputStream;
                int     c;
                do
                {
                    c = s.Read(buf, 0, 1024);
                    output.Write(buf, 0, c);
                } while (c > 0);
            }
        }
Example #48
0
 public Sound(UnmanagedMemoryStream AudioClip, double Vol)
 {
     Player = new SoundPlayer(AudioClip);
     Player.LoadAsync();
     SetVolume(Vol);
 }
 public RuntimeResourceSet(UnmanagedMemoryStream stream) : base(stream)
 {
 }
Example #50
0
        public static void WriteSafeBuffer()
        {
            const int length = 1000;
            using (var buffer = new TestSafeBuffer(length))
            {
                var stream = new UnmanagedMemoryStream(buffer, 0, (long)buffer.ByteLength, FileAccess.Write);
                Assert.Equal(stream.Length, length);

                var bytes = ArrayHelpers.CreateByteArray(length);
                var copy = bytes.Copy();
                stream.Write(copy, 0, length);

                var memory = buffer.ToArray();

                Assert.Equal(bytes, memory, ArrayHelpers.Comparer<byte>());

                stream.Write(new byte[0], 0, 0);
            }
        }
Example #51
0
 public void StartGame(UnmanagedMemoryStream soundResId)
 {
     // retrieve .wav from resource file.
     sp = new SoundPlayer(soundResId);
     sp.Play();
 }