Last active
June 6, 2020 18:33
-
-
Save hypeartist/6dd68a69ec1ea8ae1f2b7e819d4c2346 to your computer and use it in GitHub Desktop.
.net core digging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Runtime.InteropServices; | |
using System.Security; | |
using System.Threading; | |
namespace ConsoleApp1 | |
{ | |
internal static class Program | |
{ | |
private static unsafe void Main(string[] args) | |
{ | |
var threadAccessor = new ThreadAccessor(Thread.CurrentThread); | |
var currentThreadHandle = (void**)threadAccessor.ThreadProxy.ThreadHandle; | |
if (Environment.Is64BitProcess) | |
{ | |
#if DEBUG | |
const int stackAddressOffset = 34; | |
#else | |
const int stackAddressOffset = 36; | |
#endif | |
var stackEndAddress = (ulong*)*((ulong*)currentThreadHandle + stackAddressOffset); | |
while ((*--stackEndAddress & 0x00007ff000000000) != 0x00007ff000000000) // ntdll.dll!RtlUserThreadStart | |
{ | |
} | |
while ((*--stackEndAddress & 0x00007ff000000000) != 0x00007ff000000000) // kernel32.dll!BaseThreadInitThunk | |
{ | |
} | |
var baseThreadInitThunk = *stackEndAddress; | |
var kernel32ImageBase = (baseThreadInitThunk & 0xffffffffffff0000) - 0x10000; | |
Console.WriteLine($"0x{((IntPtr)kernel32ImageBase).ToInt64().ToString("X16").ToLower()}"); | |
} | |
else | |
{ | |
var stackEndAddress = (uint*)*((uint*)currentThreadHandle + 49); | |
while ((*--stackEndAddress & 0x75d00000) != 0x75d00000) // ntdll.dll!__RtlUserThreadStart | |
{ | |
} | |
while ((*--stackEndAddress & 0x75d00000) != 0x75d00000) // kernel32.dll!@BaseThreadInitThunk | |
{ | |
} | |
var baseThreadInitThunk = *stackEndAddress; | |
var kernel32ImageBase = (baseThreadInitThunk & 0xffff0000) - 0x10000; | |
Console.WriteLine($"0x{((IntPtr)kernel32ImageBase).ToInt64().ToString("X8").ToLower()}"); | |
} | |
} | |
public sealed class ThreadProxy | |
{ | |
private ExecutionContext? _executionContext; | |
private SynchronizationContext? _synchronizationContext; | |
private string? _name; | |
private Delegate? _delegate; | |
private object? _threadStartArg; | |
public/*Sic!*/ IntPtr ThreadHandle; | |
} | |
[StructLayout(LayoutKind.Explicit)] | |
public readonly struct ThreadAccessor | |
{ | |
[FieldOffset(0)] | |
private readonly Thread _thread; | |
[FieldOffset(0)] | |
public readonly ThreadProxy ThreadProxy; | |
public ThreadAccessor(Thread thread) : this() => _thread = thread; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment