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