public int read2ByteMove(string code, int moveQty, string file = "") { byte[] memory = new byte[4]; UIntPtr theCode; if (!LoadCode(code, file).Contains(",")) { theCode = LoadUIntPtrCode(code, file); } else { theCode = getCode(code, file); } UIntPtr newCode = UIntPtr.Add(theCode, moveQty); if (ReadProcessMemory(pHandle, newCode, memory, (UIntPtr)2, IntPtr.Zero)) { return(BitConverter.ToInt32(memory, 0)); } else { return(0); } }
public ulong readUIntMove(string code, string file, int moveQty) { byte[] memory = new byte[8]; UIntPtr theCode; if (!LoadCode(code, file).Contains(",")) { theCode = LoadUIntPtrCode(code, file); } else { theCode = getCode(code, file, 8); } UIntPtr newCode = UIntPtr.Add(theCode, moveQty); if (ReadProcessMemory(pHandle, newCode, memory, (UIntPtr)8, IntPtr.Zero)) { return(BitConverter.ToUInt64(memory, 0)); } else { return(0); } }
public byte GetCurrentPlaybackInputByte() { int currentPosition = garouMem.Read2Byte(this.inputListMemory); UIntPtr currentPositionAddress = UIntPtr.Add(this.inputListMemory, currentPosition); return(garouMem.ReadByte(currentPositionAddress)); }
public static void SetMapSize(IntPtr env, uint size) { int err = _setMapSizeDelegate(env, UIntPtr.Add(UIntPtr.Zero, (int)size)); if (err != 0) { throw new MdbxException("mdbx_env_set_mapsize", err); } }
public void StopRecordInput() { garouMem.WriteBytes(ADDRESS_P1_INPUT_READ, originalInstruction); int currentPosition = garouMem.Read2Byte(this.inputListMemory); UIntPtr currentPositionAddress = UIntPtr.Add(this.inputListMemory, currentPosition); garouMem.WriteBytes(currentPositionAddress, new byte[] { 0x00 }); FreeInjectedFunction(); }
public Vec3 GetObjectVec(int objectID) { const int pStructSize = 0x47C; const int pCoordsBase = 0x045C284C; int offset = objectID * pStructSize; UIntPtr objectPtr = UIntPtr.Add((UIntPtr)pCoordsBase, offset); return(new Vec3(objectPtr)); }
public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; UIntPtr ptr = (UIntPtr)arr[0]; for (int ctr = 0; ctr < arr.Length; ctr++) { UIntPtr newPtr = UIntPtr.Add(ptr, ctr); Console.Write("{0} ", newPtr); } }
public static EnvStat Stat(IntPtr env) { EnvStat stat = new EnvStat(); UIntPtr bytes = UIntPtr.Add(UIntPtr.Zero, Marshal.SizeOf(stat)); int err = _statDelegate(env, ref stat, bytes); if (err != 0) { throw new MdbxException("mdbx_env_stat", err); } return(stat); }
public static EnvInfo Info(IntPtr env) { EnvInfo info = new EnvInfo(); UIntPtr bytes = UIntPtr.Add(UIntPtr.Zero, Marshal.SizeOf(info)); int err = _infoDelegate(env, ref info, bytes); if (err != 0) { throw new MdbxException("mdbx_env_info", err); } return(info); }
public bool writeMove(string code, string type, string write, int moveQty, string file = "") //version v1.0.3 { byte[] memory = new byte[4]; int size = 4; UIntPtr theCode; if (!LoadCode(code, file).Contains(",")) { theCode = LoadUIntPtrCode(code, file); } else { theCode = getCode(code, file); } if (type == "float") { memory = BitConverter.GetBytes(Convert.ToSingle(write)); size = 4; } else if (type == "int") { memory = BitConverter.GetBytes(Convert.ToInt32(write)); size = 4; } else if (type == "byte") { memory = new byte[1]; memory = BitConverter.GetBytes(Convert.ToInt32(write)); size = 1; } else if (type == "string") { memory = new byte[write.Length]; memory = System.Text.Encoding.UTF8.GetBytes(write); size = write.Length; } UIntPtr newCode = UIntPtr.Add(theCode, moveQty); if (WriteProcessMemory(pHandle, newCode, memory, (UIntPtr)size, IntPtr.Zero)) { return(true); } else { return(false); } }
public static void UIntPtrArithmetic() { var value = new UIntPtr(40U); Equal(new UIntPtr(800U), value.Multiply(new UIntPtr(20U))); Equal(new UIntPtr(800U), value.MultiplyChecked(new UIntPtr(20U))); Equal(uint.MaxValue * 2UL, new UIntPtr(uint.MaxValue).Multiply(new UIntPtr(2U)).ToUInt64()); Equal(new UIntPtr(20U), value.Divide(new UIntPtr(2L))); Equal(new UIntPtr(40U ^ 234U), value.Xor(new UIntPtr(234U))); Equal(new UIntPtr(60U), value.Add(new UIntPtr(20U))); Equal(new UIntPtr(39U), value.Decrement()); Equal(new UIntPtr(41U), value.Increment()); Equal(new UIntPtr(1), value.Remainder(new UIntPtr(3))); }
public string ReadUTF8String(IntPtr Hwnd, UIntPtr MemoryAddress) { List <byte> bytes = new List <byte>(); byte b = ReadProcessMemory(Hwnd, MemoryAddress, 1u)[0]; while ((b != 0x0)) //Пока не кончится строка { bytes.Add(b); MemoryAddress = UIntPtr.Add(MemoryAddress, 1); b = ReadProcessMemory(Hwnd, MemoryAddress, 1u)[0]; //Читаем байт } return(Encoding.UTF8.GetString(bytes.ToArray())); }
/// <summary> /// Write to address and move by moveQty. Good for byte arrays. See https://github.com/erfg12/memory.dll/wiki/Writing-a-Byte-Array for more information. /// </summary> ///<param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param> ///<param name="type">byte, bytes, float, int, string or long.</param> /// <param name="write">byte to write</param> /// <param name="MoveQty">quantity to move</param> /// <param name="file">path and name of .ini file (OPTIONAL)</param> /// <param name="SlowDown">milliseconds to sleep between each byte</param> /// <returns></returns> public bool WriteMove(string code, string type, string write, int MoveQty, string file = "", int SlowDown = 0) { byte[] memory = new byte[4]; int size = 4; UIntPtr theCode; theCode = GetCode(code, file); if (type == "float") { memory = new byte[write.Length]; memory = BitConverter.GetBytes(Convert.ToSingle(write)); size = write.Length; } else if (type == "int") { memory = BitConverter.GetBytes(Convert.ToInt32(write)); size = 4; } else if (type == "double") { memory = BitConverter.GetBytes(Convert.ToDouble(write)); size = 8; } else if (type == "long") { memory = BitConverter.GetBytes(Convert.ToInt64(write)); size = 8; } else if (type == "byte") { memory = new byte[1]; memory[0] = Convert.ToByte(write, 16); size = 1; } else if (type == "string") { memory = new byte[write.Length]; memory = System.Text.Encoding.UTF8.GetBytes(write); size = write.Length; } UIntPtr newCode = UIntPtr.Add(theCode, MoveQty); //Debug.Write("DEBUG: Writing bytes [TYPE:" + type + " ADDR:[O]" + theCode + " [N]" + newCode + " MQTY:" + MoveQty + "] " + String.Join(",", memory) + Environment.NewLine); Thread.Sleep(SlowDown); return(WriteProcessMemory(mProc.Handle, newCode, memory, (UIntPtr)size, IntPtr.Zero)); }
public static void Add(UIntPtr ptr, int offset, ulong expected) { UIntPtr p1 = UIntPtr.Add(ptr, offset); VerifyPointer(p1, expected); UIntPtr p2 = ptr + offset; VerifyPointer(p2, expected); UIntPtr p3 = ptr; p3 += offset; VerifyPointer(p3, expected); }
public static UIntPtr Add(UIntPtr pointer, int offset) { #if NET35 switch (UIntPtr.Size) { case 4: return(new UIntPtr(unchecked ((uint)((int)pointer + offset)))); case 8: return(new UIntPtr(unchecked ((ulong)((long)pointer + offset)))); default: throw new NotSupportedException("Not supported platform"); } #else return(UIntPtr.Add(pointer, offset)); #endif }
public string ReadUTF8String(UIntPtr MemoryAddress) { const uint maxStrLenght = 200; List <byte> bytes = new List <byte>(); byte b = this.ReadByte(MemoryAddress); uint readedBytes = 0; while ((b != 0x0) & readedBytes < maxStrLenght) //While not find end of string (or string limit) { bytes.Add(b); MemoryAddress = UIntPtr.Add(MemoryAddress, 1); b = this.ReadByte(MemoryAddress); readedBytes++; } return(Encoding.UTF8.GetString(bytes.ToArray())); }
/// <summary> /// Get UInt and move to another address by moveQty. Use in a for loop. /// </summary> /// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param> /// <param name="moveQty">Quantity to move.</param> /// <param name="file">path and name of ini file (OPTIONAL)</param> /// <returns></returns> public ulong ReadUIntMove(string code, int moveQty, string file = "") { byte[] memory = new byte[8]; UIntPtr theCode = GetCode(code, file, 8); if (theCode == null || theCode == UIntPtr.Zero || theCode.ToUInt64() < 0x10000) { return(0); } UIntPtr newCode = UIntPtr.Add(theCode, moveQty); if (ReadProcessMemory(mProc.Handle, newCode, memory, (UIntPtr)8, IntPtr.Zero)) { return(BitConverter.ToUInt64(memory, 0)); } else { return(0); } }
public void CanImplementInterface() { var config = new CiladorConfigType(); config.WeaveConfig = new WeaveConfigTypeBase[] { new InterfaceMixinConfigType { InterfaceMixinMap = new InterfaceMixinMapType[] { new InterfaceMixinMapType { Interface = typeof(IInterfaceWithOnlyPrimitiveTypes).GetShortAssemblyQualifiedName(), Mixin = typeof(PropertiesAndMethodsWithPrimitiveTypesMixin).GetShortAssemblyQualifiedName() } } }, }; var assembly = ModuleWeaverHelper.WeaveAndLoadTestTarget("Cilador.Fody.TestMixinTargets", config); var targetType = assembly.GetType(typeof(InterfaceWithOnlyPrimitiveTypesTarget).FullName); Assert.That(typeof(IInterfaceWithOnlyPrimitiveTypes).IsAssignableFrom(targetType)); targetType.ValidateMemberCountsAre(1, 42, 14, 14, 0, 0); Assert.That(targetType.GetConstructor(new Type[0]) != null, "Lost existing default constructor"); var instanceObject = Activator.CreateInstance(targetType, new object[0]); Assert.That(instanceObject is IInterfaceWithOnlyPrimitiveTypes); var instance = (IInterfaceWithOnlyPrimitiveTypes)instanceObject; instance.BooleanProperty = true; Assert.That(instance.BooleanProperty); instance.BooleanProperty = false; Assert.That(!instance.BooleanProperty); instance.ByteProperty = Byte.MinValue; Assert.That(instance.ByteProperty == Byte.MinValue); instance.ByteProperty = 0; Assert.That(instance.ByteProperty == 0); instance.ByteProperty = Byte.MaxValue; Assert.That(instance.ByteProperty == Byte.MaxValue); instance.SByteProperty = SByte.MinValue; Assert.That(instance.SByteProperty == SByte.MinValue); instance.SByteProperty = 0; Assert.That(instance.SByteProperty == 0); instance.SByteProperty = SByte.MaxValue; Assert.That(instance.SByteProperty == SByte.MaxValue); instance.Int16Property = Int16.MinValue; Assert.That(instance.Int16Property == Int16.MinValue); instance.Int16Property = 0; Assert.That(instance.Int16Property == 0); instance.Int16Property = Int16.MaxValue; Assert.That(instance.Int16Property == Int16.MaxValue); instance.UInt16Property = UInt16.MinValue; Assert.That(instance.UInt16Property == UInt16.MinValue); instance.UInt16Property = 0; Assert.That(instance.UInt16Property == 0); instance.UInt16Property = UInt16.MaxValue; Assert.That(instance.UInt16Property == UInt16.MaxValue); instance.Int32Property = Int32.MinValue; Assert.That(instance.Int32Property == Int32.MinValue); instance.Int32Property = 0; Assert.That(instance.Int32Property == 0); instance.Int32Property = Int32.MaxValue; Assert.That(instance.Int32Property == Int32.MaxValue); instance.UInt32Property = UInt32.MinValue; Assert.That(instance.UInt32Property == UInt32.MinValue); instance.UInt32Property = 0; Assert.That(instance.UInt32Property == 0); instance.UInt32Property = UInt32.MaxValue; Assert.That(instance.UInt32Property == UInt32.MaxValue); instance.Int64Property = Int64.MinValue; Assert.That(instance.Int64Property == Int64.MinValue); instance.Int64Property = 0; Assert.That(instance.Int64Property == 0); instance.Int64Property = Int64.MaxValue; Assert.That(instance.Int64Property == Int64.MaxValue); instance.UInt64Property = UInt64.MinValue; Assert.That(instance.UInt64Property == UInt64.MinValue); instance.UInt64Property = 0; Assert.That(instance.UInt64Property == 0); instance.UInt64Property = UInt64.MaxValue; Assert.That(instance.UInt64Property == UInt64.MaxValue); instance.IntPtrProperty = IntPtr.Add(IntPtr.Zero, 402); Assert.That(instance.IntPtrProperty == IntPtr.Add(IntPtr.Zero, 402)); instance.IntPtrProperty = IntPtr.Zero; Assert.That(instance.IntPtrProperty == IntPtr.Zero); instance.UIntPtrProperty = UIntPtr.Add(UIntPtr.Zero, 4987); Assert.That(instance.UIntPtrProperty == UIntPtr.Add(UIntPtr.Zero, 4987)); instance.UIntPtrProperty = UIntPtr.Zero; Assert.That(instance.UIntPtrProperty == UIntPtr.Zero); instance.CharProperty = Char.MinValue; Assert.That(instance.CharProperty == Char.MinValue); instance.CharProperty = (Char)0; Assert.That(instance.CharProperty == 0); instance.CharProperty = Char.MaxValue; Assert.That(instance.CharProperty == Char.MaxValue); instance.DoubleProperty = Double.MinValue; Assert.That(instance.DoubleProperty == Double.MinValue); instance.DoubleProperty = 0; Assert.That(instance.DoubleProperty == 0); instance.DoubleProperty = Double.MaxValue; Assert.That(instance.DoubleProperty == Double.MaxValue); instance.SingleProperty = Single.MinValue; Assert.That(instance.SingleProperty == Single.MinValue); instance.SingleProperty = 0; Assert.That(instance.SingleProperty == 0); instance.SingleProperty = Single.MaxValue; Assert.That(instance.SingleProperty == Single.MaxValue); }
/// <summary> /// Creates a code cave to write custom opcodes in target process /// </summary> /// <param name="code">Address to create the trampoline</param> /// <param name="newBytes">The opcodes to write in the code cave</param> /// <param name="replaceCount">The number of bytes being replaced</param> /// <param name="size">size of the allocated region</param> /// <param name="file">ini file to look in</param> /// <remarks>Please ensure that you use the proper replaceCount /// if you replace halfway in an instruction you may cause bad things</remarks> /// <returns>UIntPtr to created code cave for use for later deallocation</returns> public UIntPtr CreateCodeCave(string code, byte[] newBytes, int replaceCount, int size = 0x1000, string file = "") { if (replaceCount < 5) { return(UIntPtr.Zero); // returning UIntPtr.Zero instead of throwing an exception } // to better match existing code UIntPtr theCode; theCode = GetCode(code, file); UIntPtr address = theCode; // if x64 we need to try to allocate near the address so we dont run into the +-2GB limit of the 0xE9 jmp UIntPtr caveAddress = UIntPtr.Zero; UIntPtr prefered = address; for (var i = 0; i < 10 && caveAddress == UIntPtr.Zero; i++) { caveAddress = VirtualAllocEx(mProc.Handle, FindFreeBlockForRegion(prefered, (uint)size), (uint)size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (caveAddress == UIntPtr.Zero) { prefered = UIntPtr.Add(prefered, 0x10000); } } // Failed to allocate memory around the address we wanted let windows handle it and hope for the best? if (caveAddress == UIntPtr.Zero) { caveAddress = VirtualAllocEx(mProc.Handle, UIntPtr.Zero, (uint)size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); } int nopsNeeded = replaceCount > 5 ? replaceCount - 5 : 0; // (to - from - 5) int offset = (int)((long)caveAddress - (long)address - 5); byte[] jmpBytes = new byte[5 + nopsNeeded]; jmpBytes[0] = 0xE9; BitConverter.GetBytes(offset).CopyTo(jmpBytes, 1); for (var i = 5; i < jmpBytes.Length; i++) { jmpBytes[i] = 0x90; } byte[] caveBytes = new byte[5 + newBytes.Length]; offset = (int)(((long)address + jmpBytes.Length) - ((long)caveAddress + newBytes.Length) - 5); newBytes.CopyTo(caveBytes, 0); caveBytes[newBytes.Length] = 0xE9; BitConverter.GetBytes(offset).CopyTo(caveBytes, newBytes.Length + 1); WriteBytes(caveAddress, caveBytes); WriteBytes(address, jmpBytes); return(caveAddress); }
public byte[] GetRecordedInput() { UIntPtr inputAddress = UIntPtr.Add(this.inputListMemory, 2); // first two bytes are counter return(this.garouMem.ReadBytes(inputAddress, INPUT_LIST_MEMORY_SIZE - 2)); }
private UIntPtr FindFreeBlockForRegion(UIntPtr baseAddress, uint size) { UIntPtr minAddress = UIntPtr.Subtract(baseAddress, 0x70000000); UIntPtr maxAddress = UIntPtr.Add(baseAddress, 0x70000000); UIntPtr ret = UIntPtr.Zero; UIntPtr tmpAddress = UIntPtr.Zero; GetSystemInfo(out SYSTEM_INFO si); if (mProc.Is64Bit) { if ((long)minAddress > (long)si.maximumApplicationAddress || (long)minAddress < (long)si.minimumApplicationAddress) { minAddress = si.minimumApplicationAddress; } if ((long)maxAddress < (long)si.minimumApplicationAddress || (long)maxAddress > (long)si.maximumApplicationAddress) { maxAddress = si.maximumApplicationAddress; } } else { minAddress = si.minimumApplicationAddress; maxAddress = si.maximumApplicationAddress; } MEMORY_BASIC_INFORMATION mbi; UIntPtr current = minAddress; UIntPtr previous = current; while (VirtualQueryEx(mProc.Handle, current, out mbi).ToUInt64() != 0) { if ((long)mbi.BaseAddress > (long)maxAddress) { return(UIntPtr.Zero); // No memory found, let windows handle } if (mbi.State == MEM_FREE && mbi.RegionSize > size) { if ((long)mbi.BaseAddress % si.allocationGranularity > 0) { // The whole size can not be used tmpAddress = mbi.BaseAddress; int offset = (int)(si.allocationGranularity - ((long)tmpAddress % si.allocationGranularity)); // Check if there is enough left if ((mbi.RegionSize - offset) >= size) { // yup there is enough tmpAddress = UIntPtr.Add(tmpAddress, offset); if ((long)tmpAddress < (long)baseAddress) { tmpAddress = UIntPtr.Add(tmpAddress, (int)(mbi.RegionSize - offset - size)); if ((long)tmpAddress > (long)baseAddress) { tmpAddress = baseAddress; } // decrease tmpAddress until its alligned properly tmpAddress = UIntPtr.Subtract(tmpAddress, (int)((long)tmpAddress % si.allocationGranularity)); } // if the difference is closer then use that if (Math.Abs((long)tmpAddress - (long)baseAddress) < Math.Abs((long)ret - (long)baseAddress)) { ret = tmpAddress; } } } else { tmpAddress = mbi.BaseAddress; if ((long)tmpAddress < (long)baseAddress) // try to get it the cloest possible // (so to the end of the region - size and // aligned by system allocation granularity) { tmpAddress = UIntPtr.Add(tmpAddress, (int)(mbi.RegionSize - size)); if ((long)tmpAddress > (long)baseAddress) { tmpAddress = baseAddress; } // decrease until aligned properly tmpAddress = UIntPtr.Subtract(tmpAddress, (int)((long)tmpAddress % si.allocationGranularity)); } if (Math.Abs((long)tmpAddress - (long)baseAddress) < Math.Abs((long)ret - (long)baseAddress)) { ret = tmpAddress; } } } if (mbi.RegionSize % si.allocationGranularity > 0) { mbi.RegionSize += si.allocationGranularity - (mbi.RegionSize % si.allocationGranularity); } previous = current; current = new UIntPtr(((ulong)mbi.BaseAddress) + (ulong)mbi.RegionSize); if ((long)current >= (long)maxAddress) { return(ret); } if ((long)previous >= (long)current) { return(ret); // Overflow } } return(ret); }
private static void Scan(Process process, out List <VMChunkInfo> chunkInfos, out List <VMRegionInfo> mappingInfos, out UIntPtr addressLimit) { IntPtr processHandle = process.Handle; MEMORY_BASIC_INFORMATION m = new MEMORY_BASIC_INFORMATION(); chunkInfos = new List <VMChunkInfo>(); const UInt64 GB = 1024 * 1024 * 1024; UInt64 maxRegionSize = (UInt64)2 * GB; UIntPtr memoryLimit; if (process.Is64BitProcess()) { memoryLimit = (UIntPtr)((UInt64)6 * GB); } else { memoryLimit = UIntPtr.Subtract(UIntPtr.Zero, 1); } addressLimit = memoryLimit; // Use UIntPtr so that we can cope with addresses above 2GB in a /3GB or "4GT" environment, or 64-bit Windows UIntPtr address = (UIntPtr)0; while ((UInt64)address < (UInt64)memoryLimit) { int result = VirtualQueryEx(processHandle, address, out m, (uint)Marshal.SizeOf(m)); if (0 == result || (UInt64)m.RegionSize > maxRegionSize) { // Record the 'end' of the address scale // (Expect 2GB in the case of a Win32 process running under 32-bit Windows, but may be // extended to up to 3GB if the OS is configured for "4 GT tuning" with the /3GB switch // Expect 4GB in the case of a Win32 process running under 64-bit Windows) addressLimit = address; break; } VMChunkInfo chunk = new VMChunkInfo(); chunk.regionStartAddress = (UIntPtr)(UInt64)m.BaseAddress; chunk.regionSize = (UInt64)m.RegionSize; chunk.type = (PageType)m.Type; chunk.state = (PageState)m.State; if ((chunk.type == PageType.Image) || (chunk.type == PageType.Mapped)) { // .Net 4 maps assemblies into memory using the memory-mapped file mechanism; // they don't show up in Process.Modules list string fileName = GetMappedFileName(processHandle, chunk.regionStartAddress); if (fileName.Length > 0) { fileName = Path.GetFileName(fileName); chunk.regionName = fileName; } } chunkInfos.Add(chunk); UIntPtr oldAddress = address; // It's maddening, but UIntPtr.Add can't cope with 64-bit offsets under Win64! address = UIntPtr.Add(address, (int)m.RegionSize); if ((UInt64)address <= (UInt64)oldAddress) { addressLimit = oldAddress; break; } } ; mappingInfos = new List <VMRegionInfo>(); try { foreach (ProcessModule module in process.Modules) { VMRegionInfo mappingInfo = new VMRegionInfo(); mappingInfo.regionStartAddress = (UIntPtr)(UInt64)module.BaseAddress; mappingInfo.regionSize = (UInt64)module.ModuleMemorySize; mappingInfo.regionName = Path.GetFileName(module.FileName); mappingInfos.Add(mappingInfo); } } catch { } // Sort by address mappingInfos.Sort(delegate(VMRegionInfo map1, VMRegionInfo map2) { return(Comparer <UInt64> .Default.Compare((UInt64)map1.regionStartAddress, (UInt64)map2.regionStartAddress)); }); }
public override void GetDataForAddress(ulong address, uint byteCount, IntPtr buffer, out uint bytesRead) { uint offset = (uint)(address - _segmentData.VirtualAddress); uint pageAlignedOffset = AlignOffsetToPageBoundary(offset); int dataIndex = (int)(pageAlignedOffset / VirtualAllocPageSize); ReaderWriterLockSlim targetLock = _pageLocks[dataIndex]; // THREADING: Once we have acquired the read lock we need to hold it, in some fashion, through the entirity of this method, that prevents the PageOut code from // evicting this page data while we are using it. targetLock.EnterReadLock(); List <(ReaderWriterLockSlim Lock, bool IsHeldAsUpgradeableReadLock)> acquiredLocks = EnsurePageRangeAtOffset(offset, targetLock, byteCount); try { if (IsSinglePageRead(offset, byteCount)) { uint inPageOffset = MapOffsetToPageOffset(offset); CacheNativeMethods.Memory.memcpy(buffer, UIntPtr.Add(_pages[dataIndex].Data, (int)inPageOffset), new UIntPtr(byteCount)); bytesRead = byteCount; return; } else // This is a read that spans at least one page boundary. { IntPtr pInsertionPoint = buffer; uint inPageOffset = MapOffsetToPageOffset(offset); int remainingBytesToRead = (int)byteCount; do { if (dataIndex == _pages.Length) { // Out of data in this segment, report how many bytes we read bytesRead = byteCount - (uint)remainingBytesToRead; return; } uint bytesInCurrentPage = Math.Min((_pages[dataIndex].DataExtent - inPageOffset), (uint)remainingBytesToRead); UIntPtr targetData = _pages[dataIndex++].Data; CacheNativeMethods.Memory.memcpy(pInsertionPoint, UIntPtr.Add(targetData, (int)inPageOffset), new UIntPtr(bytesInCurrentPage)); pInsertionPoint += (int)bytesInCurrentPage; inPageOffset = 0; remainingBytesToRead -= (int)bytesInCurrentPage; } while (remainingBytesToRead > 0); // If we get here we completed the read across multiple pages, so report we read all that was required bytesRead = byteCount; } } finally { bool sawOriginalLockInLockCollection = false; foreach (var(Lock, IsHeldAsUpgradeableReadLock) in acquiredLocks) { if (Lock == targetLock) { sawOriginalLockInLockCollection = true; } if (IsHeldAsUpgradeableReadLock) { Lock.ExitUpgradeableReadLock(); } else { Lock.ExitReadLock(); } } // Exit our originally acquire read lock if, in the process of mapping in cache pages, we didn't have to upgrade it to an upgradeable read lock (in which // case it would have been released by the loop above). if (!sawOriginalLockInLockCollection) { targetLock.ExitReadLock(); } } }
public static unsafe void TestBasics() { UIntPtr p; uint i; ulong l; if (sizeof(void *) == 4) { // Skip UIntPtr tests on 32-bit platforms return; } int size = UIntPtr.Size; Assert.Equal(size, sizeof(void *)); TestPointer(UIntPtr.Zero, 0); i = 42; TestPointer(new UIntPtr(i), i); TestPointer((UIntPtr)i, i); i = 42; TestPointer(new UIntPtr(i), i); l = 0x0fffffffffffffff; TestPointer(new UIntPtr(l), l); TestPointer((UIntPtr)l, l); void *pv = new UIntPtr(42).ToPointer(); TestPointer(new UIntPtr(pv), 42); TestPointer((UIntPtr)pv, 42); p = UIntPtr.Add(new UIntPtr(42), 5); TestPointer(p, 42 + 5); // Add is spected NOT to generate an OverflowException p = UIntPtr.Add(new UIntPtr(0xffffffffffffffff), 5); unchecked { TestPointer(p, (long)0x0000000000000004); } p = UIntPtr.Subtract(new UIntPtr(42), 5); TestPointer(p, 42 - 5); bool b; p = new UIntPtr(42); b = p.Equals(null); Assert.False(b); b = p.Equals((object)42); Assert.False(b); b = p.Equals((object)(new UIntPtr(42))); Assert.True(b); int h = p.GetHashCode(); int h2 = p.GetHashCode(); Assert.Equal(h, h2); p = new UIntPtr(42); i = (uint)p; Assert.Equal(i, 42u); l = (ulong)p; Assert.Equal(l, 42u); UIntPtr p2; p2 = (UIntPtr)i; Assert.Equal(p, p2); p2 = (UIntPtr)l; Assert.Equal(p, p2); p2 = (UIntPtr)(p.ToPointer()); Assert.Equal(p, p2); p2 = new UIntPtr(40) + 2; Assert.Equal(p, p2); p2 = new UIntPtr(44) - 2; Assert.Equal(p, p2); p = new UIntPtr(0x7fffffffffffffff); Assert.Throws <OverflowException>(() => (uint)p); }
/// <summary> /// Increments packet references count by one /// </summary> public void AddRef() { ThrowIfNull(); m_Native->ReferenceCount = UIntPtr.Add(m_Native->ReferenceCount, 1); }
public unsafe void BuildJobTree() { foreach (var job in _jobs.Values) { job.Dispose(); } _rootJobs.Clear(); _jobs.Clear(); if (_ejobDescription == null) { BuildEjobDescription(); } var jobs = _driver.EnumJobs(); var bytes = stackalloc byte[512]; var pString = (UnicodeString *)bytes; int status; int processCount; int jobIdOffset = _ejobDescription.GetOffsetOf("JobId"); int jobParentOffset = _ejobDescription.GetOffsetOf("ParentJob"); var jobIdBuffer = new byte[4]; foreach (var jobObject in jobs) { var handle = jobObject.Handle; status = NtQueryObject(handle, ObjectInformationClass.ObjectNameInformation, pString, 512); processCount = GetJobProcessCount(handle); var job = new JobObject(handle, jobObject.Address, status == 0 ? new string(pString->Buffer) : null, processCount); if (jobIdOffset >= 0 && _driver.ReadMemory(UIntPtr.Add(jobObject.Address, jobIdOffset), jobIdBuffer)) { job.JobId = BitConverter.ToInt32(jobIdBuffer, 0); } _jobs.Add(jobObject.Address, job); } if (jobParentOffset >= 0) { // nested jobs supported (Windows 8+) foreach (var jobObject in jobs) { // get parent job var parentJobAddress = UIntPtr.Add(jobObject.Address, jobParentOffset); var parentPointer = new byte[IntPtr.Size]; _driver.ReadMemory(parentJobAddress, parentPointer); var parentAddress = new UIntPtr(BitConverter.ToUInt64(parentPointer, 0)); var job = _jobs[jobObject.Address]; if (parentAddress != UIntPtr.Zero) { var parentJob = _jobs[parentAddress]; job.Parent = parentJob; parentJob.AddChildJob(job); } else { _rootJobs.Add(job); } } } }
/// <summary> /// Adds an offset to the value of an unsigned pointer. /// </summary> /// <param name="pointer">The unsigned pointer to add the offset to.</param> /// <param name="offset">The offset to add.</param> /// <returns>A new unsigned pointer that reflects the addition of to .</returns> public static UIntPtr Add(this UIntPtr pointer, Int32 offset) { return(UIntPtr.Add(pointer, offset)); }
public void ParseStringAndWriteToAddress(String value, UIntPtr address, AVariableType variableType, Boolean hexadecimal = false) { var v = 0UL; var s = 0.0f; var d = 0.0; var x = UIntPtr.Zero; if (hexadecimal && (variableType == AVariableType.Single || variableType == AVariableType.Double)) { if (variableType == AVariableType.Single) { variableType = AVariableType.DWord; } else { variableType = AVariableType.QWord; } } if (variableType == AVariableType.ByteArray) { var b = new ATByteArray(); AStringUtils.ConvertStringToBytes(value, hexadecimal, b); for (var i = 0; i < b.Length; i++) { Proc.Memory.Write(UIntPtr.Add(address, i).ToIntPtr(), (Byte)b[i]); } } else { if (variableType == AVariableType.Single || variableType == AVariableType.Double) { d = UStringUtils.StringToDouble(value); s = UStringUtils.StringToFloat(value); } else { if (!(variableType == AVariableType.String || variableType == AVariableType.UnicodeString)) { if (hexadecimal) { value = "0x" + value; } v = AStringUtils.StrToQWordEx(value); // todo make custom work //if ((variableType == AVariableType.Custom) && (customtype != nil) & customtype.scriptusesfloat) //s = UStringUtils.StringToFloat(value); } } switch (variableType) { case AVariableType.Byte: Proc.Memory.Write(address.ToIntPtr(), (Byte)v); break; case AVariableType.Word: Proc.Memory.Write(address.ToIntPtr(), (UInt16)v); break; case AVariableType.DWord: Proc.Memory.Write(address.ToIntPtr(), (UInt32)v); break; case AVariableType.QWord: Proc.Memory.Write(address.ToIntPtr(), v); break; case AVariableType.Single: Proc.Memory.Write(address.ToIntPtr(), s); break; case AVariableType.Double: Proc.Memory.Write(address.ToIntPtr(), d); break; case AVariableType.String: Proc.Memory.Write(address.ToIntPtr(), value, Encoding.ASCII); break; case AVariableType.UnicodeString: Proc.Memory.Write(address.ToIntPtr(), value, Encoding.UTF8); break; case AVariableType.Custom: // todo make custom work //{ // if (customtype != nil) // { // getmem(ba, customtype.bytesize); // //try // if (readprocessmemory(processhandle, (pointer)(address), ba, customtype.bytesize, x)) // { // if (customtype.scriptusesfloat) // customtype.convertfloattodata(s, ba, address); // else // customtype.convertintegertodata(v, ba, address); // // writeprocessmemory(processhandle, (pointer)(address), ba, customtype.bytesize, x); // } // //finally // freememandnil(ba); // //end; // } //} break; } } }