]> gitweb.factorcode.org Git - factor.git/blob - vm/os-unix.cpp
os-unix: Add MAP_JIT for apple arm64
[factor.git] / vm / os-unix.cpp
1 #include "master.hpp"
2
3 namespace factor {
4
5 bool set_memory_locked(cell base, cell size, bool locked) {
6   int prot = locked ? PROT_NONE : PROT_READ | PROT_WRITE;
7   int status = mprotect((char*)base, size, prot);
8   return status != -1;
9 }
10
11 THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) {
12   pthread_attr_t attr;
13   pthread_t thread;
14   if (pthread_attr_init(&attr) != 0)
15     fatal_error("pthread_attr_init() failed", 0);
16   if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) != 0)
17     fatal_error("pthread_attr_setdetachstate() failed", 0);
18   if (pthread_create(&thread, &attr, start_routine, args) != 0)
19     fatal_error("pthread_create() failed", 0);
20   pthread_attr_destroy(&attr);
21   return thread;
22 }
23
24 static void* null_dll;
25
26 void sleep_nanos(uint64_t nsec) {
27   timespec ts;
28   timespec ts_rem;
29   int ret;
30   ts.tv_sec = nsec / 1000000000;
31   ts.tv_nsec = nsec % 1000000000;
32   ret = nanosleep(&ts, &ts_rem);
33   while (ret == -1 && errno == EINTR) {
34     memcpy(&ts, &ts_rem, sizeof(ts));
35     ret = nanosleep(&ts, &ts_rem);
36   }
37
38   if (ret == -1)
39     fatal_error("nanosleep failed", 0);
40 }
41
42 void factor_vm::init_ffi() { null_dll = dlopen(NULL, RTLD_LAZY); }
43
44 void factor_vm::ffi_dlopen(dll* dll) {
45   dll->handle = dlopen(alien_offset(dll->path), RTLD_LAZY | RTLD_GLOBAL);
46 }
47
48 cell factor_vm::ffi_dlsym_raw(dll* dll, symbol_char* symbol) {
49   return (cell)dlsym(dll ? dll->handle : null_dll, symbol);
50 }
51
52 cell factor_vm::ffi_dlsym(dll* dll, symbol_char* symbol) {
53   return FUNCTION_CODE_POINTER(ffi_dlsym_raw(dll, symbol));
54 }
55
56 void factor_vm::ffi_dlclose(dll* dll) {
57   if (dlclose(dll->handle))
58     general_error(ERROR_FFI, false_object, false_object);
59   dll->handle = NULL;
60 }
61
62 void factor_vm::primitive_existsp() {
63   struct stat sb;
64   char* path = (char*)(untag_check<byte_array>(ctx->pop()) + 1);
65   ctx->push(tag_boolean(stat(path, &sb) >= 0));
66 }
67
68 bool move_file(const vm_char* path1, const vm_char* path2) {
69   int ret = 0;
70   do {
71     ret = rename((path1), (path2));
72   } while (ret < 0 && errno == EINTR);
73
74   return ret == 0;
75 }
76
77 segment::segment(cell size_, bool executable_p) {
78   size = size_;
79
80   int pagesize = getpagesize();
81
82   int prot;
83   if (executable_p)
84     prot = PROT_READ | PROT_WRITE | PROT_EXEC;
85   else
86     prot = PROT_READ | PROT_WRITE;
87
88   cell alloc_size = 2 * pagesize + size;
89 #if defined(__APPLE__) && defined(FACTOR_ARM64)  // FIXME: could be in header file
90   char* array = (char*)mmap(NULL, alloc_size, prot,
91                             MAP_ANON | MAP_PRIVATE | MAP_JIT, -1, 0);
92 #else
93   char* array = (char*)mmap(NULL, alloc_size, prot,
94                             MAP_ANON | MAP_PRIVATE, -1, 0);
95 #endif
96
97   if (array == (char*)-1)
98     fatal_error("Out of memory in mmap", alloc_size);
99
100   start = (cell)(array + pagesize);
101   end = start + size;
102
103   set_border_locked(true);
104 }
105
106 segment::~segment() {
107   int pagesize = getpagesize();
108   int retval = munmap((void*)(start - pagesize), 2 * pagesize + size);
109   if (retval)
110     fatal_error("Segment deallocation failed", 0);
111 }
112
113 void factor_vm::start_sampling_profiler_timer() {
114   struct itimerval timer;
115   memset((void*)&timer, 0, sizeof(struct itimerval));
116   timer.it_value.tv_usec = 1000000 / samples_per_second;
117   timer.it_interval.tv_usec = 1000000 / samples_per_second;
118   setitimer(ITIMER_REAL, &timer, NULL);
119 }
120
121 void factor_vm::end_sampling_profiler_timer() {
122   struct itimerval timer;
123   memset((void*)&timer, 0, sizeof(struct itimerval));
124   setitimer(ITIMER_REAL, &timer, NULL);
125 }
126
127 void factor_vm::dispatch_signal(void* uap, void(handler)()) {
128   dispatch_signal_handler((cell*)&UAP_STACK_POINTER(uap),
129                           (cell*)&UAP_PROGRAM_COUNTER(uap),
130                           (cell)FUNCTION_CODE_POINTER(handler));
131 }
132
133 void memory_signal_handler(int signal, siginfo_t* siginfo, void* uap) {
134
135   cell fault_addr = (cell)siginfo->si_addr;
136   cell fault_pc = (cell)UAP_PROGRAM_COUNTER(uap);
137   factor_vm* vm = current_vm();
138   vm->set_memory_protection_error(fault_addr, fault_pc);
139   vm->dispatch_signal(uap, factor::memory_signal_handler_impl);
140 }
141
142 void synchronous_signal_handler(int signal, siginfo_t* siginfo, void* uap) {
143   if (factor_vm::fatal_erroring_p)
144     return;
145
146   factor_vm* vm = current_vm_p();
147   if (!vm)
148     fatal_error("Foreign thread received signal", signal);
149   vm->signal_number = signal;
150   vm->dispatch_signal(uap, factor::synchronous_signal_handler_impl);
151 }
152
153 void safe_write_nonblock(int fd, void* data, ssize_t size);
154
155 static void enqueue_signal(factor_vm* vm, int signal) {
156   if (vm->signal_pipe_output != 0)
157     safe_write_nonblock(vm->signal_pipe_output, &signal, sizeof(int));
158 }
159
160 void enqueue_signal_handler(int signal, siginfo_t* siginfo, void* uap) {
161   if (factor_vm::fatal_erroring_p)
162     return;
163
164   factor_vm* vm = current_vm_p();
165   if (vm)
166     enqueue_signal(vm, signal);
167 }
168
169 void fep_signal_handler(int signal, siginfo_t* siginfo, void* uap) {
170   if (factor_vm::fatal_erroring_p)
171     return;
172
173   factor_vm* vm = current_vm_p();
174   if (vm) {
175     vm->enqueue_fep();
176     enqueue_signal(vm, signal);
177   } else
178     fatal_error("Foreign thread received signal", signal);
179 }
180
181 void sample_signal_handler(int signal, siginfo_t* siginfo, void* uap) {
182   factor_vm* vm = current_vm_p();
183   bool foreign_thread = false;
184   if (vm == NULL) {
185     foreign_thread = true;
186     vm = thread_vms.begin()->second;
187   }
188   if (atomic::load(&vm->sampling_profiler_p))
189     vm->enqueue_samples(1, (cell)UAP_PROGRAM_COUNTER(uap), foreign_thread);
190   else if (!foreign_thread)
191     enqueue_signal(vm, signal);
192 }
193
194 void ignore_signal_handler(int signal, siginfo_t* siginfo, void* uap) {}
195
196 void fpe_signal_handler(int signal, siginfo_t* siginfo, void* uap) {
197   factor_vm* vm = current_vm();
198   vm->signal_number = signal;
199   vm->signal_fpu_status = fpu_status(uap_fpu_status(uap));
200   uap_clear_fpu_status(uap);
201
202   vm->dispatch_signal(
203       uap, (siginfo->si_code == FPE_INTDIV || siginfo->si_code == FPE_INTOVF)
204                ? factor::synchronous_signal_handler_impl
205                : factor::fp_signal_handler_impl);
206 }
207
208 static void sigaction_safe(int signum, const struct sigaction* act,
209                            struct sigaction* oldact) {
210   int ret;
211   do {
212     ret = sigaction(signum, act, oldact);
213   } while (ret == -1 && errno == EINTR);
214
215   if (ret == -1)
216     fatal_error("sigaction failed", errno);
217 }
218
219 static void init_sigaction_with_handler(struct sigaction* act,
220                                         void (*handler)(int, siginfo_t*,
221                                                         void*)) {
222   memset(act, 0, sizeof(struct sigaction));
223   sigemptyset(&act->sa_mask);
224   act->sa_sigaction = handler;
225   act->sa_flags = SA_SIGINFO | SA_ONSTACK;
226 }
227
228 static void safe_pipe(int* in, int* out) {
229   int filedes[2];
230
231   if (pipe(filedes) < 0)
232     fatal_error("Error opening pipe", errno);
233
234   *in = filedes[0];
235   *out = filedes[1];
236
237   if (fcntl(*in, F_SETFD, FD_CLOEXEC) < 0)
238     fatal_error("Error with fcntl", errno);
239
240   if (fcntl(*out, F_SETFD, FD_CLOEXEC) < 0)
241     fatal_error("Error with fcntl", errno);
242 }
243
244 static void init_signal_pipe(factor_vm* vm) {
245   safe_pipe(&vm->signal_pipe_input, &vm->signal_pipe_output);
246
247   if (fcntl(vm->signal_pipe_output, F_SETFL, O_NONBLOCK) < 0)
248     fatal_error("Error with fcntl", errno);
249
250   vm->special_objects[OBJ_SIGNAL_PIPE] = tag_fixnum(vm->signal_pipe_input);
251 }
252
253 void factor_vm::unix_init_signals() {
254   init_signal_pipe(this);
255
256   signal_callstack_seg = new segment(callstack_size, false);
257
258   stack_t signal_callstack;
259   signal_callstack.ss_sp = (char*)signal_callstack_seg->start;
260   signal_callstack.ss_size = signal_callstack_seg->size;
261   signal_callstack.ss_flags = 0;
262
263   if (sigaltstack(&signal_callstack, (stack_t*)NULL) < 0)
264     fatal_error("sigaltstack() failed", 0);
265
266   {
267     struct sigaction memory_sigaction;
268     init_sigaction_with_handler(&memory_sigaction, memory_signal_handler);
269     sigaction_safe(SIGBUS, &memory_sigaction, NULL);
270     sigaction_safe(SIGSEGV, &memory_sigaction, NULL);
271     sigaction_safe(SIGTRAP, &memory_sigaction, NULL);
272   }
273
274   {
275     struct sigaction fpe_sigaction;
276     init_sigaction_with_handler(&fpe_sigaction, fpe_signal_handler);
277     sigaction_safe(SIGFPE, &fpe_sigaction, NULL);
278   }
279
280   {
281     struct sigaction synchronous_sigaction;
282     init_sigaction_with_handler(&synchronous_sigaction,
283                                 synchronous_signal_handler);
284     sigaction_safe(SIGILL, &synchronous_sigaction, NULL);
285     sigaction_safe(SIGABRT, &synchronous_sigaction, NULL);
286   }
287
288   {
289     struct sigaction enqueue_sigaction;
290     init_sigaction_with_handler(&enqueue_sigaction, enqueue_signal_handler);
291     sigaction_safe(SIGWINCH, &enqueue_sigaction, NULL);
292     sigaction_safe(SIGUSR1, &enqueue_sigaction, NULL);
293     sigaction_safe(SIGCONT, &enqueue_sigaction, NULL);
294     sigaction_safe(SIGURG, &enqueue_sigaction, NULL);
295     sigaction_safe(SIGIO, &enqueue_sigaction, NULL);
296     sigaction_safe(SIGPROF, &enqueue_sigaction, NULL);
297     sigaction_safe(SIGVTALRM, &enqueue_sigaction, NULL);
298 #ifdef SIGINFO
299     sigaction_safe(SIGINFO, &enqueue_sigaction, NULL);
300 #endif
301   }
302
303   handle_ctrl_c();
304
305   {
306     struct sigaction sample_sigaction;
307     init_sigaction_with_handler(&sample_sigaction, sample_signal_handler);
308     sigaction_safe(SIGALRM, &sample_sigaction, NULL);
309   }
310
311   // We don't use SA_IGN here because then the ignore action is inherited
312   // by subprocesses, which we don't want. There is a unit test in
313   // io.launcher.unix for this.
314   {
315     struct sigaction ignore_sigaction;
316     init_sigaction_with_handler(&ignore_sigaction, ignore_signal_handler);
317     sigaction_safe(SIGPIPE, &ignore_sigaction, NULL);
318     // We send SIGUSR2 to the stdin_loop thread to interrupt it on FEP
319     sigaction_safe(SIGUSR2, &ignore_sigaction, NULL);
320   }
321 }
322
323 // On Unix, shared fds such as stdin cannot be set to non-blocking mode
324 // (http://homepages.tesco.net/J.deBoynePollard/FGA/dont-set-shared-file-descriptors-to-non-blocking-mode.html)
325 // so we kludge around this by spawning a thread, which waits on a control pipe
326 // for a signal, upon receiving this signal it reads one block of data from
327 // stdin and writes it to a data pipe. Upon completion, it writes a 4-byte
328 // integer to the size pipe, indicating how much data was written to the data
329 // pipe.
330
331 // The read end of the size pipe can be set to non-blocking.
332 extern "C" {
333 int stdin_read;
334 int stdin_write;
335
336 int control_read;
337 int control_write;
338
339 int size_read;
340 int size_write;
341
342 bool stdin_thread_initialized_p = false;
343 THREADHANDLE stdin_thread;
344 pthread_mutex_t stdin_mutex;
345 }
346
347 void safe_close(int fd) {
348   if (close(fd) < 0)
349     fatal_error("error closing fd", errno);
350 }
351
352 bool check_write(int fd, void* data, ssize_t size) {
353   if (write(fd, data, size) == size)
354     return true;
355   if (errno == EINTR)
356     return check_write(fd, data, size);
357   return false;
358 }
359
360 void safe_write(int fd, void* data, ssize_t size) {
361   if (!check_write(fd, data, size))
362     fatal_error("error writing fd", errno);
363 }
364
365 void safe_write_nonblock(int fd, void* data, ssize_t size) {
366   if (!check_write(fd, data, size) && errno != EAGAIN)
367     fatal_error("error writing fd", errno);
368 }
369
370 bool safe_read(int fd, void* data, ssize_t size) {
371   ssize_t bytes = read(fd, data, size);
372   if (bytes < 0) {
373     if (errno == EINTR)
374       return safe_read(fd, data, size);
375     else {
376       fatal_error("error reading fd", errno);
377       return false;
378     }
379   } else
380     return (bytes == size);
381 }
382
383 void* stdin_loop(void* arg) {
384   unsigned char buf[4096];
385   bool loop_running = true;
386
387   sigset_t mask;
388   sigfillset(&mask);
389   sigdelset(&mask, SIGUSR2);
390   sigdelset(&mask, SIGTTIN);
391   sigdelset(&mask, SIGTERM);
392   sigdelset(&mask, SIGQUIT);
393   pthread_sigmask(SIG_SETMASK, &mask, NULL);
394
395   int unused;
396   pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &unused);
397   pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &unused);
398
399   while (loop_running) {
400     if (!safe_read(control_read, buf, 1))
401       break;
402
403     if (buf[0] != 'X')
404       fatal_error("stdin_loop: bad data on control fd", buf[0]);
405
406     for (;;) {
407       // If we fep, the parent thread will grab stdin_mutex and send us
408       // SIGUSR2 to interrupt the read() call.
409       pthread_mutex_lock(&stdin_mutex);
410       pthread_mutex_unlock(&stdin_mutex);
411       ssize_t bytes = read(0, buf, sizeof(buf));
412       if (bytes < 0) {
413         if (errno == EINTR)
414           continue;
415         else {
416           loop_running = false;
417           break;
418         }
419       } else if (bytes >= 0) {
420         safe_write(size_write, &bytes, sizeof(bytes));
421
422         if (!check_write(stdin_write, buf, bytes))
423           loop_running = false;
424         break;
425       }
426     }
427   }
428
429   safe_close(stdin_write);
430   safe_close(control_read);
431
432   return NULL;
433 }
434
435 void open_console() {
436   FACTOR_ASSERT(!stdin_thread_initialized_p);
437   safe_pipe(&control_read, &control_write);
438   safe_pipe(&size_read, &size_write);
439   safe_pipe(&stdin_read, &stdin_write);
440   stdin_thread = start_thread(stdin_loop, NULL);
441   stdin_thread_initialized_p = true;
442   pthread_mutex_init(&stdin_mutex, NULL);
443 }
444
445 // This method is used to kill the stdin_loop before exiting from factor.
446 // An Nvidia driver bug on Linux is the reason this has to be done, see:
447 //   http://www.nvnews.net/vbulletin/showthread.php?t=164619
448 void close_console() {
449   if (stdin_thread_initialized_p) {
450     pthread_cancel(stdin_thread);
451     pthread_join(stdin_thread, 0);
452   }
453 }
454
455 void lock_console() {
456   FACTOR_ASSERT(stdin_thread_initialized_p);
457   // Lock the stdin_mutex and send the stdin_loop thread a signal to interrupt
458   // any read() it has in progress. When the stdin loop iterates again, it will
459   // try to lock the same mutex and wait until unlock_console() is called.
460   pthread_mutex_lock(&stdin_mutex);
461   pthread_kill(stdin_thread, SIGUSR2);
462 }
463
464 void unlock_console() {
465   FACTOR_ASSERT(stdin_thread_initialized_p);
466   pthread_mutex_unlock(&stdin_mutex);
467 }
468
469 void ignore_ctrl_c() {
470   sig_t ret;
471   do {
472     ret = signal(SIGINT, SIG_DFL);
473   } while (ret == SIG_ERR && errno == EINTR);
474 }
475
476 void handle_ctrl_c() {
477   struct sigaction fep_sigaction;
478   init_sigaction_with_handler(&fep_sigaction, fep_signal_handler);
479   sigaction_safe(SIGINT, &fep_sigaction, NULL);
480 }
481
482 void factor_vm::primitive_disable_ctrl_break() {
483   stop_on_ctrl_break = false;
484 }
485
486 void factor_vm::primitive_enable_ctrl_break() {
487   stop_on_ctrl_break = true;
488 }
489
490 void abort() {
491   sig_t ret;
492   do {
493     ret = signal(SIGABRT, SIG_DFL);
494   } while (ret == SIG_ERR && errno == EINTR);
495
496   close_console();
497   ::abort();
498 }
499
500 }