git subrepo pull (merge) --force deps/lightning
[pcsx_rearmed.git] / deps / lightning / check / setcode.c
CommitLineData
4a71579b
PC
1/*
2 * Simple test of using an alternate buffer for the code.
3 */
4
5#include <lightning.h>
6#include <stdio.h>
7#include <assert.h>
8#include <sys/mman.h>
9#if defined(__sgi)
10# include <fcntl.h>
11#endif
12
13#ifndef MAP_ANON
14# define MAP_ANON MAP_ANONYMOUS
15# ifndef MAP_ANONYMOUS
16# define MAP_ANONYMOUS 0
17# endif
18#endif
19
20#if !defined(__sgi)
21#define mmap_fd -1
22#endif
23
24int
25main(int argc, char *argv[])
26{
27 jit_uint8_t *ptr;
28 jit_state_t *_jit;
29 jit_word_t length;
30#if defined(__sgi)
31 int mmap_fd;
32#endif
33 void (*function)(void);
79bfeef6 34 int mmap_prot, mmap_flags, result;
4a71579b
PC
35
36#if defined(__sgi)
37 mmap_fd = open("/dev/zero", O_RDWR);
38#endif
39
c0c16242 40 mmap_prot = PROT_READ | PROT_WRITE;
79bfeef6 41#if !(__OpenBSD__ || __APPLE__)
c0c16242
PC
42 mmap_prot |= PROT_EXEC;
43#endif
44#if __NetBSD__
45 mmap_prot = PROT_MPROTECT(mmap_prot);
46 mmap_flags = 0;
47#else
48 mmap_flags = MAP_PRIVATE;
49#endif
50 mmap_flags |= MAP_ANON;
51 ptr = mmap(NULL, 1024 * 1024, mmap_prot, mmap_flags, mmap_fd, 0);
4a71579b
PC
52 assert(ptr != MAP_FAILED);
53#if defined(__sgi)
54 close(mmap_fd);
55#endif
56
57 init_jit(argv[0]);
58 _jit = jit_new_state();
59
60 jit_prolog();
61 jit_prepare();
62 jit_pushargi((jit_word_t)"%s\n");
63 jit_ellipsis();
64 jit_pushargi((jit_word_t)"ok");
65 jit_finishi(printf);
66
67 /* call to jit_realize() is only required when using an alternate
68 * code buffer. Note that not using mmap'ed memory may not work
69 * on several ports and/or operating system versions */
70 jit_realize();
71
72 length = 0;
73 if (jit_get_code(&length) != NULL)
74 abort();
75
76 if (length <= 4)
77 abort();
78
79 /* check that a too small buffer fails */
80 jit_set_code(ptr, 4);
81 function = jit_emit();
82 if (function != NULL)
83 abort();
84
c0c16242 85#if __NetBSD__
79bfeef6
PC
86 result = mprotect(ptr, 1024 * 1024, PROT_READ | PROT_WRITE);
87 assert(result == 0);
c0c16242 88#endif
4a71579b
PC
89 /* and calling again with enough space works */
90 jit_set_code(ptr, 1024 * 1024);
91 function = jit_emit();
92 if (function == NULL)
93 abort();
94
95 jit_clear_state();
79bfeef6
PC
96#if __NetBSD__ || __OpenBSD__ || __APPLE__
97 result = mprotect(ptr, 1024 * 1024, PROT_READ | PROT_EXEC);
98 assert(result == 0);
c0c16242 99#endif
4a71579b
PC
100 (*function)();
101 jit_destroy_state();
102 finish_jit();
103
104 munmap(ptr, 1024 * 1024);
105
106 return (0);
107}