Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Turning this into an inline assembler #1

Open
Myriachan opened this issue Jul 9, 2022 · 0 comments
Open

Turning this into an inline assembler #1

Myriachan opened this issue Jul 9, 2022 · 0 comments

Comments

@Myriachan
Copy link

Myriachan commented Jul 9, 2022

This project is silly and I love it. I have a silly idea of my own: turning this into a kind of inline assembler.

Since you can convert assembly code to a byte array at compile-time, why not combine it with this trick? (Example is x86-32 / x86-64 MSVC; other compilers and platforms have similar ways to do this.)

#include <cstdio>
#include <cstdint>

#pragma code_seg(push)
#pragma code_seg(".text$MEOW")  // declare segment so we can use it
#pragma code_seg(pop)
__declspec(allocate(".text$MEOW"))
extern const std::uint8_t g_return1234[] =
{
    0xB8, 0xD2, 0x04, 0x00, 0x00,    // mov eax, 1234
    0xC3    // ret
};

int main()
{
    std::printf("%d\n", (*(int (*)()) (std::uintptr_t) g_return1234)());
}

Side note: the need for the std::uintptr_t cast is actually a flaw in the C++ Standard that I've brought up as a defect in the specification. The Standard says reinterpret_cast cannot remove const, but const on a function pointer makes no sense. Some compilers allow casting a const array to function pointer type, and some don't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant