MemoryAllocator

We found 10 examples in language CSharp for this search. You will see 45 fragments of code.

        public void AllocTileWorkerData(MemoryAllocator allocator, int tileCols, int tileRows, int maxThreads)
        {
            TileWorkerData = allocator.Allocate<TileWorkerData>(tileCols * tileRows + (maxThreads > 1 ? maxThreads : 0));
        }

        public void FreeTileWorkerData(MemoryAllocator allocator)
        {
            allocator.Free(TileWorkerData);
        }

        private void AllocSegMap(MemoryAllocator allocator, int segMapSize)
        {
            int i;

            for (i = 0; i < Constants.NumPingPongBuffers; ++i)
            {
                SegMapArray[i] = allocator.Allocate<byte>(segMapSize);
            }

            // Init the index.
            SegMapIdx = 0;
            PrevSegMapIdx = 1;

            CurrentFrameSegMap = SegMapArray[SegMapIdx];
            LastFrameSegMap = SegMapArray[PrevSegMapIdx];
        }

        private void FreeSegMap(MemoryAllocator allocator)
        {
            int i;

            for (i = 0; i < Constants.NumPingPongBuffers; ++i)
            {
                allocator.Free(SegMapArray[i]);
                SegMapArray[i] = ArrayPtr<byte>.Null;
            }

            CurrentFrameSegMap = ArrayPtr<byte>.Null;
            LastFrameSegMap = ArrayPtr<byte>.Null;
        }

        private void DecAllocMi(MemoryAllocator allocator, int miSize)
        {
            Mip = allocator.Allocate<ModeInfo>(miSize);
            MiGridBase = allocator.Allocate<Ptr<ModeInfo>>(miSize);
        }

        private void DecFreeMi(MemoryAllocator allocator)
        {
            allocator.Free(Mip);
            Mip = ArrayPtr<ModeInfo>.Null;
            allocator.Free(MiGridBase);
            MiGridBase = ArrayPtr<Ptr<ModeInfo>>.Null;
        }


        [Fact]
        public void ReleaseRetainedResources_DisposingPreviouslyAllocatedBuffer_IsAllowed()
        {
            IMemoryOwner<int> buffer = this.MemoryAllocator.Allocate<int>(32);
            this.MemoryAllocator.ReleaseRetainedResources();
            buffer.Dispose();
        }

        [Fact]
        public void CreateWithAggressivePooling()
        {
            if (!TestEnvironment.Is64BitProcess)
            {
                // can lead to OutOfMemoryException
                return;
            }

            this.MemoryAllocator = ArrayPoolMemoryAllocator.CreateWithAggressivePooling();

            Assert.True(this.CheckIsRentingPooledBuffer<Rgba32>(4096 * 4096));
        }

        [Fact]
        public void CreateDefault()
        {
            if (!TestEnvironment.Is64BitProcess)
            {
                // can lead to OutOfMemoryException
                return;
            }

            this.MemoryAllocator = ArrayPoolMemoryAllocator.CreateDefault();

            Assert.False(this.CheckIsRentingPooledBuffer<Rgba32>(2 * 4096 * 4096));
            Assert.True(this.CheckIsRentingPooledBuffer<Rgba32>(2048 * 2048));
        }

        [Fact]
        public void CreateWithModeratePooling()
        {
            if (!TestEnvironment.Is64BitProcess)
            {
                // can lead to OutOfMemoryException
                return;
            }

            this.MemoryAllocator = ArrayPoolMemoryAllocator.CreateWithModeratePooling();

            Assert.False(this.CheckIsRentingPooledBuffer<Rgba32>(2048 * 2048));
            Assert.True(this.CheckIsRentingPooledBuffer<Rgba32>(1024 * 16));
        }

        [Theory]
        [InlineData(-1)]
        [InlineData((int.MaxValue / SizeOfLargeStruct) + 1)]
        public void AllocateIncorrectAmount_ThrowsCorrect_ArgumentOutOfRangeException(int length)
        {
            ArgumentOutOfRangeException ex = Assert.Throws<ArgumentOutOfRangeException>(() => this.MemoryAllocator.Allocate<LargeStruct>(length));
            Assert.Equal("length", ex.ParamName);
        }

        [Theory]
        [InlineData(-1)]
        public void AllocateManagedByteBuffer_IncorrectAmount_ThrowsCorrect_ArgumentOutOfRangeException(int length)
        {
            ArgumentOutOfRangeException ex = Assert.Throws<ArgumentOutOfRangeException>(() => this.MemoryAllocator.AllocateManagedByteBuffer(length));
            Assert.Equal("length", ex.ParamName);
        }


        public void LoadImage(ProgramImage image, ushort environmentSegment = 0, string commandLineArgs = null, string stdOut = null)
        {
            memoryAllocator.LoadImage(image, environmentSegment, commandLineArgs);
            UpdateSDA();

            if (!string.IsNullOrEmpty(stdOut))
                this.fileControl.SetStdOut(stdOut);

            vm.OnCurrentProcessChanged(EventArgs.Empty);
        }
        /// <summary>
        /// Ends the current process.
        /// </summary>
        /// <param name="residentParagraphs">Number of paragraphs to stay resident in memory.</param>
        public void EndCurrentProcess(int residentParagraphs)
        {
            if (residentParagraphs == 0)
                this.fileControl.CloseAllFiles(this.memoryAllocator.CurrentProcessId);
            memoryAllocator.EndCurrentProcess(residentParagraphs);
            UpdateSDA();
        }
        public ConventionalMemoryInfo GetAllocations() => memoryAllocator.GetAllocations();
        /// <summary>
        /// Must be called once when all other initialization is complete.
        /// </summary>
        public void InitializationComplete()
        {
            InitializeListOfLists();
            this.fileControl.Initialize(this.memoryAllocator);
            this.vm.FileSystem.CurrentDriveChanged += (s, e) => this.vm.PhysicalMemory.SetString(CurrentDirectoryAddress.Segment, CurrentDirectoryAddress.Offset, this.vm.FileSystem.CurrentDrive + "\\", true);
        }
        public void Dispose()
        {
            fileControl.Dispose();
            memoryAllocator.Dispose();
        }


        public virtual void AddAllocators(Dictionary<MemoryType, MemoryAllocator> allocators)
        {
            allocators.Add(MemoryType.Constant, new MemoryAllocator());
            allocators.Add(MemoryType.Main, new MemoryAllocator());
        }

namespace CoreEngine.Graphics
{
    public readonly struct GraphicsMemoryAllocation
    {
        public GraphicsMemoryAllocation(IGraphicsMemoryAllocator memoryAllocator, GraphicsHeap graphicsHeap, ulong offset, int sizeInBytes, bool isAliasable)
        {
            this.MemoryAllocator = memoryAllocator;
            this.GraphicsHeap = graphicsHeap;
            this.Offset = offset;
            this.SizeInBytes = sizeInBytes;
            this.IsAliasable = isAliasable;
        }

        public IGraphicsMemoryAllocator MemoryAllocator { get; }
        public GraphicsHeap GraphicsHeap { get; }
        public ulong Offset { get; }
        public int SizeInBytes { get; }
        public bool IsAliasable { get; }
    }
}


    private static void OnAllocatorFree(in GraphicsMemoryRegion memoryRegion)
    {
        var memoryAllocator = memoryRegion.MemoryAllocator;
        ThrowIfNull(memoryAllocator);

        if (memoryAllocator.DeviceObject is D3D12GraphicsMemoryHeap memoryHeap)
        {
            var memoryManager = memoryHeap.MemoryManager;
            memoryManager.Free(memoryAllocator, in memoryRegion);
        }
    }

    /// <inheritdoc />
    protected override void Dispose(bool isDisposing)
    {
        var memoryAllocators = _memoryAllocators.AsSpanUnsafe(0, _memoryAllocators.Count);

        for (var index = 0; index < memoryAllocators.Length; index++)
        {
            var memoryAllocator = memoryAllocators[index];
            memoryAllocator.DeviceObject.Dispose();
        }

        _mutex.Dispose();
    }

    /// <inheritdoc />
    protected override bool TryAllocateUnsafe(in GraphicsMemoryAllocationOptions memoryAllocationOptions, out GraphicsMemoryRegion memoryRegion)
    {
        using var mutex = new DisposableMutex(_mutex, IsExternallySynchronized);
        return TryAllocateNoMutex(in memoryAllocationOptions, out memoryRegion);
    }

    /// <inheritdoc />
    protected override bool TryAllocateUnsafe(in GraphicsMemoryAllocationOptions memoryAllocationOptions, Span<GraphicsMemoryRegion> memoryRegions)
    {
        using var mutex = new DisposableMutex(_mutex, IsExternallySynchronized);
        return TryAllocateNoMutex(in memoryAllocationOptions, memoryRegions);
    }

    /// <inheritdoc />
    protected override bool TrySetMinimumByteLengthUnsafe(nuint minimumByteLength)
    {
        using var mutex = new DisposableMutex(_mutex, IsExternallySynchronized);
        return TrySetMinimumByteLengthNoMutex(minimumByteLength);
    }

    private GraphicsMemoryAllocator AddMemoryAllocator(nuint byteLength, bool isDedicated)
    {
        var memoryHeapCreateOptions = new D3D12GraphicsMemoryHeapCreateOptions {
            ByteLength = byteLength,
            D3D12HeapFlags = D3D12HeapFlags,
            D3D12HeapType = D3D12HeapType,
        };
        var memoryHeap = new D3D12GraphicsMemoryHeap(this, in memoryHeapCreateOptions);

        var memoryAllocatorCreateOptions = new GraphicsMemoryAllocatorCreateOptions {
            ByteLength = byteLength,
            IsDedicated = isDedicated,
            OnFree = new GraphicsMemoryAllocatorOnFreeCallback(&OnAllocatorFree),
        };
        var memoryAllocator = _createMemoryAllocator.Invoke(memoryHeap, in memoryAllocatorCreateOptions);

        MemoryManagerInfo.OperationCount++;
        _memoryAllocators.Add(memoryAllocator);

        MemoryManagerInfo.ByteLength += byteLength;
        MemoryManagerInfo.TotalFreeMemoryRegionByteLength += byteLength;

        return memoryAllocator;
    }


    private static void OnAllocatorFree(in GraphicsMemoryRegion memoryRegion)
    {
        var memoryAllocator = memoryRegion.MemoryAllocator;
        ThrowIfNull(memoryAllocator);

        if (memoryAllocator.DeviceObject is VulkanGraphicsMemoryHeap memoryHeap)
        {
            var memoryManager = memoryHeap.MemoryManager;
            memoryManager.Free(memoryAllocator, in memoryRegion);
        }
    }

    /// <inheritdoc />
    protected override void Dispose(bool isDisposing)
    {
        var memoryAllocators = _memoryAllocators.AsSpanUnsafe(0, _memoryAllocators.Count);

        for (var index = 0; index < memoryAllocators.Length; index++)
        {
            var memoryAllocator = memoryAllocators[index];
            memoryAllocator.DeviceObject.Dispose();
        }

        _mutex.Dispose();
    }


    /// <inheritdoc />
    protected override bool TryAllocateUnsafe(in GraphicsMemoryAllocationOptions memoryAllocationOptions, out GraphicsMemoryRegion memoryRegion)
    {
        using var mutex = new DisposableMutex(_mutex, IsExternallySynchronized);
        return TryAllocateNoMutex(in memoryAllocationOptions, out memoryRegion);
    }

    /// <inheritdoc />
    protected override bool TryAllocateUnsafe(in GraphicsMemoryAllocationOptions memoryAllocationOptions, Span<GraphicsMemoryRegion> memoryRegions)
    {
        using var mutex = new DisposableMutex(_mutex, IsExternallySynchronized);
        return TryAllocateNoMutex(in memoryAllocationOptions, memoryRegions);
    }

    /// <inheritdoc />
    protected override bool TrySetMinimumByteLengthUnsafe(nuint minimumByteLength)
    {
        using var mutex = new DisposableMutex(_mutex, IsExternallySynchronized);
        return TrySetMinimumByteLengthNoMutex(minimumByteLength);
    }

    private GraphicsMemoryAllocator AddMemoryAllocator(nuint byteLength, bool isDedicated)
    {
        var memoryHeapCreateOptions = new VulkanGraphicsMemoryHeapCreateOptions {
            ByteLength = byteLength,
            VkMemoryTypeIndex = VkMemoryTypeIndex,
        };
        var memoryHeap = new VulkanGraphicsMemoryHeap(this, in memoryHeapCreateOptions);

        var memoryAllocatorCreateOptions = new GraphicsMemoryAllocatorCreateOptions {
            ByteLength = byteLength,
            IsDedicated = isDedicated,
            OnFree = new GraphicsMemoryAllocatorOnFreeCallback(&OnAllocatorFree),
        };
        var memoryAllocator = _createMemoryAllocator.Invoke(memoryHeap, in memoryAllocatorCreateOptions);

        MemoryManagerInfo.OperationCount++;
        _memoryAllocators.Add(memoryAllocator);

        MemoryManagerInfo.ByteLength += byteLength;
        MemoryManagerInfo.TotalFreeMemoryRegionByteLength += byteLength;

        return memoryAllocator;
    }


            internal void Allocate(int n)
            {
                Interlocked.Increment(ref _allocations);
                Interlocked.Add(ref _bytesAllocated, n);
            }

        public IMemoryOwner<byte> Allocate(int length)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length));
            }

            if (length == 0)
            {
                return NullMemoryOwner;
            }

            var memoryOwner = AllocateInternal(length, out var bytesAllocated);

            Statistics.Allocate(bytesAllocated);

            return memoryOwner;
        }

        private static MemoryAllocator BuildDefault()
        {
            return new NativeMemoryAllocator(DefaultAlignment);
        }


		void SetupHack() {
			// Some XBEs appear to try to patch kernel stuff,
			// but this hack is enough to terminate that safely

			var phys = PageManager.AllocPhysPages(17);
			var virt = PageManager.AllocVirtPages(17, at: 0x80000000);
			Cpu.MapPages(virt, phys, 17, true);

			var hack = new GuestMemory<uint>(virt + 0x10000);
			var hack2 = MemoryAllocator.Allocate(0x20);
			hack[0x3c / 4] = unchecked(hack2 + 0x7FFF0000);
		}

		unsafe void SetupKernelThunk() {
			var ptr = (uint*) Cpu.CreatePhysicalPages(KernelCallsBase, 1);
			for(var i = 0; i < 400; ++i)
				ptr[i] = 0xccc1010f; // vmcall; int 3 // latter should never be hit
			var launchDataPage = MemoryAllocator.Allocate(0x3400);
			WriteLine($"Launch data page at {launchDataPage:X}");
			ptr[0xa4] = launchDataPage;
			Cpu.MapPages(KernelCallsBase, KernelCallsBase, 1, true);
			ptr[0x142] = 0xDEADBEEF; // XboxHardwareInfo
			var imageName = "xboxdash.xbe";
			// XXX: this should be 0x146.  Wtf? 0002CA8B in dash
			ptr[0x147] = MemoryAllocator.Allocate((uint) Extensions.SizeOf(typeof(AnsiString)) + (uint) imageName.Length + 1); // XeImageFileName
			var str = new GuestMemory<AnsiString>(ptr[0x147]);
			str.Value = new AnsiString {
				Buffer = ptr[0x147] + (uint) Extensions.SizeOf(typeof(AnsiString)), 
				Length = (ushort) imageName.Length, 
				MaxLength = (ushort) (imageName.Length + 1)
			};
			var gm = new GuestMemory<byte>(str.Value.Buffer);
			for(var i = 0; i < imageName.Length; ++i)
				gm[i] = (byte) imageName[i];
			gm[imageName.Length] = 0;
		}

		public void Start() {
			ThreadManager.Next();
			Cpu.Run();
		}

		public GuestMemory<T> New<T>() where T : struct =>
			new GuestMemory<T>(MemoryAllocator.Allocate((uint) Marshal.SizeOf<T>()));
		public GuestMemory<T> New<T>(T value) where T : struct =>
			new GuestMemory<T>(MemoryAllocator.Allocate((uint) Marshal.SizeOf<T>())) { Value = value };


    [Fact]
    public void Properties()
    {
      var allocator = new MemoryAllocator(_logger, new FarPtr(SEGMENT, 0), 0x10000, DEFAULT_ALIGNMENT);
      allocator.BasePointer.Should().Be(new FarPtr(SEGMENT, 0));
      allocator.Capacity.Should().Be(0x10000);
      allocator.RemainingBytes.Should().Be(0x10000);
    }

    [Fact]
    public void ConstructsJustEnough()
    {
      var allocator = new MemoryAllocator(_logger, new FarPtr(SEGMENT, 0xFFFE), 2, DEFAULT_ALIGNMENT);
      allocator.Should().NotBeNull();
    }

    [Fact]
    public void ConstructOverflowsSegment()
    {
      Action act = () => new MemoryAllocator(_logger, new FarPtr(SEGMENT, 0xFFFF), 2, DEFAULT_ALIGNMENT);
      act.Should().Throw<ArgumentException>();
    }

    [Fact]
    public void ConstructNotAligned()
    {
      Action act = () => new MemoryAllocator(_logger, new FarPtr(SEGMENT, 0xFFFF), 1, DEFAULT_ALIGNMENT);
      act.Should().Throw<ArgumentException>();
    }

    [Fact]
    public void AllocateZero()
    {
      var allocator = new MemoryAllocator(_logger, new FarPtr(SEGMENT, 0), 0x10000, DEFAULT_ALIGNMENT);

      var ptr = allocator.Malloc(0);
      ptr.Should().NotBe(FarPtr.Empty);
      allocator.RemainingBytes.Should().Be(0xFFFE);
      allocator.GetAllocatedMemorySize(ptr).Should().Be(DEFAULT_ALIGNMENT);
    }

    [Fact]
    public void FreeNull()
    {
      var allocator = new MemoryAllocator(_logger, new FarPtr(SEGMENT, 0), 0x10000, DEFAULT_ALIGNMENT);
      allocator.Free(FarPtr.Empty);
      allocator.GetAllocatedMemorySize(FarPtr.Empty).Should().Be(-1);
    }

SixLabors.ImageSharp.Memory.MemoryAllocator : Object

Methods :

public abstract IMemoryOwner<T> Allocate(Int32 length = , AllocationOptions options = None)
public abstract IManagedByteBuffer AllocateManagedByteBuffer(Int32 length = , AllocationOptions options = None)
public Void ReleaseRetainedResources()
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()