swapforth

Форк
0
/
main.c 
73 строки · 1.4 Кб
1
#include <stdio.h>
2
#include <stdint.h>
3
#include <inttypes.h>
4
#include <string.h>
5
#include <stdlib.h>
6
#include <sys/mman.h>
7

8
// These are Forth-callable C functions
9
// SwapForth is passed the array CFUNCS, so it knows the
10
// address of each of function at run-time.
11
//
12
// This means that SwapForth itself does not refer to any
13
// external symbols, so it can be relocated with memcpy().
14

15
typedef size_t cell_t;
16

17
void _dotx(cell_t x)
18
{
19
  printf("%016zx ", x);
20
}
21

22
void _bye()
23
{
24
  exit(0);
25
}
26

27
void _emit(char c)
28
{
29
  putchar(c);
30
  fflush(stdout);
31
}
32

33
int _key()
34
{
35
  return getchar();
36
}
37

38
static const size_t cfuncs[] = {
39
  (size_t)_dotx,
40
  (size_t)_bye,
41
  (size_t)_emit,
42
  (size_t)_key
43
};
44

45

46
#define MEMSIZE (1024 * 1024)
47

48
int main()
49
{
50
  extern unsigned char swapforth, swapforth_ends;
51

52
  // allocate executable memory via sys call
53
  void* mem = mmap(NULL, MEMSIZE, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0);
54

55
  // copy runtime code into allocated memory
56
  memcpy(mem, &swapforth, &swapforth_ends - &swapforth);
57
  printf("swapforth = %p\n", &swapforth);
58
  printf("mem       = %p\n", mem);
59

60
  // typecast allocated memory to a function pointer
61
  int64_t (*func) () = mem;
62

63
  int64_t stack[512 + 500];
64
  cell_t r = func(stack + 512, cfuncs);
65
  printf("(%p, %p)\n", stack + 512, cfuncs);
66
  printf("r = %zx\n", r);
67
  // printf("\ndepth = %d\n", (int)((stack + 512) - (int64_t*)r));
68

69
  // Free up allocated memory
70
  munmap(mem, MEMSIZE);
71

72
  return 0;
73
}
74

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.