1.0.1.1:
[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 #elif defined(__FreeBSD__)
73     freebsd_init();
74 #endif
75 }
76
77 sigset_t *
78 os_context_sigmask_addr(os_context_t *context)
79 {
80     /* (Unlike most of the other context fields that we access, the
81      * signal mask field is a field of the basic, outermost context
82      * struct itself both in FreeBSD 4.0 and in OpenBSD 2.6.) */
83 #if defined(__FreeBSD__)  || defined(__NetBSD__) || defined(LISP_FEATURE_DARWIN)
84     return &context->uc_sigmask;
85 #elif defined (__OpenBSD__)
86     return &context->sc_mask;
87 #else
88 #error unsupported BSD variant
89 #endif
90 }
91
92 os_vm_address_t
93 os_validate(os_vm_address_t addr, os_vm_size_t len)
94 {
95     int flags = MAP_PRIVATE | MAP_ANON;
96
97     if (addr)
98         flags |= MAP_FIXED;
99
100     addr = mmap(addr, len, OS_VM_PROT_ALL, flags, -1, 0);
101
102     if (addr == MAP_FAILED) {
103         perror("mmap");
104         return NULL;
105     }
106
107     return addr;
108 }
109
110 void
111 os_invalidate(os_vm_address_t addr, os_vm_size_t len)
112 {
113     if (munmap(addr, len) == -1)
114         perror("munmap");
115 }
116
117 os_vm_address_t
118 os_map(int fd, int offset, os_vm_address_t addr, os_vm_size_t len)
119 {
120     addr = mmap(addr, len,
121                 OS_VM_PROT_ALL,
122                 MAP_PRIVATE | MAP_FILE | MAP_FIXED,
123                 fd, (off_t) offset);
124
125     if (addr == MAP_FAILED) {
126         perror("mmap");
127         lose("unexpected mmap(..) failure\n");
128     }
129
130     return addr;
131 }
132
133 void
134 os_protect(os_vm_address_t address, os_vm_size_t length, os_vm_prot_t prot)
135 {
136     if (mprotect(address, length, prot) == -1) {
137         perror("mprotect");
138     }
139 }
140 \f
141 static boolean
142 in_range_p(os_vm_address_t a, lispobj sbeg, size_t slen)
143 {
144     char* beg = (char*) sbeg;
145     char* end = (char*) sbeg + slen;
146     char* adr = (char*) a;
147     return (adr >= beg && adr < end);
148 }
149
150 boolean
151 is_valid_lisp_addr(os_vm_address_t addr)
152 {
153     struct thread *th;
154     if(in_range_p(addr, READ_ONLY_SPACE_START, READ_ONLY_SPACE_SIZE) ||
155        in_range_p(addr, STATIC_SPACE_START   , STATIC_SPACE_SIZE) ||
156        in_range_p(addr, DYNAMIC_SPACE_START  , dynamic_space_size))
157         return 1;
158     for_each_thread(th) {
159         if(((os_vm_address_t)th->control_stack_start <= addr) &&
160            (addr < (os_vm_address_t)th->control_stack_end))
161             return 1;
162         if(in_range_p(addr, (lispobj)th->binding_stack_start,
163                       BINDING_STACK_SIZE))
164             return 1;
165     }
166     return 0;
167 }
168 \f
169 /*
170  * any OS-dependent special low-level handling for signals
171  */
172
173 #if defined LISP_FEATURE_GENCGC
174
175 /*
176  * The GENCGC needs to be hooked into whatever signal is raised for
177  * page fault on this OS.
178  */
179
180 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 #if defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
221 void
222 mach_error_memory_fault_handler(int signal, siginfo_t *siginfo, void *void_context) {
223     lose("Unhandled memory fault. Exiting.");
224 }
225 #endif
226
227 void
228 os_install_interrupt_handlers(void)
229 {
230     SHOW("os_install_interrupt_handlers()/bsd-os/defined(GENCGC)");
231 #if defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
232     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
233                                                  mach_error_memory_fault_handler);
234 #else
235     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
236 #ifdef LISP_FEATURE_FREEBSD
237                                                  (__siginfohandler_t *)
238 #endif
239                                                  memory_fault_handler);
240 #ifdef SIG_MEMORY_FAULT2
241     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT2,
242 #ifdef LISP_FEATURE_FREEBSD
243                                                  (__siginfohandler_t *)
244 #endif
245                                                  memory_fault_handler);
246 #endif
247 #endif
248
249 #ifdef LISP_FEATURE_SB_THREAD
250     undoably_install_low_level_interrupt_handler(SIG_INTERRUPT_THREAD,
251                                                  interrupt_thread_handler);
252     undoably_install_low_level_interrupt_handler(SIG_STOP_FOR_GC,
253                                                  sig_stop_for_gc_handler);
254 #ifdef SIG_RESUME_FROM_GC
255     undoably_install_low_level_interrupt_handler(SIG_RESUME_FROM_GC,
256                                                  sig_stop_for_gc_handler);
257 #endif
258 #endif
259     SHOW("leaving os_install_interrupt_handlers()");
260 }
261
262 #else /* Currently PPC/Darwin/Cheney only */
263
264 static void
265 sigsegv_handler(int signal, siginfo_t *info, void* void_context)
266 {
267     os_context_t *context = arch_os_get_context(&void_context);
268     unsigned int pc =  (unsigned int *)(*os_context_pc_addr(context));
269     os_vm_address_t addr;
270
271     addr = arch_get_bad_addr(signal,info,context);
272     if(!interrupt_maybe_gc(signal, info, context))
273         if(!handle_guard_page_triggered(context,addr))
274             interrupt_handle_now(signal, info, context);
275     /* Work around G5 bug; fix courtesy gbyers */
276     DARWIN_FIX_CONTEXT(context);
277 }
278
279 void
280 os_install_interrupt_handlers(void)
281 {
282     SHOW("os_install_interrupt_handlers()/bsd-os/!defined(GENCGC)");
283     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
284                                                  sigsegv_handler);
285 #ifdef SIG_MEMORY_FAULT2
286     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT2,
287                                                  sigsegv_handler);
288 #endif
289 }
290
291 #endif /* defined GENCGC */
292
293 #ifdef __NetBSD__
294 static void netbsd_init()
295 {
296     struct rlimit rl;
297     int mib[2], osrev;
298     size_t len;
299
300     /* Are we running on a sufficiently functional kernel? */
301     mib[0] = CTL_KERN;
302     mib[1] = KERN_OSREV;
303
304     len = sizeof(osrev);
305     sysctl(mib, 2, &osrev, &len, NULL, 0);
306
307     /* If we're older than 2.0... */
308     if (osrev < 200000000) {
309         fprintf(stderr, "osrev = %d (needed at least 200000000).\n", osrev);
310         lose("NetBSD kernel too old to run sbcl.\n");
311     }
312
313     /* NetBSD counts mmap()ed space against the process's data size limit,
314      * so yank it up. This might be a nasty thing to do? */
315     getrlimit (RLIMIT_DATA, &rl);
316     /* Amazingly for such a new port, the provenance and meaning of
317        this number are unknown.  It might just mean REALLY_BIG_LIMIT,
318        or possibly it should be calculated from dynamic space size.
319        -- CSR, 2004-04-08 */
320     rl.rlim_cur = 1073741824;
321     if (setrlimit (RLIMIT_DATA, &rl) < 0) {
322         fprintf (stderr,
323                  "RUNTIME WARNING: unable to raise process data size limit:\n\
324   %s.\n\
325 The system may fail to start.\n",
326                  strerror(errno));
327     }
328 }
329
330 /* The stat() routines in NetBSD's C library are compatibility
331    wrappers for some very old version of the stat buffer structure.
332    Programs must be processed by the C toolchain in order to get an
333    up-to-date definition of the stat() routine.  These wrappers are
334    used only in sb-posix, as of 2006-10-15. -- RMK */
335 int _stat(const char *path, struct stat *sb) {
336   return (stat(path, sb));
337 }
338
339 int _lstat(const char *path, struct stat *sb) {
340   return (lstat(path, sb));
341 }
342
343 int _fstat(int fd, struct stat *sb) {
344   return (fstat(fd, sb));
345 }
346
347
348 #endif /* __NetBSD__ */
349
350 #ifdef __FreeBSD__
351 static void freebsd_init()
352 {
353     /* Quote from sbcl-devel (NIIMI Satoshi): "Some OSes, like FreeBSD
354      * 4.x with GENERIC kernel, does not enable SSE support even on
355      * SSE capable CPUs". Detect this situation and skip the
356      * fast_bzero sse/base selection logic that's normally done in
357      * x86-assem.S.
358      */
359 #ifdef LISP_FEATURE_X86
360     size_t len;
361     int instruction_sse;
362
363     len = sizeof(instruction_sse);
364     if (sysctlbyname("hw.instruction_sse", &instruction_sse, &len, NULL, 0) == 0
365         && instruction_sse != 0) {
366         /* Use the SSE detector */
367         fast_bzero_pointer = fast_bzero_detect;
368     }
369 #endif /* LISP_FEATURE_X86 */
370 }
371 #endif /* __FreeBSD__ */
372
373 #ifdef LISP_FEATURE_DARWIN
374 /* defined in ppc-darwin-os.c instead */
375 #elif defined(LISP_FEATURE_FREEBSD)
376 #ifndef KERN_PROC_PATHNAME
377 #define KERN_PROC_PATHNAME 12
378 #endif
379
380 extern int getosreldate(void);
381
382 char *
383 os_get_runtime_executable_path()
384 {
385     char path[PATH_MAX + 1];
386
387     if (getosreldate() >= 600024) {
388         /* KERN_PROC_PATHNAME is available */
389         size_t len = PATH_MAX + 1;
390         int mib[4];
391
392         mib[0] = CTL_KERN;
393         mib[1] = KERN_PROC;
394         mib[2] = KERN_PROC_PATHNAME;
395         mib[3] = -1;
396         if (sysctl(mib, 4, &path, &len, NULL, 0) != 0)
397             return NULL;
398     } else {
399         int size;
400         size = readlink("/proc/curproc/file", path, sizeof(path) - 1);
401         if (size < 0)
402             return NULL;
403         path[size] = '\0';
404     }
405     if (strcmp(path, "unknown") == 0)
406         return NULL;
407     return copied_string(path);
408 }
409 #else /* Not DARWIN or FREEBSD */
410 char *
411 os_get_runtime_executable_path()
412 {
413     return NULL;
414 }
415 #endif