Created
January 19, 2024 12:11
-
-
Save kbridge/959d10a32e31b280f19585484378a45f to your computer and use it in GitHub Desktop.
method extracted from v8 source code. MSVC/Windows only.
This file contains hidden or 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
#include <windows.h> | |
#include <iostream> | |
#include <sstream> | |
#include <string> | |
#include <utility> | |
#include <intrin.h> | |
#include <stdint.h> | |
// current thread only | |
uintptr_t current_stack_start() | |
{ | |
thread_local static uintptr_t address = | |
reinterpret_cast< | |
#ifdef _WIN64 | |
NT_TIB64 * | |
#else | |
NT_TIB * | |
#endif | |
>(NtCurrentTeb())->StackBase; // see also StackLimit | |
return address; | |
} | |
uintptr_t current_stack_position() | |
{ | |
return reinterpret_cast<uintptr_t>(_AddressOfReturnAddress()); | |
} | |
std::string format_uintptr(uintptr_t value) | |
{ | |
std::ostringstream o; | |
o << "0x"; | |
o.setf(std::ios::hex, std::ios::basefield); | |
o.setf(std::ios::uppercase); | |
o.fill('0'); | |
o.width(sizeof(uintptr_t) * 2); | |
o << value; | |
return std::move(o).str(); | |
} | |
std::string current_stack_range() | |
{ | |
uintptr_t position = current_stack_position(); | |
uintptr_t start = current_stack_start(); | |
return ( | |
std::ostringstream() | |
<< format_uintptr(position) << " <= x <= " << format_uintptr(start) | |
<< " " | |
<< "[" << (start - position) << " bytes]" | |
).str(); | |
} | |
bool check_on_stack(const void *ptr) | |
{ | |
uintptr_t address = reinterpret_cast<uintptr_t>(ptr); | |
return current_stack_position() <= address && address <= current_stack_start(); | |
} | |
int main() | |
{ | |
int foo = 0; | |
int *bar = new int; | |
std::cout << current_stack_range() << "\n"; | |
std::cout << check_on_stack(&foo) << "\n"; | |
std::cout << check_on_stack(bar) << "\n"; | |
return 0; | |
} | |
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/api/api.cc;l=768;drc=e5f8ff312fe542f39c7d34b4440f18d1500b15f9;bpv=0;bpt=1 | |
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/base/platform/platform-win32.cc;l=1811;drc=e5f8ff312fe542f39c7d34b4440f18d1500b15f9 | |
// https://stackoverflow.com/questions/15944119/addressofreturnaddress-equivalent-in-clang-llvm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment