Skip to content

Instantly share code, notes, and snippets.

@kaushiks
Created March 31, 2020 00:52
Show Gist options
  • Save kaushiks/a02efbafeb3f640c1c907f18f6b2956d to your computer and use it in GitHub Desktop.
Save kaushiks/a02efbafeb3f640c1c907f18f6b2956d to your computer and use it in GitHub Desktop.
//
// adder.cpp
//
// CXXFLAGS="-std=c++14 -O3 -ggdb -ggdb3" make adder
//
#include <iostream>
#include <cstdint>
#include <sys/mman.h>
class Adder final {
public:
Adder(uint32_t value)
: _push_rbp(0x55),
_mov_rbp_rsp{0x48, 0x89, 0xe5},
_lea_eax_rdi_{0x8d, 0x47},
_value(value),
_pop_rbp(0x5d),
_ret(0xc3) {
}
int (*entry())(int) {
return reinterpret_cast<int(*)(int)>(this);
}
private:
uint8_t const _push_rbp; // push rbp
uint8_t const _mov_rbp_rsp[3]; // mov rbp, rsp
uint8_t const _lea_eax_rdi_[2];
uint8_t const _value; // lea eax, [rdi + value]
uint8_t const _pop_rbp; // pop rbp
uint8_t const _ret; // ret
} __attribute__((packed));
int main() {
Adder* adder_heap = reinterpret_cast<Adder*>(::mmap(nullptr, 4096, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON | MAP_PRIVATE, 0, 0));
auto adder1 = new (adder_heap) Adder(1);
auto adder2 = new (adder_heap + 1) Adder(2);
auto add1 = adder1->entry();
auto add2 = adder2->entry();
for (int i = 0; i < 10; i++) {
std::cout << add1(i) << std::endl;
std::cout << add2(i) << std::endl;
}
::munmap(adder_heap, 4096);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment