Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * Arguments passed: %rdi, %rsi, %rdx, %rcx, %r8, %r9, stack (r-to-l)
 * Return: %rax, %rdx, %xmm0, %xmm1, %st0, %st1
 *
 * Caller saved: r10-r11, xmm4-5, xmm6-15 (high 64)
 * Callee saved: r12-r15, rdi, rsi, rbx, rbp, rsp, xmm6-15 (low 64)
 */
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <stdint.h>
#include <dlfcn.h>

/*
void show() {
  void (*fp)(char*);

  fp = puts;
  fp("hello evan.");
}
*/

#define _B(byte) (*code++ = (unsigned char)byte)
#define _W(word) (*((unsigned short*)code)++ = word)
// #define _L(word) (*((unsigned int*)code)++ = word)
#define _L(word) ({ unsigned long *_i = (unsigned long*)code; *_i = word; code += sizeof(unsigned long); })

void flush(void *dest, int len) {
  void *page;
#ifdef PAGESIZE
  const int page_size = PAGESIZE;
#else
  static int page_size = -1;
  if(page_size == -1) page_size = sysconf(_SC_PAGESIZE);
#endif

  page = (void*)((uintptr_t)dest & ~(page_size - 1));

  printf("%x / %x / %x / %d\n", dest, page, page_size, sizeof(unsigned long));

  mprotect((void*)page, page_size, PROT_READ | PROT_WRITE | PROT_EXEC);
}

int main(int argc, char **argv) {
  unsigned char *end, *code;
  void *start;
  void (*fp)();
  char *msg = "hello from runtime land.";
  start = calloc(1, 1024);
  code = (unsigned char*)start;
  _B(0x55);
  //_B(0x89); _B(0xe5);
  _B(0x48); _B(0x89); _B(0xe5);
  _B(0x48); _B(0x83); _B(0xec); _B(0x08);
  _B(0x48); _B(0xbf); _L((unsigned long)msg);
  _B(0x48); _B(0xb8);
  // _B(0x48); _B(0xa1);
  //_L((unsigned long)show);
  _L((unsigned long)dlsym(0, "puts"));
  _B(0xff); _B(0xd0);
  _B(0x48); _B(0x83); _B(0xec); _B(-0x08);
  _B(0xc9);
  // _B(0x5d);
  _B(0xc3);

  printf(" => %lx\n", dlsym(0, "puts"));

  flush(start, 1024);
  end = code;
  code = (unsigned char*)start;

  int i;
  for(i = 0; i < (end - code); i++) {
    printf("%02x ", code[i]);
  }

  printf("\n");

  fp = (void*)start;
  fp();

  return 1;
}