don't stack-allocate specialized vectors on non-conservtive control stacks
[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 #include <dirent.h>   /* For the opendir()/readdir() wrappers */
56 #include <sys/socket.h> /* For the socket() wrapper */
57 static void netbsd_init();
58 #endif /* __NetBSD__ */
59
60 #ifdef __FreeBSD__
61 #include <sys/sysctl.h>
62 #if defined(LISP_FEATURE_SB_THREAD) && !defined(LISP_FEATURE_SB_PTHREAD_FUTEX)
63 #include <sys/umtx.h>
64 #endif
65
66 static void freebsd_init();
67 #endif /* __FreeBSD__ */
68
69 #ifdef __OpenBSD__
70 #include <sys/types.h>
71 #include <sys/resource.h>
72 #include <sys/stat.h>
73 #include <sys/sysctl.h>
74 #include <dlfcn.h>
75 #ifdef LISP_FEATURE_X86
76 #include <machine/cpu.h>
77 #endif
78
79 static void openbsd_init();
80 #endif
81
82 void
83 os_init(char *argv[], char *envp[])
84 {
85     os_vm_page_size = BACKEND_PAGE_BYTES;
86
87 #ifdef __NetBSD__
88     netbsd_init();
89 #elif defined(__FreeBSD__)
90     freebsd_init();
91 #elif defined(__OpenBSD__)
92     openbsd_init();
93 #elif defined(LISP_FEATURE_DARWIN)
94     darwin_init();
95 #endif
96 }
97
98 sigset_t *
99 os_context_sigmask_addr(os_context_t *context)
100 {
101     /* (Unlike most of the other context fields that we access, the
102      * signal mask field is a field of the basic, outermost context
103      * struct itself both in FreeBSD 4.0 and in OpenBSD 2.6.) */
104 #if defined(__FreeBSD__)  || defined(__NetBSD__) || defined(LISP_FEATURE_DARWIN)
105     return &context->uc_sigmask;
106 #elif defined (__OpenBSD__)
107     return &context->sc_mask;
108 #else
109 #error unsupported BSD variant
110 #endif
111 }
112
113 os_vm_address_t
114 os_validate(os_vm_address_t addr, os_vm_size_t len)
115 {
116     int flags = MAP_PRIVATE | MAP_ANON;
117
118     if (addr)
119         flags |= MAP_FIXED;
120
121     addr = mmap(addr, len, OS_VM_PROT_ALL, flags, -1, 0);
122
123     if (addr == MAP_FAILED) {
124         perror("mmap");
125         return NULL;
126     }
127
128     return addr;
129 }
130
131 void
132 os_invalidate(os_vm_address_t addr, os_vm_size_t len)
133 {
134     if (munmap(addr, len) == -1)
135         perror("munmap");
136 }
137
138 os_vm_address_t
139 os_map(int fd, int offset, os_vm_address_t addr, os_vm_size_t len)
140 {
141     addr = mmap(addr, len,
142                 OS_VM_PROT_ALL,
143                 MAP_PRIVATE | MAP_FILE | MAP_FIXED,
144                 fd, (off_t) offset);
145
146     if (addr == MAP_FAILED) {
147         perror("mmap");
148         lose("unexpected mmap(..) failure\n");
149     }
150
151     return addr;
152 }
153
154 void
155 os_protect(os_vm_address_t address, os_vm_size_t length, os_vm_prot_t prot)
156 {
157     if (mprotect(address, length, prot) == -1) {
158         perror("mprotect");
159     }
160 }
161 \f
162 static boolean
163 in_range_p(os_vm_address_t a, lispobj sbeg, size_t slen)
164 {
165     char* beg = (char*) sbeg;
166     char* end = (char*) sbeg + slen;
167     char* adr = (char*) a;
168     return (adr >= beg && adr < end);
169 }
170
171 boolean
172 is_valid_lisp_addr(os_vm_address_t addr)
173 {
174     struct thread *th;
175
176     if (in_range_p(addr, READ_ONLY_SPACE_START, READ_ONLY_SPACE_SIZE) ||
177         in_range_p(addr, STATIC_SPACE_START, STATIC_SPACE_SIZE) ||
178         in_range_p(addr, DYNAMIC_SPACE_START, dynamic_space_size))
179         return 1;
180     for_each_thread(th) {
181         if (((os_vm_address_t)th->control_stack_start <= addr) &&
182             (addr < (os_vm_address_t)th->control_stack_end))
183             return 1;
184         if (in_range_p(addr, (lispobj) th->binding_stack_start,
185                        BINDING_STACK_SIZE))
186             return 1;
187     }
188     return 0;
189 }
190 \f
191 /*
192  * any OS-dependent special low-level handling for signals
193  */
194
195 #if defined LISP_FEATURE_GENCGC
196
197 /*
198  * The GENCGC needs to be hooked into whatever signal is raised for
199  * page fault on this OS.
200  */
201
202 void
203 memory_fault_handler(int signal, siginfo_t *siginfo, os_context_t *context)
204 {
205     void *fault_addr = arch_get_bad_addr(signal, siginfo, context);
206
207 #if defined(LISP_FEATURE_RESTORE_TLS_SEGMENT_REGISTER_FROM_CONTEXT)
208     FSHOW_SIGNAL((stderr, "/ TLS: restoring fs: %p in memory_fault_handler\n",
209                   *CONTEXT_ADDR_FROM_STEM(fs)));
210     os_restore_tls_segment_register(context);
211 #endif
212
213     FSHOW((stderr, "Memory fault at: %p, PC: %p\n", fault_addr, *os_context_pc_addr(context)));
214
215     if (!gencgc_handle_wp_violation(fault_addr))
216         if(!handle_guard_page_triggered(context,fault_addr))
217             lisp_memory_fault_error(context, fault_addr);
218 }
219
220 #if defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
221 void
222 mach_error_memory_fault_handler(int signal, siginfo_t *siginfo,
223                                 os_context_t *context) {
224     lose("Unhandled memory fault. Exiting.");
225 }
226 #endif
227
228 void
229 os_install_interrupt_handlers(void)
230 {
231     SHOW("os_install_interrupt_handlers()/bsd-os/defined(GENCGC)");
232 #if defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
233     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
234                                                  mach_error_memory_fault_handler);
235 #else
236     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
237 #ifdef LISP_FEATURE_FREEBSD
238                                                  (__siginfohandler_t *)
239 #endif
240                                                  memory_fault_handler);
241 #endif
242
243 #ifdef LISP_FEATURE_SB_THREAD
244     undoably_install_low_level_interrupt_handler(SIG_STOP_FOR_GC,
245                                                  sig_stop_for_gc_handler);
246 #endif
247     SHOW("leaving os_install_interrupt_handlers()");
248 }
249
250 #else /* Currently PPC/Darwin/Cheney only */
251
252 static void
253 sigsegv_handler(int signal, siginfo_t *info, os_context_t *context)
254 {
255 #if 0
256     unsigned int pc =  (unsigned int *)(*os_context_pc_addr(context));
257 #endif
258     os_vm_address_t addr;
259
260     addr = arch_get_bad_addr(signal, info, context);
261     if (!cheneygc_handle_wp_violation(context, addr))
262         if (!handle_guard_page_triggered(context, addr))
263             interrupt_handle_now(signal, info, context);
264 }
265
266 void
267 os_install_interrupt_handlers(void)
268 {
269     SHOW("os_install_interrupt_handlers()/bsd-os/!defined(GENCGC)");
270     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
271                                                  sigsegv_handler);
272 }
273
274 #endif /* defined GENCGC */
275
276 #ifdef __NetBSD__
277 static void netbsd_init()
278 {
279     struct rlimit rl;
280     int mib[2], osrev;
281     size_t len;
282
283     /* Are we running on a sufficiently functional kernel? */
284     mib[0] = CTL_KERN;
285     mib[1] = KERN_OSREV;
286
287     len = sizeof(osrev);
288     sysctl(mib, 2, &osrev, &len, NULL, 0);
289
290     /* If we're older than 2.0... */
291     if (osrev < 200000000) {
292         fprintf(stderr, "osrev = %d (needed at least 200000000).\n", osrev);
293         lose("NetBSD kernel too old to run sbcl.\n");
294     }
295
296     /* NetBSD counts mmap()ed space against the process's data size limit,
297      * so yank it up. This might be a nasty thing to do? */
298     getrlimit (RLIMIT_DATA, &rl);
299     /* Amazingly for such a new port, the provenance and meaning of
300        this number are unknown.  It might just mean REALLY_BIG_LIMIT,
301        or possibly it should be calculated from dynamic space size.
302        -- CSR, 2004-04-08 */
303     rl.rlim_cur = 1073741824;
304     if (setrlimit (RLIMIT_DATA, &rl) < 0) {
305         fprintf (stderr,
306                  "RUNTIME WARNING: unable to raise process data size limit:\n\
307   %s.\n\
308 The system may fail to start.\n",
309                  strerror(errno));
310     }
311 }
312
313 /* Various routines in NetBSD's C library are compatibility wrappers
314    for old versions. Programs must be processed by the C toolchain in
315    order to get up-to-date definitions of such routines. */
316 /* The stat-family, opendir, and readdir are used only in sb-posix, as
317    of 2007-01-16. -- RMK */
318 int
319 _stat(const char *path, struct stat *sb)
320 {
321     return stat(path, sb);
322 }
323 int
324 _lstat(const char *path, struct stat *sb)
325 {
326     return lstat(path, sb);
327 }
328 int
329 _fstat(int fd, struct stat *sb)
330 {
331     return fstat(fd, sb);
332 }
333
334 DIR *
335 _opendir(const char *filename)
336 {
337     return opendir(filename);
338 }
339 struct dirent *
340 _readdir(DIR *dirp)
341 {
342     return readdir(dirp);
343 }
344
345 /* Used in sb-bsd-sockets. */
346 int
347 _socket(int domain, int type, int protocol)
348 {
349     return socket(domain, type, protocol);
350 }
351 #endif /* __NetBSD__ */
352
353 #ifdef __FreeBSD__
354 extern int getosreldate(void);
355
356 int sig_memory_fault;
357
358 static void freebsd_init()
359 {
360     /* Memory fault signal on FreeBSD was changed from SIGBUS to
361      * SIGSEGV. */
362     if (getosreldate() < 700004)
363         sig_memory_fault = SIGBUS;
364     else
365         sig_memory_fault = SIGSEGV;
366
367     /* Quote from sbcl-devel (NIIMI Satoshi): "Some OSes, like FreeBSD
368      * 4.x with GENERIC kernel, does not enable SSE support even on
369      * SSE capable CPUs". Detect this situation and skip the
370      * fast_bzero sse/base selection logic that's normally done in
371      * x86-assem.S.
372      */
373 #ifdef LISP_FEATURE_X86
374     {
375         size_t len;
376         int instruction_sse;
377
378         len = sizeof(instruction_sse);
379         if (sysctlbyname("hw.instruction_sse", &instruction_sse, &len,
380                          NULL, 0) == 0 && instruction_sse != 0) {
381             /* Use the SSE detector */
382             fast_bzero_pointer = fast_bzero_detect;
383         }
384     }
385 #endif /* LISP_FEATURE_X86 */
386 }
387
388 #if defined(LISP_FEATURE_SB_THREAD) && defined(LISP_FEATURE_SB_FUTEX) \
389     && !defined(LISP_FEATURE_SB_PTHREAD_FUTEX)
390 int
391 futex_wait(int *lock_word, long oldval, long sec, unsigned long usec)
392 {
393     struct timespec timeout;
394     int ret;
395
396     if (sec < 0)
397         ret = umtx_wait((void *)lock_word, oldval, NULL);
398     else {
399         timeout.tv_sec = sec;
400         timeout.tv_nsec = usec * 1000;
401         ret = umtx_wait((void *)lock_word, oldval, &timeout);
402     }
403
404     switch (ret) {
405     case 0:
406         return 0;
407     case ETIMEDOUT:
408         return 1;
409     case EINTR:
410         return 2;
411     default:
412         /* EWOULDBLOCK and others, need to check the lock */
413         return -1;
414     }
415 }
416
417 int
418 futex_wake(int *lock_word, int n)
419 {
420     return umtx_wake((void *)lock_word, n);
421 }
422 #endif
423 #endif /* __FreeBSD__ */
424
425 #ifdef LISP_FEATURE_DARWIN
426 /* defined in ppc-darwin-os.c instead */
427 #elif defined(LISP_FEATURE_FREEBSD)
428 #ifndef KERN_PROC_PATHNAME
429 #define KERN_PROC_PATHNAME 12
430 #endif
431
432 char *
433 os_get_runtime_executable_path(int external)
434 {
435     char path[PATH_MAX + 1];
436
437     if (getosreldate() >= 600024) {
438         /* KERN_PROC_PATHNAME is available */
439         size_t len = PATH_MAX + 1;
440         int mib[4];
441
442         mib[0] = CTL_KERN;
443         mib[1] = KERN_PROC;
444         mib[2] = KERN_PROC_PATHNAME;
445         mib[3] = -1;
446         if (sysctl(mib, 4, &path, &len, NULL, 0) != 0)
447             return NULL;
448     } else {
449         int size;
450         size = readlink("/proc/curproc/file", path, sizeof(path) - 1);
451         if (size < 0)
452             return NULL;
453         path[size] = '\0';
454     }
455     if (strcmp(path, "unknown") == 0)
456         return NULL;
457     return copied_string(path);
458 }
459 #elif defined(LISP_FEATURE_NETBSD) || defined(LISP_FEATURE_OPENBSD)
460 char *
461 os_get_runtime_executable_path(int external)
462 {
463     struct stat sb;
464     if (!external && stat("/proc/curproc/file", &sb) == 0)
465         return copied_string("/proc/curproc/file");
466     return NULL;
467 }
468 #else /* Not DARWIN or FREEBSD or NETBSD or OPENBSD */
469 char *
470 os_get_runtime_executable_path(int external)
471 {
472     return NULL;
473 }
474 #endif
475
476 #ifdef __OpenBSD__
477
478 int openbsd_use_fxsave = 0;
479
480 void
481 openbsd_init()
482 {
483 #ifdef LISP_FEATURE_X86
484     int mib[2];
485     size_t size;
486 #endif
487     /*
488      * Show a warning if it looks like the memory available after
489      * allocating the spaces won't be at least this much.
490      */
491 #ifdef LISP_FEATURE_X86_64
492     const int wantfree = 64 * 1024 * 1024;
493 #else
494     const int wantfree = 32 * 1024 * 1024;
495 #endif
496     struct rlimit rl;
497
498 #ifdef LISP_FEATURE_X86
499     /* Save the machdep.osfxsr sysctl for use by os_restore_fp_control() */
500     mib[0] = CTL_MACHDEP;
501     mib[1] = CPU_OSFXSR;
502     size = sizeof (openbsd_use_fxsave);
503     sysctl(mib, 2, &openbsd_use_fxsave, &size, NULL, 0);
504 #endif
505
506     /* OpenBSD, like NetBSD, counts mmap()ed space against the
507      * process's data size limit. If the soft limit is lower than the
508      * hard limit then try to yank it up, this lets users in the
509      * "staff" or "daemon" login classes run sbcl with larger dynamic
510      * space sizes.
511      */
512     getrlimit (RLIMIT_DATA, &rl);
513     if (rl.rlim_cur < rl.rlim_max) {
514         rl.rlim_cur = rl.rlim_max;
515         if (setrlimit (RLIMIT_DATA, &rl) < 0) {
516             fprintf (stderr,
517                      "RUNTIME WARNING: unable to raise process data size limit:\n\
518   %s.\n\
519 The system may fail to start.\n",
520                      strerror(errno));
521         }
522     }
523
524     /*
525      * Display a (hopefully) helpful warning if it looks like we won't
526      * be able to allocate enough memory.
527      */
528     getrlimit (RLIMIT_DATA, &rl);
529     if (dynamic_space_size + READ_ONLY_SPACE_SIZE + STATIC_SPACE_SIZE +
530         LINKAGE_TABLE_SPACE_SIZE + wantfree > rl.rlim_cur)
531         fprintf (stderr,
532                  "RUNTIME WARNING: data size resource limit may be too low,\n"
533                  "  try decreasing the dynamic space size with --dynamic-space-size\n"
534                  "  or raising the datasize or datasize-max limits in /etc/login.conf\n");
535 }
536
537 /* OpenBSD's dlsym() relies on the gcc bulitin
538  * __builtin_return_address(0) returning an address in the
539  * executable's text segment, but when called from lisp it will return
540  * an address in the dynamic space.  Work around this by calling this
541  * wrapper function instead. Note that tail-call optimization will
542  * defeat this, disable it by saving the dlsym() return value in a
543  * volatile variable.
544 */
545 void *
546 os_dlsym(void *handle, const char *symbol)
547 {
548     void * volatile ret = dlsym(handle, symbol);
549     return ret;
550 }
551
552 #endif