Skip to content

Instantly share code, notes, and snippets.

@EgorBo
Last active September 9, 2022 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EgorBo/aeaaae0755c2dfa04320b2a9372b900e to your computer and use it in GitHub Desktop.
Save EgorBo/aeaaae0755c2dfa04320b2a9372b900e to your computer and use it in GitHub Desktop.
AddrSan.cs
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
unsafe class Program
{
[DllImport("kernel32")]
static extern byte* VirtualAlloc(IntPtr addr, nuint size, uint typ, uint prot);
static void Main()
{
// Case 1: pass 50 elements of a managed array
int[] data = new int[50];
Foo(ref data[0], 50);
// Case 2: same amount of memory, just allocated at the page boundary
uint length = (uint)Environment.SystemPageSize;
byte* ptr = VirtualAlloc(IntPtr.Zero, length, 0x1000 | 0x2000 /* reserve commit */, 0x04);
ref int pointer = ref Unsafe.AsRef<int>(ptr + length - 50 * sizeof(int));
// pointer pointing to exactly 50 ints (200 bytes)
Foo(ref pointer, 50);
}
static void Foo(ref int data, nuint length)
{
// This algorithm has a bug, it reads more than needed for last vector
for (nuint i = 0; i < length; i += (nuint)Vector128<int>.Count)
{
Vector128<int> vec = Vector128.LoadUnsafe(ref data, i);
vec += Vector128.Create(1);
vec.StoreUnsafe(ref data, i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment