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