6c77f5a646b07108c838feba472306e0ef77ee0a
[sbcl.git] / src / runtime / linux-os.c
1 /*
2  * the Linux incarnation of OS-dependent routines.  See also
3  * $(sbcl_arch)-linux-os.c
4  *
5  * This file (along with os.h) exports an OS-independent interface to
6  * the operating system VM facilities. Surprise surprise, this
7  * interface looks a lot like the Mach interface (but simpler in some
8  * places). For some operating systems, a subset of these functions
9  * will have to be emulated.
10  */
11
12 /*
13  * This software is part of the SBCL system. See the README file for
14  * more information.
15  *
16  * This software is derived from the CMU CL system, which was
17  * written at Carnegie Mellon University and released into the
18  * public domain. The software is in the public domain and is
19  * provided with absolutely no warranty. See the COPYING and CREDITS
20  * files for more information.
21  */
22
23 #include <stdio.h>
24 #include <sys/param.h>
25 #include <sys/file.h>
26 #include "sbcl.h"
27 #include "./signal.h"
28 #include "os.h"
29 #include "arch.h"
30 #include "globals.h"
31 #include "interrupt.h"
32 #include "interr.h"
33 #include "lispregs.h"
34 #include "runtime.h"
35 #include "genesis/static-symbols.h"
36 #include "genesis/fdefn.h"
37 #include <sys/socket.h>
38 #include <sys/utsname.h>
39
40 #include <sys/types.h>
41 #include <signal.h>
42 /* #include <sys/sysinfo.h> */
43 #include <sys/time.h>
44 #include <sys/stat.h>
45 #include <unistd.h>
46 #include <linux/version.h>
47
48 #include "validate.h"
49 #include "thread.h"
50 #include "gc.h"
51 #if defined LISP_FEATURE_GENCGC
52 #include "gencgc-internal.h"
53 #endif
54
55 #ifdef LISP_FEATURE_LINUX
56 /* Linux "man personality" on Debian 3.1 doesn't say what Linux
57  * version introduced support for #include <sys/personality.h>, but
58  * judging from jesnell's code for sbcl-0.9.4, 'twas Linux 2.6. */
59 #define PERSONALITY_SUPPORTED_AT_COMPILE_TIME \
60   (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0))
61 #else
62 /* Linux "man personality" on Debian 3.1 says that <sys/personality.h>
63  * stuff is Linux-only. */
64 #define PERSONALITY_SUPPORTED_AT_COMPILE_TIME 0
65 #endif
66 #if PERSONALITY_SUPPORTED_AT_COMPILE_TIME
67 #include <sys/personality.h>
68 #endif
69
70 size_t os_vm_page_size;
71
72 #ifdef LISP_FEATURE_SB_THREAD
73 #include <sys/syscall.h>
74 #include <unistd.h>
75 #include <errno.h>
76
77 /* values taken from the kernel's linux/futex.h.  This header file
78    doesn't exist in userspace, which is our excuse for not grovelling
79    them automatically */
80 #define FUTEX_WAIT (0)
81 #define FUTEX_WAKE (1)
82 #define FUTEX_FD (2)
83 #define FUTEX_REQUEUE (3)
84
85 #define sys_futex sbcl_sys_futex
86 static inline int sys_futex (void *futex, int op, int val, struct timespec *rel)
87 {
88     return syscall (SYS_futex, futex, op, val, rel);
89 }
90
91 int
92 futex_wait(int *lock_word, int oldval)
93 {
94     int t= sys_futex(lock_word,FUTEX_WAIT,oldval, 0);
95     return t;
96 }
97
98 int
99 futex_wake(int *lock_word, int n)
100 {
101     return sys_futex(lock_word,FUTEX_WAKE,n,0);
102 }
103 #endif
104
105 \f
106 int linux_sparc_siginfo_bug = 0;
107 int linux_no_threads_p = 0;
108
109 #ifdef LISP_FEATURE_SB_THREAD
110 int isnptl (void)
111 {
112   size_t n = confstr (_CS_GNU_LIBPTHREAD_VERSION, NULL, 0);
113   if (n > 0)
114     {
115       char *buf = alloca (n);
116       confstr (_CS_GNU_LIBPTHREAD_VERSION, buf, n);
117       if (strstr (buf, "NPTL"))
118         return 1;
119     }
120   return 0;
121 }
122 #endif
123
124 void
125 os_init(char *argv[], char *envp[])
126 {
127     /* Conduct various version checks: do we have enough mmap(), is
128      * this a sparc running 2.2, can we do threads? */
129 #ifdef LISP_FEATURE_SB_THREAD
130     int *futex=0;
131 #endif
132     struct utsname name;
133     int major_version;
134     int minor_version;
135     char *p;
136     uname(&name);
137     p=name.release;
138     major_version = atoi(p);
139     p=strchr(p,'.')+1;
140     minor_version = atoi(p);
141     if (major_version<2) {
142         lose("linux kernel version too old: major version=%d (can't run in version < 2.0.0)",
143              major_version);
144     }
145     if (!(major_version>2 || minor_version >= 4)) {
146 #ifdef LISP_FEATURE_SPARC
147         FSHOW((stderr,"linux kernel %d.%d predates 2.4;\n enabling workarounds for SPARC kernel bugs in signal handling.\n", major_version,minor_version));
148         linux_sparc_siginfo_bug = 1;
149 #endif
150     }
151 #ifdef LISP_FEATURE_SB_THREAD
152     futex_wait(futex,-1);
153     if(errno==ENOSYS) {
154        lose("This version of SBCL is compiled with threading support, but your kernel is too old to support this.\n\
155 Please use a more recent kernel or a version of SBCL without threading support.\n");
156     }
157     if(! isnptl()) {
158        lose("This version of SBCL only works correctly with the NPTL threading library. Please use a newer glibc, use an older SBCL, or stop using LD_ASSUME_KERNEL");
159     }
160 #endif
161     os_vm_page_size = getpagesize();
162
163 #ifdef LISP_FEATURE_LINUX
164     /* KLUDGE: Disable memory randomization on new Linux kernels
165      * by setting a personality flag and re-executing. (We need
166      * to re-execute, since the memory maps that can conflict with
167      * the SBCL spaces have already been done at this point).
168      */
169     if ((major_version == 2 && minor_version >= 6)
170         || major_version >= 3) { /* i.e., if running on Linux which is new
171                                   * enough to have <sys/personality.h> */
172 #if PERSONALITY_SUPPORTED_AT_COMPILE_TIME
173         {
174             long pers = personality(-1);
175             /* 0x40000 aka. ADDR_NO_RANDOMIZE */
176             if (!(pers & 0x40000)) {
177                 if (personality(pers | 0x40000) != -1) {
178                     /* Use /proc/self/exe instead of trying to figure out
179                      * the executable path from PATH and argv[0], since
180                      * that's unreliable. We follow the symlink instead of
181                      * executing the file directly in order to prevent top
182                      * from displaying the name of the process as "exe". */
183                     char runtime[PATH_MAX+1];
184                     int i = readlink("/proc/self/exe", runtime, PATH_MAX);
185                     if (i != -1) {
186                         runtime[i] = '\0';
187                         execve(runtime, argv, envp);
188                     }
189                 }
190                 /* Either changing the personality or execve() failed. Either
191                  * way we might as well continue, and hope that the random
192                  * memory maps are ok this time around.
193                  */
194                 fprintf(stderr, "WARNING: Couldn't re-execute SBCL with the proper personality flags (maybe /proc isn't mounted?). Trying to continue anyway.\n");
195             }
196         }
197 #else
198         /* KLUDGE: This doesn't seem like a particularly clever thing
199          * to do, but I can't think of anything better at the moment.
200          * One rigorously-correct-seeming possibility would be to have
201          * personality() stuff be suppressed only at the explicit
202          * request of the builder (in customize-target-features.lisp),
203          * and then simply continue here without error, on the theory
204          * that the builder knew what he was doing. But even to me
205          * that seems like a lot of trouble to put the user to in the
206          * common case when he's building on the same system he's
207          * running on. -- WHN */
208         lose("This SBCL executable was built on some system too old to have <sys/personality.h>, and running it on this newer system which has <sys/personality.h> is unsupported. Consider rebuilding SBCL from source on the new system.");
209 #endif
210     }
211 }
212 #endif
213
214
215 #ifdef LISP_FEATURE_ALPHA
216 /* The Alpha is a 64 bit CPU.  SBCL is a 32 bit application.  Due to all
217  * the places that assume we can get a pointer into a fixnum with no
218  * information loss, we have to make sure it allocates all its ram in the
219  * 0-2Gb region.  */
220
221 static void * under_2gb_free_pointer=DYNAMIC_1_SPACE_END;
222 #endif
223
224 os_vm_address_t
225 os_validate(os_vm_address_t addr, os_vm_size_t len)
226 {
227     int flags =  MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
228     os_vm_address_t actual;
229
230 #ifdef LISP_FEATURE_ALPHA
231     if (!addr) {
232         addr=under_2gb_free_pointer;
233     }
234 #endif
235     actual = mmap(addr, len, OS_VM_PROT_ALL, flags, -1, 0);
236     if (actual == MAP_FAILED || (addr && (addr!=actual))) {
237         perror("mmap");
238         return 0;               /* caller should check this */
239     }
240
241 #ifdef LISP_FEATURE_ALPHA
242
243     len=(len+(os_vm_page_size-1))&(~(os_vm_page_size-1));
244     under_2gb_free_pointer+=len;
245 #endif
246
247     return actual;
248 }
249
250 void
251 os_invalidate(os_vm_address_t addr, os_vm_size_t len)
252 {
253     if (munmap(addr,len) == -1) {
254         perror("munmap");
255     }
256 }
257
258 os_vm_address_t
259 os_map(int fd, int offset, os_vm_address_t addr, os_vm_size_t len)
260 {
261     os_vm_address_t actual;
262
263     actual = mmap(addr, len, OS_VM_PROT_ALL, MAP_PRIVATE | MAP_FIXED,
264                   fd, (off_t) offset);
265     if (actual == MAP_FAILED || (addr && (addr != actual))) {
266         perror("mmap");
267         lose("unexpected mmap(..) failure");
268     }
269
270     return actual;
271 }
272
273 void
274 os_protect(os_vm_address_t address, os_vm_size_t length, os_vm_prot_t prot)
275 {
276     if (mprotect(address, length, prot) == -1) {
277         perror("mprotect");
278     }
279 }
280 \f
281 boolean
282 is_valid_lisp_addr(os_vm_address_t addr)
283 {
284     struct thread *th;
285     size_t ad = (size_t) addr;
286
287     if ((READ_ONLY_SPACE_START <= ad && ad < READ_ONLY_SPACE_END)
288         || (STATIC_SPACE_START <= ad && ad < STATIC_SPACE_END)
289 #if defined LISP_FEATURE_GENCGC
290         || (DYNAMIC_SPACE_START <= ad && ad < DYNAMIC_SPACE_END)
291 #else
292         || (DYNAMIC_0_SPACE_START <= ad && ad < DYNAMIC_0_SPACE_END)
293         || (DYNAMIC_1_SPACE_START <= ad && ad < DYNAMIC_1_SPACE_END)
294 #endif
295         )
296         return 1;
297     for_each_thread(th) {
298         if((size_t)(th->control_stack_start) <= ad
299            && ad < (size_t)(th->control_stack_end))
300             return 1;
301         if((size_t)(th->binding_stack_start) <= ad
302            && ad < (size_t)(th->binding_stack_start + BINDING_STACK_SIZE))
303             return 1;
304     }
305     return 0;
306 }
307 \f
308 /*
309  * any OS-dependent special low-level handling for signals
310  */
311
312
313 #if defined LISP_FEATURE_GENCGC
314
315 /*
316  * The GENCGC needs to be hooked into whatever signal is raised for
317  * page fault on this OS.
318  */
319 static void
320 sigsegv_handler(int signal, siginfo_t *info, void* void_context)
321 {
322     os_context_t *context = arch_os_get_context(&void_context);
323     void* fault_addr = (void*)info->si_addr;
324     if (!gencgc_handle_wp_violation(fault_addr))
325         if(!handle_guard_page_triggered(context,fault_addr))
326 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
327             arrange_return_to_lisp_function(context, SymbolFunction(MEMORY_FAULT_ERROR));
328 #else
329             interrupt_handle_now(signal, info, context);
330 #endif
331 }
332
333 #else
334
335 static void
336 sigsegv_handler(int signal, siginfo_t *info, void* void_context)
337 {
338     os_context_t *context = arch_os_get_context(&void_context);
339     os_vm_address_t addr = arch_get_bad_addr(signal,info,context);
340
341 #ifdef LISP_FEATURE_ALPHA
342     /* Alpha stuff: This is the end of a pseudo-atomic section during
343        which a signal was received.  We must deal with the pending
344        interrupt (see also interrupt.c, ../code/interrupt.lisp)
345
346        (how we got here: when interrupting, we set bit 63 in reg_ALLOC.
347        At the end of the atomic section we tried to write to reg_ALLOC,
348        got a SIGSEGV (there's nothing mapped there) so ended up here. */
349     if (addr != NULL &&
350         *os_context_register_addr(context,reg_ALLOC) & (1L<<63)){
351         *os_context_register_addr(context,reg_ALLOC) -= (1L<<63);
352         interrupt_handle_pending(context);
353         return;
354     }
355 #endif
356
357     if(!interrupt_maybe_gc(signal, info, context))
358         if(!handle_guard_page_triggered(context,addr))
359             interrupt_handle_now(signal, info, context);
360 }
361 #endif
362
363 void
364 os_install_interrupt_handlers(void)
365 {
366     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
367                                                  sigsegv_handler);
368 #ifdef LISP_FEATURE_SB_THREAD
369     undoably_install_low_level_interrupt_handler(SIG_INTERRUPT_THREAD,
370                                                  interrupt_thread_handler);
371     undoably_install_low_level_interrupt_handler(SIG_STOP_FOR_GC,
372                                                  sig_stop_for_gc_handler);
373 #endif
374 }