ae80974789fd76c2f3cde94571ac1df206b83826
[sbcl.git] / src / runtime / bsd-os.c
1 /*
2  * OS-dependent routines for BSD-ish systems
3  *
4  * This file (along with os.h) exports an OS-independent interface to
5  * the operating system VM facilities. This interface looks a lot like
6  * the Mach interface (but simpler in some places). For some operating
7  * systems, a subset of these functions will have to be emulated.
8  */
9
10 /*
11  * This software is part of the SBCL system. See the README file for
12  * more information.
13  *
14  * This software is derived from the CMU CL system, which was
15  * written at Carnegie Mellon University and released into the
16  * public domain. The software is in the public domain and is
17  * provided with absolutely no warranty. See the COPYING and CREDITS
18  * files for more information.
19  */
20
21 #include <stdio.h>
22 #include <sys/param.h>
23 #include <sys/file.h>
24 #include <unistd.h>
25 #include <assert.h>
26 #include <errno.h>
27 #include "sbcl.h"
28 #include "./signal.h"
29 #include "os.h"
30 #include "arch.h"
31 #include "globals.h"
32 #include "interrupt.h"
33 #include "interr.h"
34 #include "lispregs.h"
35 #include "thread.h"
36 #include "runtime.h"
37 #include "genesis/static-symbols.h"
38 #include "genesis/fdefn.h"
39
40 #include <sys/types.h>
41 #include <signal.h>
42 /* #include <sys/sysinfo.h> */
43 #include "validate.h"
44 #if defined LISP_FEATURE_GENCGC
45 #include "gencgc-internal.h"
46 #endif
47 \f
48 os_vm_size_t os_vm_page_size;
49
50 #ifdef __NetBSD__
51 #include <sys/resource.h>
52 #include <sys/sysctl.h>
53 #include <string.h>
54 #include <sys/stat.h> /* For the stat-family wrappers. */
55
56 static void netbsd_init();
57 #endif /* __NetBSD__ */
58
59 #ifdef __FreeBSD__
60 #include <sys/sysctl.h>
61
62 static void freebsd_init();
63 #endif /* __FreeBSD__ */
64
65 void
66 os_init(char *argv[], char *envp[])
67 {
68     os_vm_page_size = getpagesize();
69
70 #ifdef __NetBSD__
71     netbsd_init();
72 #endif /* __NetBSD__ */
73 #ifdef __FreeBSD__
74     freebsd_init();
75 #endif /* __FreeBSD__ */
76 }
77
78 sigset_t *
79 os_context_sigmask_addr(os_context_t *context)
80 {
81     /* (Unlike most of the other context fields that we access, the
82      * signal mask field is a field of the basic, outermost context
83      * struct itself both in FreeBSD 4.0 and in OpenBSD 2.6.) */
84 #if defined(__FreeBSD__)  || defined(__NetBSD__) || defined(LISP_FEATURE_DARWIN)
85     return &context->uc_sigmask;
86 #elif defined (__OpenBSD__)
87     return &context->sc_mask;
88 #else
89 #error unsupported BSD variant
90 #endif
91 }
92
93 os_vm_address_t
94 os_validate(os_vm_address_t addr, os_vm_size_t len)
95 {
96     int flags = MAP_PRIVATE | MAP_ANON;
97
98     if (addr)
99         flags |= MAP_FIXED;
100
101     addr = mmap(addr, len, OS_VM_PROT_ALL, flags, -1, 0);
102
103     if (addr == MAP_FAILED) {
104         perror("mmap");
105         return NULL;
106     }
107
108     return addr;
109 }
110
111 void
112 os_invalidate(os_vm_address_t addr, os_vm_size_t len)
113 {
114     if (munmap(addr, len) == -1)
115         perror("munmap");
116 }
117
118 os_vm_address_t
119 os_map(int fd, int offset, os_vm_address_t addr, os_vm_size_t len)
120 {
121     addr = mmap(addr, len,
122                 OS_VM_PROT_ALL,
123                 MAP_PRIVATE | MAP_FILE | MAP_FIXED,
124                 fd, (off_t) offset);
125
126     if (addr == MAP_FAILED) {
127         perror("mmap");
128         lose("unexpected mmap(..) failure\n");
129     }
130
131     return addr;
132 }
133
134 void
135 os_protect(os_vm_address_t address, os_vm_size_t length, os_vm_prot_t prot)
136 {
137     if (mprotect(address, length, prot) == -1) {
138         perror("mprotect");
139     }
140 }
141 \f
142 static boolean
143 in_range_p(os_vm_address_t a, lispobj sbeg, size_t slen)
144 {
145     char* beg = (char*) sbeg;
146     char* end = (char*) sbeg + slen;
147     char* adr = (char*) a;
148     return (adr >= beg && adr < end);
149 }
150
151 boolean
152 is_valid_lisp_addr(os_vm_address_t addr)
153 {
154     struct thread *th;
155     if(in_range_p(addr, READ_ONLY_SPACE_START, READ_ONLY_SPACE_SIZE) ||
156        in_range_p(addr, STATIC_SPACE_START   , STATIC_SPACE_SIZE) ||
157        in_range_p(addr, DYNAMIC_SPACE_START  , dynamic_space_size))
158         return 1;
159     for_each_thread(th) {
160         if(((os_vm_address_t)th->control_stack_start <= addr) &&
161            (addr < (os_vm_address_t)th->control_stack_end))
162             return 1;
163         if(in_range_p(addr, (lispobj)th->binding_stack_start,
164                       BINDING_STACK_SIZE))
165             return 1;
166     }
167     return 0;
168 }
169 \f
170 /*
171  * any OS-dependent special low-level handling for signals
172  */
173
174 #if defined LISP_FEATURE_GENCGC
175
176 /*
177  * The GENCGC needs to be hooked into whatever signal is raised for
178  * page fault on this OS.
179  */
180 static void
181 memory_fault_handler(int signal, siginfo_t *siginfo, void *void_context
182 #if defined(LISP_FEATURE_FREEBSD) && defined(LISP_FEATURE_X86_64)
183 /* FreeBSD/amd64 stores fault address only in undocumented 4th arg. */
184                      ,void *fault_addr
185 #endif
186     )
187 {
188     os_context_t *context = arch_os_get_context(&void_context);
189 #if defined(LISP_FEATURE_FREEBSD) && defined(LISP_FEATURE_X86_64)
190     /* KLUDGE: Store fault address into si_addr for compatibilities. */
191     siginfo->si_addr = fault_addr;
192 #else
193     void *fault_addr = arch_get_bad_addr(signal, siginfo, context);
194 #endif
195
196 #if defined(LISP_FEATURE_RESTORE_TLS_SEGMENT_REGISTER_FROM_CONTEXT)
197     FSHOW_SIGNAL((stderr, "/ TLS: restoring fs: %p in memory_fault_handler\n",
198                   *CONTEXT_ADDR_FROM_STEM(fs)));
199     os_restore_tls_segment_register(context);
200 #endif
201
202     FSHOW((stderr, "Memory fault at: %p, PC: %p\n", fault_addr, *os_context_pc_addr(context)));
203
204     if (!gencgc_handle_wp_violation(fault_addr))
205         if(!handle_guard_page_triggered(context,fault_addr)) {
206 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
207             lisp_memory_fault_error(context, fault_addr);
208 #else
209             if (!interrupt_maybe_gc_int(signal, siginfo, context)) {
210                 interrupt_handle_now(signal, siginfo, context);
211             }
212 #if defined(LISP_FEATURE_DARWIN)
213             /* Work around G5 bug; fix courtesy gbyers */
214             DARWIN_FIX_CONTEXT(context);
215 #endif
216 #endif
217         }
218 }
219
220 void
221 os_install_interrupt_handlers(void)
222 {
223     SHOW("os_install_interrupt_handlers()/bsd-os/defined(GENCGC)");
224     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
225 #ifdef LISP_FEATURE_FREEBSD
226                                                  (__siginfohandler_t *)
227 #endif
228                                                  memory_fault_handler);
229 #ifdef SIG_MEMORY_FAULT2
230     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT2,
231 #ifdef LISP_FEATURE_FREEBSD
232                                                  (__siginfohandler_t *)
233 #endif
234                                                  memory_fault_handler);
235 #endif
236
237 #ifdef LISP_FEATURE_SB_THREAD
238     undoably_install_low_level_interrupt_handler(SIG_INTERRUPT_THREAD,
239                                                  interrupt_thread_handler);
240     undoably_install_low_level_interrupt_handler(SIG_STOP_FOR_GC,
241                                                  sig_stop_for_gc_handler);
242 #ifdef SIG_RESUME_FROM_GC
243     undoably_install_low_level_interrupt_handler(SIG_RESUME_FROM_GC,
244                                                  sig_stop_for_gc_handler);
245 #endif
246 #endif
247
248     SHOW("leaving os_install_interrupt_handlers()");
249 }
250
251 #else /* Currently PPC/Darwin/Cheney only */
252
253 static void
254 sigsegv_handler(int signal, siginfo_t *info, void* void_context)
255 {
256     os_context_t *context = arch_os_get_context(&void_context);
257     unsigned int pc =  (unsigned int *)(*os_context_pc_addr(context));
258     os_vm_address_t addr;
259
260     addr = arch_get_bad_addr(signal,info,context);
261     if(!interrupt_maybe_gc(signal, info, context))
262         if(!handle_guard_page_triggered(context,addr))
263             interrupt_handle_now(signal, info, context);
264     /* Work around G5 bug; fix courtesy gbyers */
265     DARWIN_FIX_CONTEXT(context);
266 }
267
268 void
269 os_install_interrupt_handlers(void)
270 {
271     SHOW("os_install_interrupt_handlers()/bsd-os/!defined(GENCGC)");
272     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
273                                                  sigsegv_handler);
274 #ifdef SIG_MEMORY_FAULT2
275     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT2,
276                                                  sigsegv_handler);
277 #endif
278 }
279
280 #endif /* defined GENCGC */
281
282 #ifdef __NetBSD__
283 static void netbsd_init()
284 {
285     struct rlimit rl;
286     int mib[2], osrev;
287     size_t len;
288
289     /* Are we running on a sufficiently functional kernel? */
290     mib[0] = CTL_KERN;
291     mib[1] = KERN_OSREV;
292
293     len = sizeof(osrev);
294     sysctl(mib, 2, &osrev, &len, NULL, 0);
295
296     /* If we're older than 2.0... */
297     if (osrev < 200000000) {
298         fprintf(stderr, "osrev = %d (needed at least 200000000).\n", osrev);
299         lose("NetBSD kernel too old to run sbcl.\n");
300     }
301
302     /* NetBSD counts mmap()ed space against the process's data size limit,
303      * so yank it up. This might be a nasty thing to do? */
304     getrlimit (RLIMIT_DATA, &rl);
305     /* Amazingly for such a new port, the provenance and meaning of
306        this number are unknown.  It might just mean REALLY_BIG_LIMIT,
307        or possibly it should be calculated from dynamic space size.
308        -- CSR, 2004-04-08 */
309     rl.rlim_cur = 1073741824;
310     if (setrlimit (RLIMIT_DATA, &rl) < 0) {
311         fprintf (stderr,
312                  "RUNTIME WARNING: unable to raise process data size limit:\n\
313   %s.\n\
314 The system may fail to start.\n",
315                  strerror(errno));
316     }
317 }
318
319 /* The stat() routines in NetBSD's C library are compatibility
320    wrappers for some very old version of the stat buffer structure.
321    Programs must be processed by the C toolchain in order to get an
322    up-to-date definition of the stat() routine.  These wrappers are
323    used only in sb-posix, as of 2006-10-15. -- RMK */
324 int _stat(const char *path, struct stat *sb) {
325   return (stat(path, sb));
326 }
327
328 int _lstat(const char *path, struct stat *sb) {
329   return (lstat(path, sb));
330 }
331
332 int _fstat(int fd, struct stat *sb) {
333   return (fstat(fd, sb));
334 }
335
336
337 #endif /* __NetBSD__ */
338
339 #ifdef __FreeBSD__
340 static void freebsd_init()
341 {
342     /* Quote from sbcl-devel (NIIMI Satoshi): "Some OSes, like FreeBSD
343      * 4.x with GENERIC kernel, does not enable SSE support even on
344      * SSE capable CPUs". Detect this situation and skip the
345      * fast_bzero sse/base selection logic that's normally done in
346      * x86-assem.S.
347      */
348 #ifdef LISP_FEATURE_X86
349     size_t len;
350     int instruction_sse;
351
352     len = sizeof(instruction_sse);
353     if (sysctlbyname("hw.instruction_sse", &instruction_sse, &len, NULL, 0) == 0
354         && instruction_sse != 0) {
355         /* Use the SSE detector */
356         fast_bzero_pointer = fast_bzero_detect;
357     }
358 #endif /* LISP_FEATURE_X86 */
359 }
360 #endif /* __FreeBSD__ */
361
362 #ifdef LISP_FEATURE_DARWIN
363 /* defined in ppc-darwin-os.c instead */
364 #elif defined(LISP_FEATURE_FREEBSD)
365 #ifndef KERN_PROC_PATHNAME
366 #define KERN_PROC_PATHNAME 12
367 #endif
368
369 extern int getosreldate(void);
370
371 char *
372 os_get_runtime_executable_path()
373 {
374     char path[PATH_MAX + 1];
375
376     if (getosreldate() >= 600024) {
377         /* KERN_PROC_PATHNAME is available */
378         size_t len = PATH_MAX + 1;
379         int mib[4];
380
381         mib[0] = CTL_KERN;
382         mib[1] = KERN_PROC;
383         mib[2] = KERN_PROC_PATHNAME;
384         mib[3] = -1;
385         if (sysctl(mib, 4, &path, &len, NULL, 0) != 0)
386             return NULL;
387     } else {
388         int size;
389         size = readlink("/proc/curproc/file", path, sizeof(path) - 1);
390         if (size < 0)
391             return NULL;
392         path[size] = '\0';
393     }
394     if (strcmp(path, "unknown") == 0)
395         return NULL;
396     return copied_string(path);
397 }
398 #else /* Not DARWIN or FREEBSD */
399 char *
400 os_get_runtime_executable_path()
401 {
402     return NULL;
403 }
404 #endif