private static T CreateSyscall(SyscallImportAttribute syscallImport) { // Create the shellcode used to perform the syscall var syscallIndex = GetSyscallIndex(syscallImport.DllName, syscallImport.FunctionName); var shellcodeBytes = Environment.Is64BitProcess ? Assembler.AssembleSyscall64(syscallIndex) : Assembler.AssembleSyscall32(syscallIndex); // Write the shellcode into the pinned object heap var pinnedArray = GC.AllocateArray <byte>(shellcodeBytes.Length, true); shellcodeBytes.CopyTo(pinnedArray); // Wrap the shellcode in a managed delegate var shellcodeAddress = Marshal.UnsafeAddrOfPinnedArrayElement(pinnedArray, 0); if (!Kernel32.VirtualProtect(shellcodeAddress, shellcodeBytes.Length, ProtectionType.ExecuteReadWrite, out _)) { throw new Win32Exception(); } return(Marshal.GetDelegateForFunctionPointer <T>(shellcodeAddress)); }
/// <summary> /// Constructor that initializes an evaluator to use a specified GPU with a specified network file. /// </summary> /// <param name="networkFilename"></param> /// <param name="gpuID"></param> public LC0LibraryNNEvaluator(string networkFilename, int gpuID) { if (gpuID < 0 || gpuID >= NNEvaluatorStats.MAX_GPUS) { throw new ArgumentOutOfRangeException(nameof(gpuID)); } CheckLibraryDirectoryOnPath(); SessionID = sessionIDPool.GetFreeID(); GPUID = gpuID; NetworkFilename = networkFilename; AllocErrorCode allocError = Alloc(SessionID, networkFilename, gpuID); if (allocError != AllocErrorCode.NO_ERROR) { throw new Exception($"Error returned by LC0 library in call to Alloc: {allocError}"); } // Allocate arrays pinned so we can pass the pointer to the DLL // TODO: would it be better to used fixed each time we call out to DLL? ItemsInStruct = GC.AllocateArray <CeresTransferBlockInItem>(MAX_POSITIONS_PER_BATCH, pinned: true); ItemsOutStruct = GC.AllocateArray <CeresTransferBlockOutItem>(MAX_POSITIONS_PER_BATCH, pinned: true); unsafe { fixed(CeresTransferBlockInItem *inputs = &ItemsInStruct[0]) fixed(CeresTransferBlockOutItem * outputs = &ItemsOutStruct[0]) { ptrBlockInItems = (IntPtr)inputs; ptrBlockOutItems = (IntPtr)outputs; } } }
public static long CreateGarbage() { byte[][] smallGarbage = new byte[2000][]; // This will force us to use more than one region in the small object heap for (int i = 0; i < 2000; i++) { // It will roughly span one page smallGarbage[i] = new byte[4000]; } // This will force us to use more than one region in the large object heap byte[] largeGarbage = new byte[33 * 1024 * 1024]; // This will force us to use more than one region in the pin object heap byte[] pinnedGarbage = GC.AllocateArray <byte>(33 * 1024 * 1024, /* pinned = */ true); GC.Collect(2, GCCollectionMode.Forced, blocking: true, compacting: true); long committed = GC.GetGCMemoryInfo().TotalCommittedBytes; GC.KeepAlive(smallGarbage); GC.KeepAlive(largeGarbage); GC.KeepAlive(pinnedGarbage); return(committed); }
public WinUSBInterfaceStream(WeakReference <WinUSBInterface> parentInterface) { this.parentInterface = parentInterface; if (!parentInterface.TryGetTarget(out var usbInterface)) { throw new InvalidOperationException("Weak reference to parent interface is unexpectedly invalid"); } this.interfaceNum = usbInterface.InterfaceNum; winUsbHandle = usbInterface.BorrowHandle(); if (usbInterface.InputPipe is byte readPipe) { this.readPipe = readPipe; readBuffer = GC.AllocateArray <byte>(usbInterface.InputReportLength, true); readPtr = (byte *)Unsafe.AsPointer(ref readBuffer[0]); } if (usbInterface.OutputPipe is byte writePipe) { this.writePipe = writePipe; writeBuffer = GC.AllocateArray <byte>(usbInterface.OutputReportLength, true); writePtr = (byte *)Unsafe.AsPointer(ref writeBuffer[0]); } }
public static void DoWork() { // Allocate POH objects var arr0 = GC.AllocateUninitializedArray <int>(100000, true); var arr1 = GC.AllocateArray <int>(200000, true); int k = 0; while (k < 3) { Console.WriteLine("{0}: Restarting run {1}", Thread.CurrentThread.Name, k); int[] largeArray = new int[1000000]; for (int i = 0; i <= 100; i++) { int[] saveArray = largeArray; largeArray = new int[largeArray.Length + 100000]; saveArray = null; //Console.WriteLine("{0} at size {1}",Thread.CurrentThread.Name,largeArray.Length.ToString()); } k++; } GC.KeepAlive(arr0); GC.KeepAlive(arr1); }
private static async Task DoReceiveAsync(Socket udpSocket, ThroughputCounter throughput, CancellationToken cancelToken) { // Taking advantage of pre-pinned memory here using the .NET5 POH (pinned object heap). var buffer = GC.AllocateArray <byte>(PacketSize, true); var bufferMem = buffer.AsMemory(); while (!cancelToken.IsCancellationRequested) { try { var result = await udpSocket.ReceiveFromAsync(bufferMem); // The result tells me where it came from, and gives me the data. if (result is SocketReceiveFromResult recvResult) { throughput.Add(recvResult.ReceivedBytes); } else { break; } } catch (SocketException) { // Socket exception means we are finished. break; } } }
internal ConcurrentDictionary_YcsbBenchmark(Key[] i_keys_, Key[] t_keys_, TestLoader testLoader) { this.testLoader = testLoader; init_keys_ = i_keys_; txn_keys_ = t_keys_; numaStyle = testLoader.Options.NumaStyle; distribution = testLoader.Distribution; readPercent = testLoader.Options.ReadPercent; #if DASHBOARD statsWritten = new AutoResetEvent[threadCount]; for (int i = 0; i < threadCount; i++) { statsWritten[i] = new AutoResetEvent(false); } threadThroughput = new double[threadCount]; threadAverageLatency = new double[threadCount]; threadMaximumLatency = new double[threadCount]; threadProgress = new long[threadCount]; writeStats = new bool[threadCount]; freq = Stopwatch.Frequency; #endif input_ = GC.AllocateArray <Input>(8, true); for (int i = 0; i < 8; i++) { input_[i].value = i; } store = new (testLoader.Options.ThreadCount, testLoader.MaxKey, new KeyComparer()); }
private static unsafe ReportHandler[] GetPinnedArray() { var array = GC.AllocateArray <ReportHandler>(1, pinned: true); array[0] = new ReportHandler { getVersionId = &GetVersionId, printDebug = &PrintDebug, onErrorControlROM = &OnErrorControlROM, onErrorControlPCMROM = &OnErrorPCMROM, showLCDMessage = &ShowLCDMessage, onMIDIMessagePlayed = &OnMIDIMessagePlayed, onMIDIQueueOverflow = &OnMIDIQueueOverflow, onMIDISystemRealtime = &OnMIDISystemRealtime, onDeviceReset = &OnDeviceReset, onDeviceReconfig = &OnDeviceReconfig, onNewReverbMode = &OnNewReverbMode, onNewReverbTime = &OnNewReverbTime, onNewReverbLevel = &OnNewReverbLevel, onPolyStateChanged = &OnPolyStateChanged, onProgramChanged = &OnProgramChanged }; return(array); }
internal T[]? Rent() { T[]?[] arrays = _arrays; T[]? result = null; bool lockTaken = false; bool allocateArray = false; try { _lock.Enter(ref lockTaken); if (_index < arrays.Length) { result = arrays[_index]; arrays[_index++] = null; allocateArray = result == null; } } finally { if (lockTaken) { _lock.Exit(false); } } if (allocateArray) { result = GC.AllocateArray <T>(_arrayLength, pinned: true); } return(result); }
public unsafe BottomLevelAccelerationStructure(Api api, RayTracingProperties rayTracingProperties, BottomLevelGeometry geometries) : base(api, rayTracingProperties) { _geometry = GC.AllocateArray <AccelerationStructureGeometryKHR>(geometries.Geometry.Count, true); geometries.Geometry.CopyTo(_geometry); _buildOffsetInfo = GC.AllocateArray <AccelerationStructureBuildRangeInfoKHR>(geometries.BuildOffsetInfo.Count, true); geometries.BuildOffsetInfo.CopyTo(_buildOffsetInfo); _buildGeometryInfo.SType = StructureType.AccelerationStructureBuildGeometryInfoKhr; _buildGeometryInfo.Flags = _flags; _buildGeometryInfo.GeometryCount = (uint)_geometry.Length; _buildGeometryInfo.PGeometries = (AccelerationStructureGeometryKHR *)Unsafe.AsPointer(ref _geometry[0]); _buildGeometryInfo.Mode = BuildAccelerationStructureModeKHR.BuildAccelerationStructureModeBuildKhr; _buildGeometryInfo.Type = AccelerationStructureTypeKHR.AccelerationStructureTypeBottomLevelKhr; _buildGeometryInfo.SrcAccelerationStructure = default; // Note: Could use stackalloc here, but the model count might be too high uint[] maxPrimCount = new uint[_buildOffsetInfo.Length]; for (int i = 0; i != maxPrimCount.Length; i++) maxPrimCount[i] = _buildOffsetInfo[i].PrimitiveCount; fixed(uint *maxPrimCountPtr = &maxPrimCount[0]) GetBuildSizes(maxPrimCountPtr, out _buildSizesInfo); }
/// <summary> /// Creates a new page-locked 1D array. /// </summary> /// <param name="accelerator">The parent accelerator.</param> /// <param name="extent">The number of elements to allocate.</param> /// <param name="uninitialized">True, to allocate an uninitialized array.</param> internal unsafe PageLockedArray1D( Accelerator accelerator, LongIndex1D extent, bool uninitialized) { if (extent < 0L) { throw new ArgumentOutOfRangeException(nameof(extent)); } #if NET5_0 array = uninitialized ? GC.AllocateUninitializedArray <T>(extent.ToIntIndex(), pinned: true) : GC.AllocateArray <T>(extent.ToIntIndex(), pinned: true); fixed(T *ptr = array) Initialize(accelerator, new IntPtr(ptr), extent); #else Trace.WriteLineIf( uninitialized, RuntimeErrorMessages.NotSupportedUninitalizedArrayInitialization); array = new T[extent]; handle = GCHandle.Alloc(array, GCHandleType.Pinned); Initialize(accelerator, handle.AddrOfPinnedObject(), extent); #endif }
public static int RunTest(String[] args) { int[] large = new int[100000]; int[] pinned = GC.AllocateArray <int>(32, true); Console.WriteLine("Test Passed"); return(100); }
/// <summary> /// Instantiate the epoch table /// </summary> public LightEpoch() { long p; #if NET5_0_OR_GREATER tableRaw = GC.AllocateArray <Entry>(kTableSize + 2, true); p = (long)Unsafe.AsPointer(ref tableRaw[0]); #else // Over-allocate to do cache-line alignment tableRaw = new Entry[kTableSize + 2]; tableHandle = GCHandle.Alloc(tableRaw, GCHandleType.Pinned); p = (long)tableHandle.AddrOfPinnedObject(); #endif // Force the pointer to align to 64-byte boundaries long p2 = (p + (Constants.kCacheLineBytes - 1)) & ~(Constants.kCacheLineBytes - 1); tableAligned = (Entry *)p2; CurrentEpoch = 1; SafeToReclaimEpoch = 0; for (int i = 0; i < kDrainListSize; i++) { drainList[i].epoch = int.MaxValue; } drainCount = 0; }
public BlittableAllocator(LogSettings settings, IFasterEqualityComparer <Key> comparer, Action <long, long> evictCallback = null, LightEpoch epoch = null, Action <CommitInfo> flushCallback = null) : base(settings, comparer, evictCallback, epoch, flushCallback) { overflowPagePool = new OverflowPool <PageUnit>(4, p => #if NET5_0_OR_GREATER { } #else p.handle.Free() #endif ); if (BufferSize > 0) { values = new byte[BufferSize][]; #if NET5_0_OR_GREATER pointers = GC.AllocateArray <long>(BufferSize, true); nativePointers = (long *)Unsafe.AsPointer(ref pointers[0]); #else pointers = new long[BufferSize]; handles = new GCHandle[BufferSize]; ptrHandle = GCHandle.Alloc(pointers, GCHandleType.Pinned); nativePointers = (long *)ptrHandle.AddrOfPinnedObject(); #endif } }
private unsafe static void AllocateArrayCheckPinning() { var list = new List <long[]>(); var r = new Random(1234); for (int i = 0; i < 10000; i++) { int size = r.Next(2, 100); var arr = i % 2 == 1 ? GC.AllocateArray <long>(size, pinned: true) : GC.AllocateUninitializedArray <long>(size, pinned: true); fixed(long *pElem = &arr[0]) { *pElem = (long)pElem; } if (r.Next(100) % 2 == 0) { list.Add(arr); } } GC.Collect(); foreach (var arr in list) { fixed(long *pElem = &arr[0]) { Assert.Equal(*pElem, (long)pElem); } } }
private unsafe void EnsureInitialized() { if (Volatile.Read(ref PointerList) == null) { lock (ManagedArray) { if (PointerList != null) { return; } StructArray = GC.AllocateArray <ParameterDescriptionStruct>(ManagedArray.Length, true); var list = GC.AllocateArray <IntPtr>(ManagedArray.Length, true); for (int i = 0; i < ManagedArray.Length; ++i) { ref var elem = ref StructArray[i]; elem = ManagedArray[i].internalDescription; list[i] = (IntPtr)Unsafe.AsPointer(ref elem); } Volatile.Write(ref PointerList, list); } }
public MultiProducerSequencerRef2(int bufferSize, IWaitStrategy waitStrategy) { if (bufferSize < 1) { throw new ArgumentException("bufferSize must not be less than 1"); } if (!bufferSize.IsPowerOf2()) { throw new ArgumentException("bufferSize must be a power of 2"); } _bufferSize = bufferSize; _waitStrategy = waitStrategy; _isBlockingWaitStrategy = !(waitStrategy is INonBlockingWaitStrategy); #if NETCOREAPP _availableBuffer = GC.AllocateArray <int>(bufferSize, pinned: true); _availableBufferPointer = (int *)Unsafe.AsPointer(ref _availableBuffer[0]); #else _availableBuffer = new int[bufferSize]; #endif _indexMask = bufferSize - 1; _indexShift = DisruptorUtil.Log2(bufferSize); InitialiseAvailableBuffer(); }
protected AServer(Configuration config) { ManualMode = config.Test == TestType.Manual; // Use Pinned Object Heap to reduce GC pressure MessageBuffer = GC.AllocateArray <byte>(config.MessageByteSize, true); config.Message.CopyTo(MessageBuffer, 0); }
public void AllocateArrayTest() { //从.Net 5开始支持 //AllocateArray 在托管堆根据长度分配数组,对数组对象分配默认值 //第一个参数是需要分配数组的长度 //第二个参数是否在GC中固定 People[] arr = GC.AllocateArray <People>(16); Console.WriteLine(arr.Length); }
unsafe public static void Main(string[] args) { var pinnedArray = GC.AllocateArray <byte>(128, pinned: true); fixed(byte *ptr = pinnedArray) { // This is no-op 'pinning' as it does not influence the GC } }
public EchoServer(Configuration config, BenchmarkStatistics benchmarkStatistics) : base(IPAddress.Parse(config.Address), config.Port) { ManualMode = config.Test == TestType.Manual; // Use Pinned Object Heap to reduce GC pressure message = GC.AllocateArray <byte>(config.MessageByteSize, true); config.Message.CopyTo(message, 0); NetCoreServerBenchmark.ProcessTransmissionType(config.Transmission); this.benchmarkStatistics = benchmarkStatistics; }
/// <summary> /// Initializes a new instance of the <see cref="EntryTable{TValue}"/> class with the specified capacity. /// </summary> /// <param name="capacity">Capacity of the table</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than 0</exception> public EntryTable(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity)); } _freeHint = 0; _allocated = new BitMap(); _table = GC.AllocateArray <TEntry>(capacity, pinned: true); }
public AllocObject(bool poh) { if (poh) { m_array = GC.AllocateArray <int>(ArraySize, true); } else { m_array = new int[ArraySize]; } }
private static T CreateSyscall(string dllName, string functionName) { var dllBytes = dllName.Equals("ntdll.dll", StringComparison.OrdinalIgnoreCase) ? Registry.NtdllBytes : Registry.Win32UBytes; // Look for the function in the DLL var peImage = new PeImage(dllBytes); var function = peImage.ExportDirectory.GetExportedFunction(functionName); if (function is null) { throw new EntryPointNotFoundException($"Failed to find the function {functionName} in the DLL {dllName}"); } // Create the shellcode used to perform the syscall Span <byte> shellcodeBytes; if (Environment.Is64BitProcess) { // Read the syscall index var syscallIndex = MemoryMarshal.Read <int>(dllBytes.Span.Slice(function.Offset + Constants.SyscallIndexOffset64)); shellcodeBytes = Assembler.AssembleSyscall64(syscallIndex); } else { // Read the syscall index var syscallIndex = MemoryMarshal.Read <int>(dllBytes.Span.Slice(function.Offset + Constants.SyscallIndexOffset32)); shellcodeBytes = Assembler.AssembleSyscall32(syscallIndex); } // Write the shellcode into the pinned object heap var pinnedArray = GC.AllocateArray <byte>(shellcodeBytes.Length, true); shellcodeBytes.CopyTo(pinnedArray); // Wrap the shellcode in a managed delegate var shellcodeAddress = Marshal.UnsafeAddrOfPinnedArrayElement(pinnedArray, 0); if (!Kernel32.VirtualProtect(shellcodeAddress, shellcodeBytes.Length, ProtectionType.ExecuteReadWrite, out _)) { throw new Win32Exception(); } return(Marshal.GetDelegateForFunctionPointer <T>(shellcodeAddress)); }
/* * public static ulong StaticValue; * * static void Main(string[] args) * { * Console.WriteLine("Start"); * * long sum = 0; * * MyNode node = new MyNode(); * * Enumerable.Range(0, 2 Environment.ProcessorCount).Select((i) => * { * return ThreadPool.QueueUserWorkItem((_) => * { * while (true) * { * var myType = new MyType(); * * unchecked * { * node = node.ChildNode = new MyNode(); // Hold some memory that will survive over garbage collection * * Interlocked.Add(ref sum, myType.Fibonacci(1000)); * try * { * MyMethod1(); * } catch * { * * } * } * } * }); * }).ToArray(); * * Console.WriteLine("Press key to exit"); * Console.Read(); * } * * static void MyMethod1() * { * ThrowSomeException(); * } * * static void ThrowSomeException() * { * throw new ArgumentNullException("test"); * } */ public static int RunTest(String[] args) { int numAllocators = 1024; int[] root1 = GC.AllocateArray <int>(AllocObject.ArraySize, true); int[] root2 = GC.AllocateArray <int>(AllocObject.ArraySize, true); AllocObject[] objs = new AllocObject[numAllocators]; Random rand = new Random(); int numPoh = 0; int numReg = 0; int i = 0; while (true) { i++; int pos = rand.Next(0, numAllocators); bool poh = rand.NextDouble() > 0.5; objs[pos] = new AllocObject(poh); if (poh) { ++numPoh; } else { ++numReg; } if (i % 1000 == 0) { GC.Collect(); //Console.WriteLine($"Did {i} iterations Allocated={GC.GetAllocatedBytesForCurrentThread()}"); } try { throw new Exception("pouet"); } catch { } int[] m_array = new int[100]; } Console.WriteLine($"{numPoh} POH allocs and {numReg} normal allocs."); GC.KeepAlive(root1); GC.KeepAlive(root2); return(100); }
public static int RunTest(String[] args) { int[] large = new int[100000]; int[] pinned = GC.AllocateArray <int>(32, true); // don't let the jit to optimize these allocations GC.KeepAlive(large); GC.KeepAlive(pinned); Console.WriteLine("Test Passed"); return(100); }
private static void AllocateArray() { // allocate a bunch of SOH byte arrays and touch them. var r = new Random(1234); for (int i = 0; i < 10000; i++) { int size = r.Next(10000); var arr = GC.AllocateArray <byte>(size, pinned: i % 2 == 1); if (size > 1) { arr[0] = 5; arr[size - 1] = 17; Assert.True(arr[0] == 5 && arr[size - 1] == 17); } } // allocate a bunch of LOH int arrays and touch them. for (int i = 0; i < 1000; i++) { int size = r.Next(100000, 1000000); var arr = GC.AllocateArray <int>(size, pinned: i % 2 == 1); arr[0] = 5; arr[size - 1] = 17; Assert.True(arr[0] == 5 && arr[size - 1] == 17); } // allocate a string array { int i = 100; var arr = GC.AllocateArray <string>(i); arr[0] = "5"; arr[i - 1] = "17"; Assert.True(arr[0] == "5" && arr[i - 1] == "17"); } // allocate max size byte array { if (IntPtr.Size == 8) { int i = 0x7FFFFFC7; var arr = GC.AllocateArray <byte>(i); arr[0] = 5; arr[i - 1] = 17; Assert.True(arr[0] == 5 && arr[i - 1] == 17); } } }
public BasePointer(IVirtualScreen screen, string Name) { ReportBuffer = GC.AllocateArray <byte>(Unsafe.SizeOf <T>(), pinned: true); ReportPointer = (T *)Unsafe.AsPointer(ref ReportBuffer[0]); T report = CreateReport(); *ReportPointer = report; VirtualScreen = screen; Device = VMultiDevice.Retrieve(Name); ScreenToVMulti = new Vector2(VirtualScreen.Width, VirtualScreen.Height) / 32767; }
public unsafe CommandBuffers(Api api, CommandPool commandPool, uint count) { (_api, _commandPool) = (api, commandPool); var allocInfo = new CommandBufferAllocateInfo(); allocInfo.SType = StructureType.CommandBufferAllocateInfo; allocInfo.CommandPool = _commandPool.VkCommandPool; allocInfo.Level = CommandBufferLevel.Primary; allocInfo.CommandBufferCount = count; _commandBuffers = GC.AllocateArray <CommandBuffer>((int)count, true); Util.Verify(_api.Vk.AllocateCommandBuffers(_api.Device.VkDevice, &allocInfo, (CommandBuffer *)Unsafe.AsPointer(ref _commandBuffers[0])), $"{nameof(CommandBuffers)}: Unable to allocate command buffers"); }
/// <summary> /// Construct new instance /// </summary> /// <param name="eventHandler">Event handler</param> /// <param name="bufferSize">Buffer size</param> public SeaaBuffer(EventHandler <SocketAsyncEventArgs> eventHandler, int bufferSize) { socketEventAsyncArgs = new SocketAsyncEventArgs(); #if NET5_0_OR_GREATER buffer = GC.AllocateArray <byte>(bufferSize, true); #else buffer = new byte[bufferSize]; handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); #endif bufferPtr = (byte *)Unsafe.AsPointer(ref buffer[0]); socketEventAsyncArgs.SetBuffer(buffer, 0, bufferSize); socketEventAsyncArgs.Completed += eventHandler; }