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