Beispiel #1
0
 private static uint FindEntryPoint(IntPtr hProcess, IntPtr hModule)
 {
     if (hProcess.IsNull() || hProcess.Compare(-1L))
     {
         throw new ArgumentException("Invalid process handle.", "hProcess");
     }
     if (hModule.IsNull())
     {
         throw new ArgumentException("Invalid module handle.", "hModule");
     }
     byte[] array = WinAPI.ReadRemoteMemory(hProcess, hModule, (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
     if (array != null)
     {
         ushort num  = BitConverter.ToUInt16(array, 0);
         uint   num2 = BitConverter.ToUInt32(array, 60);
         if (num == 23117)
         {
             byte[] array2 = WinAPI.ReadRemoteMemory(hProcess, hModule.Add((long)((ulong)num2)), (uint)Marshal.SizeOf(typeof(IMAGE_NT_HEADER32)));
             if (array2 != null && BitConverter.ToUInt32(array2, 0) == 17744u)
             {
                 IMAGE_NT_HEADER32 iMAGE_NT_HEADER = default(IMAGE_NT_HEADER32);
                 using (UnmanagedBuffer unmanagedBuffer = new UnmanagedBuffer(256))
                 {
                     if (unmanagedBuffer.Translate <IMAGE_NT_HEADER32>(array2, out iMAGE_NT_HEADER))
                     {
                         return(iMAGE_NT_HEADER.OptionalHeader.AddressOfEntryPoint);
                     }
                 }
                 return(0u);
             }
         }
     }
     return(0u);
 }
Beispiel #2
0
        /**
         * Find the entry point of a loaded module
         * based on its Base Address. Reverses the PE
         * structure to find the entry point
         */
        private static uint FindEntryPoint(IntPtr hProcess, IntPtr hModule)
        {
            if (hProcess.IsNull() || hProcess.Compare(-1))
            {
                throw new ArgumentException("Invalid process handle.", "hProcess");
            }
            if (hModule.IsNull())
            {
                throw new ArgumentException("Invalid module handle.", "hModule");
            }

            byte[] bDosHeader = WinAPI.ReadRemoteMemory(hProcess, hModule, (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
            if (bDosHeader != null)
            {
                ushort e_magic  = BitConverter.ToUInt16(bDosHeader, 0);
                uint   e_lfanew = BitConverter.ToUInt32(bDosHeader, 0x3C);
                if (e_magic == 23117)
                {
                    byte[] bNtHeader = WinAPI.ReadRemoteMemory(hProcess, hModule.Add(e_lfanew), (uint)Marshal.SizeOf(typeof(IMAGE_NT_HEADER32)));
                    if (bNtHeader != null && BitConverter.ToUInt32(bNtHeader, 0) == 17744)
                    {
                        IMAGE_NT_HEADER32 ntHd = default(IMAGE_NT_HEADER32);
                        using (var buffer = new UnmanagedBuffer(256))
                            if (buffer.Translate <IMAGE_NT_HEADER32>(bNtHeader, out ntHd))
                            {
                                return(ntHd.OptionalHeader.AddressOfEntryPoint);
                            }
                    }
                }
            }
            return(0);
        }
Beispiel #3
0
        private void btnDisAsm_Click(object sender, EventArgs e)
        {
            rtbHexDump.Clear();

            //Console.WriteLine("Version: " + BeaEngine.Version);
            //Console.WriteLine("Revision: " + BeaEngine.Revision);

            //UnmanagedBuffer buffer = new UnmanagedBuffer(File.ReadAllBytes("BeaEngine.dll"));

            uint address  = Convert.ToUInt32(tbOffsetToWatch.Text, 16);
            uint naddress = address + (uint)baseAddressModule;

            UnmanagedBuffer buffer = new UnmanagedBuffer(procTools.Memory.ReadBytes(naddress, 1120));

            var disasm = new Disasm();

            //disasm.EIP = new IntPtr(buffer.Ptr.ToInt64() + 0x400);
            disasm.EIP = new IntPtr(buffer.Ptr.ToInt64());

            for (int counter = 0; counter < 100; ++counter)
            {
                int result = BeaEngine.Disasm(disasm);

                if (result == (int)BeaConstants.SpecialInfo.UNKNOWN_OPCODE)
                {
                    break;
                }

                //rtbHexDump.AppendText("0x" + disasm.EIP.ToString("X") + " " + disasm.CompleteInstr+"\r\n");
                rtbHexDump.AppendText("0x" + address.ToString("X") + "\t" + disasm.CompleteInstr + "\r\n");
                disasm.EIP = new IntPtr(disasm.EIP.ToInt64() + result);
                address   += (uint)result;
            }
        }
Beispiel #4
0
            static void RunTest(string testTypeName, string throwExceptionStr)
            {
                bool throwExceptionInner = bool.Parse(throwExceptionStr);
                var  buffer = UnmanagedBuffer <L8> .Allocate(100);

                var allocator = new MockUnmanagedMemoryAllocator <L8>(buffer);

                Configuration.Default.MemoryAllocator = allocator;

                var image = new Image <L8>(10, 10);

                Assert.Equal(1, UnmanagedMemoryHandle.TotalOutstandingHandles);
                try
                {
                    GetTest(testTypeName).ProcessPixelRowsImpl(image, _ =>
                    {
                        ((IDisposable)buffer).Dispose();
                        Assert.Equal(1, UnmanagedMemoryHandle.TotalOutstandingHandles);
                        if (throwExceptionInner)
                        {
                            throw new NonFatalException();
                        }
                    });
                }
                catch (NonFatalException)
                {
                }

                Assert.Equal(0, UnmanagedMemoryHandle.TotalOutstandingHandles);
            }
Beispiel #5
0
 internal static object MarshalFromUnmanaged(uint tomarshal, UnmanagedType type, uint sizeconst, Type knowntype)
 {
     if (type == UnmanagedType.Interface)
     {
         if (knowntype == typeof(UnmanagedBuffer))
         {
             return((object)new UnmanagedBuffer((IntPtr)tomarshal));
         }
         else
         {
             return(UnmanagedObject.Create(knowntype, (IntPtr)tomarshal));
         }
     }
     else if (type == UnmanagedType.LPStruct)
     {
         UnmanagedBuffer buff = new UnmanagedBuffer((IntPtr)tomarshal);
         return(buff.ReadAt(0, knowntype));
     }
     else if (type == UnmanagedType.LPWStr)
     {
         UnmanagedBuffer buff = new UnmanagedBuffer((IntPtr)tomarshal);
         return((object)buff.ReadUnicodeStringAt(0));
     }
     else if (type == UnmanagedType.LPStr)
     {
         UnmanagedBuffer buff = new UnmanagedBuffer((IntPtr)tomarshal);
         return((object)buff.ReadStringAt(0));
     }
     else
     {
         return((object)tomarshal);
     }
 }
Beispiel #6
0
        public void RefCountedTest()
        {
            var sharedPool = new SharedPool <UnmanagedBuffer>(() => UnmanagedBuffer.Allocate(100), 1);
            var shared     = sharedPool.GetOrCreate(); // refcount = 1

            // a private copy shoudl point to the same resource
            var otherShared = shared.DeepClone(); // refcount = 1 + 1

            Assert.AreNotEqual(shared, otherShared);
            Assert.AreEqual(shared.Inner, otherShared.Inner);
            Assert.AreEqual(shared.Resource, otherShared.Resource);

            // a clone should point to the same resource, but should not reuse the container
            var cloned = otherShared;

            Serializer.Clone(shared, ref cloned, new SerializationContext()); // refcount = 2 - 1 + 1
            Assert.AreNotEqual(shared, cloned);
            Assert.AreEqual(shared.Inner, cloned.Inner);
            Assert.AreEqual(shared.Resource, cloned.Resource);

            // disposing should not affect other copies
            shared.Dispose(); // refcount = 2 - 1
            Assert.AreEqual(0, sharedPool.AvailableCount);
            Assert.IsNull(shared.Inner);
            Assert.IsNull(shared.Resource);
            Assert.IsNotNull(cloned.Inner);
            Assert.IsNotNull(cloned.Resource);

            // disposing the last copy should return the resource to the pool
            cloned.Dispose(); // refcount = 1 - 1
            Assert.AreEqual(1, sharedPool.AvailableCount);
            Assert.IsNull(cloned.Inner);
            Assert.IsNull(cloned.Resource);
        }
        /// <inheritdoc />
        internal override MemoryGroup <T> AllocateGroup <T>(
            long totalLength,
            int bufferAlignment,
            AllocationOptions options = AllocationOptions.None)
        {
            long totalLengthInBytes = totalLength * Unsafe.SizeOf <T>();

            if (totalLengthInBytes <= this.sharedArrayPoolThresholdInBytes)
            {
                var buffer = new SharedArrayPoolBuffer <T>((int)totalLength);
                return(MemoryGroup <T> .CreateContiguous(buffer, options.Has(AllocationOptions.Clean)));
            }

            if (totalLengthInBytes <= this.poolBufferSizeInBytes)
            {
                // Optimized path renting single array from the pool
                UnmanagedMemoryHandle mem = this.pool.Rent();
                if (mem.IsValid)
                {
                    UnmanagedBuffer <T> buffer = this.pool.CreateGuardedBuffer <T>(mem, (int)totalLength, options.Has(AllocationOptions.Clean));
                    return(MemoryGroup <T> .CreateContiguous(buffer, options.Has(AllocationOptions.Clean)));
                }
            }

            // Attempt to rent the whole group from the pool, allocate a group of unmanaged buffers if the attempt fails:
            if (MemoryGroup <T> .TryAllocate(this.pool, totalLength, bufferAlignment, options, out MemoryGroup <T> poolGroup))
            {
                return(poolGroup);
            }

            return(MemoryGroup <T> .Allocate(this.nonPoolAllocator, totalLength, bufferAlignment, options));
        }
        private void ThreadTest()
        {
            this.isRunning = true;


            var i2cController = I2cController.FromName(SC20260.I2cBus.I2c1);

            try {
                var ov9655 = new Ov9655Controller(i2cController);

read_id:
                try {
                    var id = ov9655.ReadId();
                }
                catch {
                    goto read_id;
                }

                byte[]          data           = null;
                UnmanagedBuffer unmangedBuffer = null;

                if (Memory.UnmanagedMemory.FreeBytes != 0)
                {
                    unmangedBuffer = new UnmanagedBuffer(640 * 480 * 2);
                    data           = unmangedBuffer.Bytes;
                }
                else
                {
                    data = new byte[640 * 480 * 2];
                }

                ov9655.SetResolution(Ov9655Controller.Resolution.Vga);
                var displayController = Display.DisplayController;

                while (this.isRunning)
                {
                    try {
                        ov9655.Capture(data, 500);

                        displayController.DrawBuffer(0, this.TopBar.ActualHeight, 0, 0, 480, 272 - this.TopBar.ActualHeight, 640, data, 0);
                    }
                    catch {
                    }

                    Thread.Sleep(10);
                }

                if (unmangedBuffer != null)
                {
                    unmangedBuffer.Dispose();
                }
            }
            catch {
            }


            this.isRunning = false;

            return;
        }
        /// <inheritdoc />
        public override IMemoryOwner <T> Allocate <T>(
            int length,
            AllocationOptions options = AllocationOptions.None)
        {
            Guard.MustBeGreaterThanOrEqualTo(length, 0, nameof(length));
            int lengthInBytes = length * Unsafe.SizeOf <T>();

            if (lengthInBytes <= this.sharedArrayPoolThresholdInBytes)
            {
                var buffer = new SharedArrayPoolBuffer <T>(length);
                if (options.Has(AllocationOptions.Clean))
                {
                    buffer.GetSpan().Clear();
                }

                return(buffer);
            }

            if (lengthInBytes <= this.poolBufferSizeInBytes)
            {
                UnmanagedMemoryHandle mem = this.pool.Rent();
                if (mem.IsValid)
                {
                    UnmanagedBuffer <T> buffer = this.pool.CreateGuardedBuffer <T>(mem, length, options.Has(AllocationOptions.Clean));
                    return(buffer);
                }
            }

            return(this.nonPoolAllocator.Allocate <T>(length, options));
        }
Beispiel #10
0
        /// <summary>
        /// Create unmanaged image from the specified managed image.
        /// </summary>
        /// <param name="imageData">Source locked image data.</param>
        /// <returns>Returns new unmanaged image, which is a copy of source managed image.</returns>
        /// <remarks><para>The method creates an exact copy of specified managed image, but allocated
        /// in unmanaged memory. This means that managed image may be unlocked right after call to this
        /// method.</para></remarks>
        public static Image FromManagedImage(BitmapData imageData)
        {
            PixelFormat pixelFormat = PixelFormatHelper.FromSystemPixelFormat(imageData.PixelFormat);

            // allocate memory for the image
            return(new Image(UnmanagedBuffer.CreateCopyFrom(imageData.Scan0, imageData.Stride * imageData.Height), imageData.Width, imageData.Height, imageData.Stride, pixelFormat));
        }
Beispiel #11
0
        /// <summary>
        /// Disassembles the given code
        /// </summary>
        /// <param name="generatedCode">The generated code</param>
        public string Disassemble(IList <byte> generatedCode)
        {
            var output = new StringBuilder();
            var buffer = new UnmanagedBuffer(generatedCode.ToArray());

            var disasm = new Disasm()
            {
                Archi = 64
            };

            int offset = 0;

            while (offset < generatedCode.Count)
            {
                disasm.EIP = new IntPtr(buffer.Ptr.ToInt64() + offset);
                int result = BeaEngine64.Disasm(disasm);

                if (result == (int)BeaConstants.SpecialInfo.UNKNOWN_OPCODE)
                {
                    break;
                }

                //strBuffer.AppendLine("0x" + offset.ToString("X") + " " + disasm.CompleteInstr);
                output.AppendLine(disasm.CompleteInstr);
                offset += result;
            }

            return(output.ToString());
        }
        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        private void EnsureCapacity(int capacity)
        {
            // Make sure the requested capacity doesn't exceed SecureString's defined limit
            if (capacity > MaxLength)
            {
                throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
            }

            // If we already have enough space allocated, we're done
            if (_buffer != null && (capacity * sizeof(char)) <= (int)_buffer.ByteLength)
            {
                return;
            }

            // We need more space, so allocate a new buffer, copy all our data into it,
            // and then swap the new for the old.
            UnmanagedBuffer newBuffer = UnmanagedBuffer.Allocate(capacity * sizeof(char));

            if (_buffer != null)
            {
                UnmanagedBuffer.Copy(_buffer, newBuffer, _buffer.ByteLength);
                _buffer.Dispose();
            }
            _buffer = newBuffer;
        }
 private static uint FindEntryPoint(IntPtr hProcess, IntPtr hModule)
 {
     if (hProcess.IsNull() || hProcess.Compare(-1L))
     {
         throw new ArgumentException("Invalid process handle.", "hProcess");
     }
     if (hModule.IsNull())
     {
         throw new ArgumentException("Invalid module handle.", "hModule");
     }
     byte[] buffer = WinAPI.ReadRemoteMemory(hProcess, hModule, (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
     if (buffer != null)
     {
         ushort num  = BitConverter.ToUInt16(buffer, 0);
         uint   num2 = BitConverter.ToUInt32(buffer, 60);
         if (num == 0x5a4d)
         {
             byte[] buffer2 = WinAPI.ReadRemoteMemory(hProcess, hModule.Add((long)num2), (uint)Marshal.SizeOf(typeof(IMAGE_NT_HEADER32)));
             if ((buffer2 != null) && (BitConverter.ToUInt32(buffer2, 0) == 0x4550))
             {
                 IMAGE_NT_HEADER32 result = new IMAGE_NT_HEADER32();
                 using (UnmanagedBuffer buffer3 = new UnmanagedBuffer(0x100))
                 {
                     if (buffer3.Translate <IMAGE_NT_HEADER32>(buffer2, out result))
                     {
                         return(result.OptionalHeader.AddressOfEntryPoint);
                     }
                 }
             }
         }
     }
     return(0);
 }
            internal static unsafe void Copy(UnmanagedBuffer source, UnmanagedBuffer destination, ulong bytesLength)
            {
                if (bytesLength == 0)
                {
                    return;
                }

                byte *srcPtr = null, dstPtr = null;

                try
                {
                    source.AcquirePointer(ref srcPtr);
                    destination.AcquirePointer(ref dstPtr);
                    Buffer.MemoryCopy(srcPtr, dstPtr, destination.ByteLength, bytesLength);
                }
                finally
                {
                    if (dstPtr != null)
                    {
                        destination.ReleasePointer();
                    }
                    if (srcPtr != null)
                    {
                        source.ReleasePointer();
                    }
                }
            }
        /// <summary>
        /// Disassembles the given code
        /// </summary>
        /// <param name="generatedCode">The generated code</param>
        public static string Disassemble(IList<byte> generatedCode)
        {
            var strBuffer = new StringBuilder();
            var buffer = new UnmanagedBuffer(generatedCode.ToArray());

            var disasm = new Disasm();
            disasm.Archi = 64;

            int offset = 0;
            while (offset < generatedCode.Count)
            {
                disasm.EIP = new IntPtr(buffer.Ptr.ToInt64() + offset);
                int result = BeaEngine64.Disasm(disasm);

                if (result == (int)BeaConstants.SpecialInfo.UNKNOWN_OPCODE)
                {
                    break;
                }

                //strBuffer.AppendLine("0x" + offset.ToString("X") + " " + disasm.CompleteInstr);
                strBuffer.AppendLine(disasm.CompleteInstr);
                offset += result;
            }

            return strBuffer.ToString();
        }
        public static T ReadEnumAttribute <T>(hid_t hid, string key) where T : struct, IConvertible
        {
            var attribute = H5A.open(hid, key);

            if (attribute < 0)
            {
                throw new ArgumentException(string.Format("Attribute {0} not found.", key));
            }

            var type = H5A.get_type(attribute);

            if (type < 0)
            {
                H5A.close(attribute);
                throw new Exception("H5A.get_type failed.");
            }

            var size = H5T.get_size(type).ToInt32();

            if (size == 0)
            {
                H5T.close(type);
                H5A.close(attribute);
                throw new Exception("H5T.get_size failed.");
            }

            var unmanagedBuffer = new UnmanagedBuffer(size);

            H5A.read(attribute, type, unmanagedBuffer);

            H5T.close(type);
            H5A.close(attribute);

            return(unmanagedBuffer.ReadEnum <T>());
        }
Beispiel #17
0
        //static constructor: inject code required to perform the call once
        static UnmanagedCall()
        {
            uint loopaddress;
            uint code_alignment;

            uint pAddress;
            uint pStacksize;
            uint ppStack;
            uint pThisPar;
            uint pRetVal;
            uint pStackPointerBackup;

            AsmBuilder asm = new AsmBuilder();

            //should use our own heap, not the default heap; since the code buffer needs execution rights
            m_Parameters = Allocator.AllocateBuffer(7 * 4);
            m_Code       = Allocator.AllocateBuffer(61);

            data_alignment = ((uint)m_Parameters.Address) % 4;
            code_alignment = ((uint)m_Code.Address) % 4;

            pAddress            = (uint)m_Parameters.Address + data_alignment + 4 * 0;
            pStacksize          = (uint)m_Parameters.Address + data_alignment + 4 * 1;
            ppStack             = (uint)m_Parameters.Address + data_alignment + 4 * 2;
            pThisPar            = (uint)m_Parameters.Address + data_alignment + 4 * 3;
            pRetVal             = (uint)m_Parameters.Address + data_alignment + 4 * 4;
            pStackPointerBackup = (uint)m_Parameters.Address + data_alignment + 4 * 5;

            //backup context
            asm.Instructions.Add(new PushAll());
            asm.Instructions.Add(new BackupEsp(pStackPointerBackup));
            //build stack
            asm.Instructions.Add(new MovEcxMemory(pStacksize));
            asm.Instructions.Add(new MovEdxMemory(ppStack));
            //store current position for the stack push loop
            loopaddress = code_alignment + (uint)asm.Size;    //relative
            //build stack builder loop
            asm.Instructions.Add(new MovEaxEdx());
            asm.Instructions.Add(new DereferEax());
            asm.Instructions.Add(new PushEax());
            asm.Instructions.Add(new AddEdx(4));
            asm.Instructions.Add(new DecEcx());
            asm.Instructions.Add(new JnzRelativeShort((int)loopaddress));
            //build call
            asm.Instructions.Add(new MovEcxMemory(pThisPar));
            asm.Instructions.Add(new CallFunctionPointer(pAddress));
            //store return value
            asm.Instructions.Add(new MovMemoryEax(pRetVal));
            //restore context
            asm.Instructions.Add(new RestoreEsp(pStackPointerBackup));
            asm.Instructions.Add(new PopAll());
            //return
            asm.Instructions.Add(new Rtn());

            //write code
            asm.Write(m_Code, (int)code_alignment);

            //build function pointer
            m_Call = (SimpleCallDelegate)Marshal.GetDelegateForFunctionPointer((IntPtr)((uint)m_Code.Address + code_alignment), typeof(SimpleCallDelegate));
        }
Beispiel #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Image"/> class.
 /// </summary>
 /// <param name="imageData">Pointer to image data in unmanaged memory.</param>
 /// <param name="width">Image width in pixels.</param>
 /// <param name="height">Image height in pixels.</param>
 /// <param name="stride">Image stride (line size in bytes).</param>
 /// <param name="pixelFormat">Image pixel format.</param>
 /// <remarks><para><note>Using this constructor, make sure all specified image attributes are correct
 /// and correspond to unmanaged memory buffer. If some attributes are specified incorrectly,
 /// this may lead to exceptions working with the unmanaged memory.</note></para></remarks>
 public Image(IntPtr imageData, int width, int height, int stride, PixelFormat pixelFormat)
 {
     this.image       = UnmanagedBuffer.WrapIntPtr(imageData, height * stride);
     this.width       = width;
     this.height      = height;
     this.stride      = stride;
     this.pixelFormat = pixelFormat;
 }
Beispiel #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Image"/> class.
 /// </summary>
 /// <param name="image">The unmanaged array containing the image.</param>
 /// <param name="width">Image width in pixels.</param>
 /// <param name="height">Image height in pixels.</param>
 /// <param name="stride">Image stride (line size in bytes).</param>
 /// <param name="pixelFormat">Image pixel format.</param>
 /// <remarks><para><note>Using this constructor, make sure all specified image attributes are correct
 /// and correspond to unmanaged memory buffer. If some attributes are specified incorrectly,
 /// this may lead to exceptions working with the unmanaged memory.</note></para></remarks>
 public Image(UnmanagedBuffer image, int width, int height, int stride, PixelFormat pixelFormat)
 {
     this.image       = image;
     this.width       = width;
     this.height      = height;
     this.stride      = stride;
     this.pixelFormat = pixelFormat;
 }
 public void CopyToValidation3()
 {
     using (UnmanagedBuffer source = GetBuffer(BUFFER_SIZE, false),
            target = GetBuffer(BUFFER_SIZE, false))
     {
         source.CopyTo(target);
     }
 }
 private void DisposeCore()
 {
     if (_buffer != null && !_buffer.IsInvalid)
     {
         _buffer.Dispose();
         _buffer = null;
     }
 }
 private void DisposeCore()
 {
     if (_buffer != null && !_buffer.IsInvalid)
     {
         _buffer.Dispose();
         _buffer = null;
     }
 }
Beispiel #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Image"/> class.
 /// </summary>
 /// <param name="bitmapData">Locked bitmap data.</param>
 /// <remarks><note>Unlike <see cref="FromManagedImage(BitmapData)"/> method, this constructor does not make
 /// copy of managed image. This means that managed image must stay locked for the time of using the instance
 /// of unamanged image.</note></remarks>
 public Image(BitmapData bitmapData)
 {
     this.image       = UnmanagedBuffer.WrapIntPtr(bitmapData.Scan0, bitmapData.Height * bitmapData.Stride);
     this.width       = bitmapData.Width;
     this.height      = bitmapData.Height;
     this.stride      = bitmapData.Stride;
     this.pixelFormat = PixelFormatHelper.FromSystemPixelFormat(bitmapData.PixelFormat);
 }
 public void CopyValidateSize3()
 {
     using (UnmanagedBuffer source = GetBuffer(BUFFER_SIZE, true),
            target = GetBuffer(BUFFER_SIZE, true))
     {
         source.CopyTo(target, BUFFER_SIZE * 2);
     }
 }
        /// <summary>
        /// Creates a new disassembler
        /// </summary>
        /// <param name="compilationData">The compilation data</param>
        public Disassembler(AbstractCompilationData compilationData)
        {
            this.compilationData = compilationData;

            this.codeBuffer = new UnmanagedBuffer(compilationData.Function.GeneratedCode.ToArray());
            this.disassembler = new Disasm();
            this.disassembler.Archi = 64;
            this.disassembler.EIP = new IntPtr(this.codeBuffer.Ptr.ToInt64());
        }
            internal static UnmanagedBuffer Allocate(int bytes)
            {
                Debug.Assert(bytes >= 0);
                UnmanagedBuffer buffer = new UnmanagedBuffer();

                buffer.SetHandle(Marshal.AllocHGlobal(bytes));
                buffer.Initialize((ulong)bytes);
                return(buffer);
            }
Beispiel #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageBase"/> class.
 /// </summary>
 /// <param name="bitmapData">Locked bitmap data.</param>
 /// <param name="makeCopy">Indicates whether a copy is made (default is false).</param>
 /// <remarks>
 /// <para>When the <paramref name="makeCopy"/> parameter is false (default), the image simply wraps
 /// the bitmap data. As such, the bitmap data must stay locked for the duration of using the <see cref="ImageBase"/> object.
 /// </para>
 /// <para>If the <paramref name="makeCopy"/> parameter is set to true, a copy of the bitmap
 /// data is made, and the bitmap data can be released right after the <see cref="ImageBase"/> has been constructed.
 /// </para>
 /// </remarks>
 public ImageBase(BitmapData bitmapData, bool makeCopy = false)
 {
     this.image = makeCopy ?
                  UnmanagedBuffer.CreateCopyFrom(bitmapData.Scan0, bitmapData.Stride * bitmapData.Height) :
                  UnmanagedBuffer.WrapIntPtr(bitmapData.Scan0, bitmapData.Height * bitmapData.Stride);
     this.width       = bitmapData.Width;
     this.height      = bitmapData.Height;
     this.stride      = bitmapData.Stride;
     this.pixelFormat = PixelFormatHelper.FromSystemPixelFormat(bitmapData.PixelFormat);
 }
Beispiel #28
0
#pragma warning restore CA1419

            public static UnmanagedBuffer Allocate(int byteLength)
            {
                Debug.Assert(byteLength >= 0);
                UnmanagedBuffer buffer = new UnmanagedBuffer();

                buffer.SetHandle(Marshal.AllocHGlobal(byteLength));
                buffer.Initialize((ulong)byteLength);
                buffer._byteLength = byteLength;
                return(buffer);
            }
Beispiel #29
0
        public void Allocate_CreatesValidBuffer()
        {
            using var buffer = UnmanagedBuffer <int> .Allocate(10);

            Span <int> span = buffer.GetSpan();

            Assert.Equal(10, span.Length);
            span[9] = 123;
            Assert.Equal(123, span[9]);
        }
Beispiel #30
0
        /// <summary>
        /// Creates a new disassembler
        /// </summary>
        /// <param name="compilationData">The compilation data</param>
        public Disassembler(AbstractCompilationData compilationData)
        {
            this.compilationData = compilationData;

            this.codeBuffer   = new UnmanagedBuffer(compilationData.Function.GeneratedCode.ToArray());
            this.disassembler = new Disasm()
            {
                Archi = 64,
                EIP   = new IntPtr(this.codeBuffer.Ptr.ToInt64())
            };
        }
Beispiel #31
0
        private Geobase(UnmanagedBuffer buffer)
        {
            _buffer = buffer;

            var cityIndexData = GeobaseIndexData <GLocation> .Create(Header.Records, GetCityLocationIndex, GetLocation);

            CityIndex = new GeobaseIndex <string, GLocation>(cityIndexData, new GCityComparer());

            var ipIntervalIndexData = GeobaseIndexData <GIpInterval> .Create(Header.Records, idx => idx, GetIpInterval);

            IpIntervalIndex = new GeobaseIndex <string, GIpInterval>(ipIntervalIndexData, new GIpComparer());
        }
        internal SecureString(SecureString str)
        {
            // Allocate enough space to store the provided string
            EnsureCapacity(str._decryptedLength);
            _decryptedLength = str._decryptedLength;

            // Copy the string into the newly allocated space
            if (_decryptedLength > 0)
            {
                UnmanagedBuffer.Copy(str._buffer, _buffer, (ulong)(str._decryptedLength * sizeof(char)));
            }
        }
Beispiel #33
0
        private SecureString(SecureString str)
        {
            Debug.Assert(str._buffer != null, "Expected other SecureString's buffer to be non-null");
            Debug.Assert(str._encrypted, "Expected to be used only on encrypted SecureStrings");

            _buffer = UnmanagedBuffer.Allocate((int)str._buffer.ByteLength);
            Debug.Assert(_buffer != null);
            UnmanagedBuffer.Copy(str._buffer, _buffer, str._buffer.ByteLength);

            _decryptedLength = str._decryptedLength;
            _encrypted       = str._encrypted;
        }
 internal SmtpSession(TcpClient client, UnmanagedBuffer buffer)
 {
     m_client = client;
     m_buffer = buffer;
 }
        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        private void EnsureCapacity(int capacity)
        {
            // Make sure the requested capacity doesn't exceed SecureString's defined limit
            if (capacity > MaxLength)
            {
                throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
            }

            // If we already have enough space allocated, we're done
            if (_buffer != null && (capacity * sizeof(char)) <= (int)_buffer.ByteLength)
            {
                return;
            }

            // We need more space, so allocate a new buffer, copy all our data into it,
            // and then swap the new for the old.
            UnmanagedBuffer newBuffer = UnmanagedBuffer.Allocate(capacity * sizeof(char));
            if (_buffer != null)
            {
                UnmanagedBuffer.Copy(_buffer, newBuffer, _buffer.ByteLength);
                _buffer.Dispose();
            }
            _buffer = newBuffer;
        }
Beispiel #36
0
    private unsafe void ReadFileIntoUnmanagedBuffer(System.IO.FileStream/*!*/ inputStream) {
      long size = inputStream.Seek(0, System.IO.SeekOrigin.End);
      if (size > int.MaxValue) throw new System.IO.FileLoadException();
      inputStream.Seek(0, System.IO.SeekOrigin.Begin);
      int n = (int)size;
      this.bufferLength = n;
      this.unmanagedBuffer = new UnmanagedBuffer(n);
      byte* pb = (byte*)this.unmanagedBuffer.Pointer;
#if !ROTOR
#if WHIDBEY && !OldWhidbey
      if (!Reader.ReadFile(inputStream.SafeFileHandle.DangerousGetHandle(), pb, n, &n, IntPtr.Zero)) throw new System.IO.FileLoadException();
#else
      if (!Reader.ReadFile(inputStream.Handle, pb, n, &n, IntPtr.Zero)) throw new System.IO.FileLoadException();
#endif
#else
      //Read a fixed length block at a time, so that the GC does not come under pressure from lots of large byte arrays.
      int bufferLen = 8096;
      byte[] buffer = new byte[bufferLen];
      while (n > 0){
        if (n < bufferLen) bufferLen = n;
        inputStream.Read(buffer, 0, bufferLen);
        for (int i = 0; i < bufferLen; i++) *pb++ = buffer[i];
        n -= bufferLen;
      }
#endif
    }
Beispiel #37
0
    public void Dispose(){
      if (this.unmanagedBuffer != null)
        this.unmanagedBuffer.Dispose();
      this.unmanagedBuffer = null;
      if (this.tables != null)
        this.tables.Dispose();
      //this.tables = null;
#if !ROTOR && !UseSingularityPDB
      if (this.debugReader != null)
        Marshal.ReleaseComObject(this.debugReader);
      this.debugReader = null;
#endif
    }
Beispiel #38
0
 internal unsafe Reader(byte[]/*!*/ buffer, IDictionary localAssemblyCache, bool doNotLockFile, bool getDebugInfo, bool useStaticCache, bool preserveShortBranches) {
   Debug.Assert(buffer != null);
   if (localAssemblyCache == null) localAssemblyCache = new Hashtable();
   this.localAssemblyCache = localAssemblyCache;
   this.getDebugSymbols = getDebugInfo;
   this.doNotLockFile = false;
   this.useStaticCache = useStaticCache;
   this.preserveShortBranches = preserveShortBranches;
   int n = this.bufferLength = buffer.Length;
   this.unmanagedBuffer = new UnmanagedBuffer(n);
   //^ base();
   byte* pb = (byte*)this.unmanagedBuffer.Pointer;
   for (int i = 0; i < n; i++) *pb++ = buffer[i];
 }
 internal static UnmanagedBuffer Allocate(int bytes)
 {
     Debug.Assert(bytes >= 0);
     UnmanagedBuffer buffer = new UnmanagedBuffer();
     buffer.SetHandle(Marshal.AllocHGlobal(bytes));
     buffer.Initialize((ulong)bytes);
     return buffer;
 }
            internal static unsafe void Copy(UnmanagedBuffer source, UnmanagedBuffer destination, ulong bytesLength)
            {
                if (bytesLength == 0)
                {
                    return;
                }

                byte* srcPtr = null, dstPtr = null;
                try
                {
                    source.AcquirePointer(ref srcPtr);
                    destination.AcquirePointer(ref dstPtr);
                    Buffer.MemoryCopy(srcPtr, dstPtr, destination.ByteLength, bytesLength);
                }
                finally
                {
                    if (dstPtr != null)
                    {
                        destination.ReleasePointer();
                    }
                    if (srcPtr != null)
                    {
                        source.ReleasePointer();
                    }
                }
            }
        /**
         * Find the entry point of a loaded module
         * based on its Base Address. Reverses the PE
         * structure to find the entry point
         */
        private static uint FindEntryPoint(IntPtr hProcess, IntPtr hModule)
        {
            if (hProcess.IsNull() || hProcess.Compare(-1))
                throw new ArgumentException("Invalid process handle.", "hProcess");
            if (hModule.IsNull())
                throw new ArgumentException("Invalid module handle.", "hModule");

            byte[] bDosHeader = WinAPI.ReadRemoteMemory(hProcess, hModule, (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
            if (bDosHeader != null)
            {
                ushort e_magic = BitConverter.ToUInt16(bDosHeader, 0);
                uint e_lfanew = BitConverter.ToUInt32(bDosHeader, 0x3C);
                if (e_magic == 23117)
                {
                    byte[] bNtHeader = WinAPI.ReadRemoteMemory(hProcess, hModule.Add(e_lfanew), (uint)Marshal.SizeOf(typeof(IMAGE_NT_HEADER32)));
                    if (bNtHeader != null && BitConverter.ToUInt32(bNtHeader, 0) == 17744)
                    {
                        IMAGE_NT_HEADER32 ntHd = default(IMAGE_NT_HEADER32);
                        using (var buffer = new UnmanagedBuffer(256))
                            if (buffer.Translate<IMAGE_NT_HEADER32>(bNtHeader, out ntHd))
                                return ntHd.OptionalHeader.AddressOfEntryPoint;
                    }
                }
            }
            return 0;
        }
 public void Add(UnmanagedBuffer buffer)
 {
     m_pool.Add(buffer);
 }