c7b2b909f0ef6297ce92dfc25b8128d535f8f048
[sbcl.git] / tests / foreign-stack-alignment.impure.lisp
1 ;;;; Testing the stack alignment of foreign calls. Uses stack-alignment-offset.c.
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; While most of SBCL is derived from the CMU CL system, the test
7 ;;;; files (like this one) were written from scratch after the fork
8 ;;;; from CMU CL.
9 ;;;;
10 ;;;; This software is in the public domain and is provided with
11 ;;;; absolutely no warranty. See the COPYING and CREDITS files for
12 ;;;; more information.
13
14 (use-package :sb-alien)
15
16 ;;; Callbacks are not part of the exported interface yet -- when they are this can
17 ;;; go away.
18 (import 'sb-alien::alien-lambda)
19
20 (defun run (program &rest arguments)
21   (let* ((proc nil)
22          (output
23           (with-output-to-string (s)
24             (setf proc (run-program program arguments
25                                     :output s)))))
26     (unless (zerop (process-exit-code proc))
27       (error "Bad exit code: ~S~%Output:~% ~S"
28              (process-exit-code proc)
29              output))
30     output))
31
32 (defvar *required-alignment*
33   #+(and ppc darwin) 16
34   #+(and ppc (not darwin)) 8
35   #+x86-64 16
36   #+mips 8
37   #+(and x86 (not darwin)) 4
38   #+(and x86 darwin) 16
39   #-(or x86 x86-64 mips ppc) (error "Unknown platform"))
40
41 ;;;; Build the offset-tool as regular excutable, and run it with
42 ;;;; fork/exec, so that no lisp is on the stack. This is our known-good
43 ;;;; number.
44
45 #-win32
46 (progn
47   (run "/bin/sh" "run-compiler.sh" "-sbcl-pic"
48        "stack-alignment-offset.c" "-o" "stack-alignment-offset")
49
50   (defparameter *good-offset*
51     (parse-integer (run "./stack-alignment-offset"
52                         (princ-to-string *required-alignment*))))
53
54   ;; Build the tool again, this time as a shared object, and load it
55
56   (run "/bin/sh" "run-compiler.sh" "-sbcl-pic" "-sbcl-shared"
57        "stack-alignment-offset.c" "-o" "stack-alignment-offset.so")
58
59   (load-shared-object (truename "stack-alignment-offset.so"))
60
61   (define-alien-routine stack-alignment-offset int (alignment int))
62   (define-alien-routine trampoline int (callback (function int))))
63
64 ;;;; Now get the offset by calling from lisp, first with a regular foreign function
65 ;;;; call, then with an intervening callback.
66
67 (with-test (:name :regular :fails-on :win32)
68   (assert (= *good-offset* (stack-alignment-offset *required-alignment*))))
69
70 (with-test (:name :callback :fails-on :win32)
71   (assert (= *good-offset* (trampoline (alien-lambda int ()
72                                        (stack-alignment-offset *required-alignment*))))))
73
74 (when (probe-file "stack-alignment-offset.so")
75   (delete-file "stack-alignment-offset")
76   (delete-file "stack-alignment-offset.so"))
77
78 ;;;; success!