| 1 | ;;;; rt.lisp -- the run time: what the compiled code calls. |
| 2 | ;;;; |
| 3 | ;;;; A compiled program is Lisp code over raw memory. Every raz variable |
| 4 | ;;;; lives at an address, as the report wants (ADR works on any of them): |
| 5 | ;;;; |
| 6 | ;;;; - the module variables, the string literals, the constant arrays |
| 7 | ;;;; and records and the errors' messages lie in one block, the data, |
| 8 | ;;;; mapped at the fixed address +DATA-BASE+, so that each of their |
| 9 | ;;;; addresses is a number the compiler knows; |
| 10 | ;;;; - a procedure's parameters, variables and temporaries lie in its |
| 11 | ;;;; frame, on a raz stack of its thread: *SP* is the first free byte. |
| 12 | ;;;; |
| 13 | ;;;; Values in Lisp: an integer, pointer, ERROR or set is an integer, |
| 14 | ;;;; kept within its type's range; a BOOL is T or NIL; a real a |
| 15 | ;;;; DOUBLE-FLOAT or SINGLE-FLOAT; a procedure value a number, its index |
| 16 | ;;;; in *PROCS*. An array, record, variant or slice is handled by its |
| 17 | ;;;; address. This file holds the operations on these that are more than |
| 18 | ;;;; a Lisp function the compiler can name directly. |
| 19 | |
| 20 | (in-package :raz) |
| 21 | |
| 22 | (defconstant +data-base+ #x200000000000 |
| 23 | "Where the data block is mapped, out of the way of SBCL's own memory.") |
| 24 | |
| 25 | (sb-ext:defglobal *data-image* (make-array 0 :element-type '(unsigned-byte 8)) |
| 26 | "The data block's first contents, made by the compiler.") |
| 27 | |
| 28 | (sb-ext:defglobal *procs* (vector nil) |
| 29 | "The procedures that are values: a procedure value is an index here; 0 is nil.") |
| 30 | |
| 31 | (sb-ext:defglobal *main* nil |
| 32 | "The program: a function that runs the module bodies and main, and returns the status.") |
| 33 | |
| 34 | (defvar *sp* 0 "The first free byte of this thread's raz stack.") |
| 35 | (defvar *stack-end* 0 "The end of this thread's raz stack.") |
| 36 | |
| 37 | ;;; Memory. LD reads a scalar of an access kind (types.lisp, ACCESS-KIND) |
| 38 | ;;; at an address, ST writes one. |
| 39 | |
| 40 | (defmacro ld (kind addr) |
| 41 | (let ((sap `(sb-sys:int-sap ,addr))) |
| 42 | (ecase kind |
| 43 | (:i8 `(sb-sys:signed-sap-ref-8 ,sap 0)) |
| 44 | (:i16 `(sb-sys:signed-sap-ref-16 ,sap 0)) |
| 45 | (:i32 `(sb-sys:signed-sap-ref-32 ,sap 0)) |
| 46 | (:i64 `(sb-sys:signed-sap-ref-64 ,sap 0)) |
| 47 | (:u8 `(sb-sys:sap-ref-8 ,sap 0)) |
| 48 | (:u16 `(sb-sys:sap-ref-16 ,sap 0)) |
| 49 | (:u32 `(sb-sys:sap-ref-32 ,sap 0)) |
| 50 | (:u64 `(sb-sys:sap-ref-64 ,sap 0)) |
| 51 | (:bool `(/= 0 (sb-sys:sap-ref-8 ,sap 0))) |
| 52 | (:f32 `(sb-sys:sap-ref-single ,sap 0)) |
| 53 | (:f64 `(sb-sys:sap-ref-double ,sap 0))))) |
| 54 | |
| 55 | (defmacro st (kind addr value) |
| 56 | (if (eq kind :bool) |
| 57 | `(setf (sb-sys:sap-ref-8 (sb-sys:int-sap ,addr) 0) (if ,value 1 0)) |
| 58 | `(setf (ld ,kind ,addr) ,value))) |
| 59 | |
| 60 | (defmacro c-call (name result &rest typed-args) |
| 61 | "Calls the C function NAME; TYPED-ARGS alternate alien types and values." |
| 62 | (let ((types (loop for (ty) on typed-args by #'cddr collect ty)) |
| 63 | (vals (loop for (nil v) on typed-args by #'cddr collect v))) |
| 64 | `(sb-alien:alien-funcall |
| 65 | (sb-alien:extern-alien ,name (function ,result ,@types)) ,@vals))) |
| 66 | |
| 67 | (defun move (dst src n) |
| 68 | "Copies N bytes from SRC to DST, which may overlap." |
| 69 | (when (> n 0) |
| 70 | (c-call "memmove" sb-alien:unsigned-long sb-alien:unsigned-long dst sb-alien:unsigned-long src |
| 71 | sb-alien:unsigned-long n)) |
| 72 | dst) |
| 73 | |
| 74 | (defun zero (dst n) |
| 75 | (when (> n 0) |
| 76 | (c-call "memset" sb-alien:unsigned-long sb-alien:unsigned-long dst sb-alien:int 0 |
| 77 | sb-alien:unsigned-long n)) |
| 78 | dst) |
| 79 | |
| 80 | (defun bytes-equal (a b n) |
| 81 | (or (= n 0) |
| 82 | (= 0 (c-call "memcmp" sb-alien:int sb-alien:unsigned-long a sb-alien:unsigned-long b |
| 83 | sb-alien:unsigned-long n)))) |
| 84 | |
| 85 | (defun slice (addr ptr len) |
| 86 | "Writes the slice (PTR, LEN) at ADDR, and gives ADDR." |
| 87 | (st :u64 addr ptr) |
| 88 | (st :i64 (+ addr 8) len) |
| 89 | addr) |
| 90 | |
| 91 | ;;; Frames. ENTER is the first thing a procedure does: its frame is the |
| 92 | ;;; SIZE bytes from FP, which must fit the stack, and start at zero. |
| 93 | |
| 94 | (define-condition stack-overflow (error) ()) |
| 95 | |
| 96 | (defun enter (fp size) |
| 97 | (when (> (+ fp size) *stack-end*) |
| 98 | ;; stopped at the top of the stack, where there is room to stop |
| 99 | (error 'stack-overflow)) |
| 100 | (zero fp size)) |
| 101 | |
| 102 | ;;; Stopping (section 10). A failed check, and every fault, comes to |
| 103 | ;;; STOP, which hands its message to the library's Rt.stop: it writes it, |
| 104 | ;;; runs the procedures registered with Rt.atExit and ends with status 2. |
| 105 | |
| 106 | (defvar *stopping* nil) |
| 107 | |
| 108 | (defun stop (text) |
| 109 | (let ((bytes (sb-ext:string-to-octets text :external-format :utf-8))) |
| 110 | (when *stopping* |
| 111 | ;; a stop while stopping: say it and end, with no more of the library |
| 112 | (write-bytes 2 bytes) |
| 113 | (write-bytes 2 #(10)) |
| 114 | (exit-now 2)) |
| 115 | (let ((*stopping* t) |
| 116 | (buf (c-call "malloc" sb-alien:unsigned-long sb-alien:unsigned-long (+ 16 (length bytes))))) |
| 117 | (loop for b across bytes for i from 16 do (st :u8 (+ buf i) b)) |
| 118 | (funcall 'razp::|Rt.stop| (slice buf (+ buf 16) (length bytes)))) |
| 119 | (exit-now 2))) |
| 120 | |
| 121 | (defun write-bytes (fd bytes) |
| 122 | (let ((buf (c-call "malloc" sb-alien:unsigned-long sb-alien:unsigned-long (max 1 (length bytes))))) |
| 123 | (loop for b across bytes for i from 0 do (st :u8 (+ buf i) b)) |
| 124 | (c-call "write" sb-alien:long sb-alien:int fd sb-alien:unsigned-long buf |
| 125 | sb-alien:unsigned-long (length bytes)))) |
| 126 | |
| 127 | (defun exit-now (status) |
| 128 | "Ends the program at once: C's buffers flushed, then the process." |
| 129 | (c-call "fflush" sb-alien:int sb-alien:unsigned-long 0) |
| 130 | (c-call "_exit" sb-alien:void sb-alien:int (logand status #xFF))) |
| 131 | |
| 132 | ;;; The checks of section 6.5, and those of division (6.1). WHERE is the |
| 133 | ;;; place, "file:line:col". |
| 134 | |
| 135 | (defun check-index (i n where) |
| 136 | (if (and (<= 0 i) (< i n)) |
| 137 | i |
| 138 | (stop (format nil "~a: index ~d is out of range for a length of ~d" where i n)))) |
| 139 | |
| 140 | (defun check-slice (lo hi n where) |
| 141 | (cond ((< lo 0) (stop (format nil "~a: slice bound ~d is below 0" where lo))) |
| 142 | ((< hi lo) (stop (format nil "~a: slice [~d..~d] runs backwards" where lo hi))) |
| 143 | ((and n (> hi n)) (stop (format nil "~a: slice bound ~d is beyond the length ~d" where hi n))) |
| 144 | (t lo))) |
| 145 | |
| 146 | (defun check-copy (ls ld where) |
| 147 | (when (> ls ld) |
| 148 | (stop (format nil "~a: COPY of ~d elements into ~d" where ls ld)))) |
| 149 | |
| 150 | (defun check-enum (i n where) |
| 151 | (if (and (<= 0 i) (< i n)) |
| 152 | i |
| 153 | (stop (format nil "~a: ~d is no position of the enumeration, which has ~d names" where i n)))) |
| 154 | |
| 155 | (defun divide (a b bits signed where mod) |
| 156 | "A div B, or A mod B with MOD, of a BITS-wide integer type." |
| 157 | (cond ((= b 0) (stop (format nil "~a: a division by zero" where))) |
| 158 | ((and signed (= b -1) (= a (- (expt 2 (1- bits))))) |
| 159 | (stop (format nil "~a: a division of the smallest ~d-bit integer by -1" where bits))) |
| 160 | (mod (rem a b)) |
| 161 | (t (values (truncate a b))))) |
| 162 | |
| 163 | ;;; Conversions (6.7) that are more than a Lisp function. |
| 164 | |
| 165 | (defun real-to-int (x bits signed) |
| 166 | "Rounded toward zero; a NaN or a value out of I64's range is the smallest I64, then cut." |
| 167 | (let ((i (if (and (= x x) (>= x -9223372036854775808d0) (< x 9223372036854775808d0)) |
| 168 | (truncate x) |
| 169 | (- (expt 2 63))))) |
| 170 | (if signed (sb-c::mask-signed-field bits i) (ldb (byte bits 0) i)))) |
| 171 | |
| 172 | ;;; Procedure values. |
| 173 | |
| 174 | (defun proc-fn (h) |
| 175 | "The function of procedure value H; nil stops the program." |
| 176 | (if (and (< 0 h) (< h (length *procs*))) |
| 177 | (svref *procs* h) |
| 178 | (stop (if (= h 0) "a call of a nil procedure" "a call of a bad procedure value")))) |
| 179 | |
| 180 | ;;; Procedures given to C: a C function for each, made once. |
| 181 | |
| 182 | (sb-ext:defglobal *callbacks* (make-hash-table) "Procedure value -> the address of its C function.") |
| 183 | (sb-ext:defglobal *callbacks-lock* (sb-thread:make-mutex) "") |
| 184 | |
| 185 | (defun c-callback (h make) |
| 186 | (if (= h 0) |
| 187 | 0 |
| 188 | (sb-thread:with-mutex (*callbacks-lock*) |
| 189 | (or (gethash h *callbacks*) |
| 190 | (setf (gethash h *callbacks*) (sb-sys:sap-int (funcall make (proc-fn h)))))))) |
| 191 | |
| 192 | (defmacro in-raz-thread (&body body) |
| 193 | "BODY, on a raz stack: a thread C started has none until it calls raz." |
| 194 | `(flet ((run () ,@body)) |
| 195 | (if (= *stack-end* 0) (with-raz-thread (run)) (run)))) |
| 196 | |
| 197 | ;;; The atomic built-ins (6.8), on INT, UINT and pointers. A CAS on a |
| 198 | ;;; word is the one the machine has; XCHG and XADD loop on it. |
| 199 | |
| 200 | (defun cas (addr old new signed) |
| 201 | (declare (type (unsigned-byte 64) addr)) |
| 202 | (if signed |
| 203 | (let ((old old) (new new)) |
| 204 | (declare (type (signed-byte 64) old new)) |
| 205 | (= old (sb-ext:cas (sb-sys:signed-sap-ref-64 (sb-sys:int-sap addr) 0) old new))) |
| 206 | (let ((old old) (new new)) |
| 207 | (declare (type (unsigned-byte 64) old new)) |
| 208 | (= old (sb-ext:cas (sb-sys:sap-ref-64 (sb-sys:int-sap addr) 0) old new))))) |
| 209 | |
| 210 | (defun xchg (addr x signed) |
| 211 | (loop (let ((old (if signed (ld :i64 addr) (ld :u64 addr)))) |
| 212 | (when (cas addr old x signed) (return old))))) |
| 213 | |
| 214 | (defun xadd (addr x signed) |
| 215 | (loop (let* ((old (if signed (ld :i64 addr) (ld :u64 addr))) |
| 216 | (new (if signed (sb-c::mask-signed-field 64 (+ old x)) (ldb (byte 64 0) (+ old x))))) |
| 217 | (when (cas addr old new signed) (return old))))) |
| 218 | |
| 219 | ;;; SYSCALL, through the C library's syscall(), which gives -1 and errno |
| 220 | ;;; where Linux gives minus the errno. |
| 221 | |
| 222 | (defun syscall (n &optional (a 0) (b 0) (c 0) (d 0) (e 0) (f 0)) |
| 223 | (flet ((w (x) (ldb (byte 64 0) x))) |
| 224 | (let ((r (c-call "syscall" sb-alien:long sb-alien:long n |
| 225 | sb-alien:unsigned-long (w a) sb-alien:unsigned-long (w b) |
| 226 | sb-alien:unsigned-long (w c) sb-alien:unsigned-long (w d) |
| 227 | sb-alien:unsigned-long (w e) sb-alien:unsigned-long (w f)))) |
| 228 | (if (= r -1) (- (sb-alien:get-errno)) r)))) |
| 229 | |
| 230 | ;;; The command line: C's own argv, which SBCL's run time keeps. |
| 231 | |
| 232 | (defun argv () (ld :u64 (sb-sys:find-foreign-symbol-address "posix_argv"))) |
| 233 | |
| 234 | (defun argc () |
| 235 | (loop with a = (argv) for i from 0 while (/= 0 (ld :u64 (+ a (* 8 i)))) finally (return i))) |
| 236 | |
| 237 | ;;; Raz stacks: memory mapped for each thread, not reserved, so that it |
| 238 | ;;; costs only what it uses. |
| 239 | |
| 240 | (defconstant +stack-size+ (* 256 1024 1024)) |
| 241 | |
| 242 | (defun map-memory (size &optional (at 0)) |
| 243 | ;; mmap(at, size, read|write, private|anonymous|noreserve, and |
| 244 | ;; fixed_noreplace if AT is given) |
| 245 | (let ((r (syscall 9 at size 3 (logior #x22 #x4000 (if (= at 0) 0 #x100000)) -1 0))) |
| 246 | (when (or (< r 0) (and (/= at 0) (/= r at))) |
| 247 | (write-bytes 2 (sb-ext:string-to-octets (format nil "can't map ~d bytes of memory~%" size))) |
| 248 | (exit-now 2)) |
| 249 | r)) |
| 250 | |
| 251 | (defmacro with-raz-thread (&body body) |
| 252 | "Runs BODY on a raz stack of its own, with the reals' traps off (6.3)." |
| 253 | `(let* ((*sp* (map-memory +stack-size+)) |
| 254 | (*stack-end* (+ *sp* +stack-size+))) |
| 255 | (sb-int:with-float-traps-masked (:overflow :invalid :inexact :divide-by-zero :underflow) |
| 256 | (catching-faults ,@body)))) |
| 257 | |
| 258 | (defun raz-frames () |
| 259 | "The names of the raz procedures under way, the innermost first." |
| 260 | (let ((names '())) |
| 261 | (sb-debug:map-backtrace |
| 262 | (lambda (frame) |
| 263 | (let ((name (sb-di:debug-fun-name (sb-di:frame-debug-fun frame)))) |
| 264 | (when (and (symbolp name) (eq (symbol-package name) (find-package :razp))) |
| 265 | (push (symbol-name name) names))))) |
| 266 | (nreverse names))) |
| 267 | |
| 268 | (defun trace-calls () |
| 269 | "Rt.trace: the calls under way, on standard error." |
| 270 | (dolist (name (raz-frames)) |
| 271 | (write-bytes 2 (sb-ext:string-to-octets (format nil " in ~a~%" name))))) |
| 272 | |
| 273 | (defmacro catching-faults (&body body) |
| 274 | "BODY, where a bad address or an exhausted stack stops the program, |
| 275 | from the bottom of the raz stack, where there is room to stop." |
| 276 | `(let ((where nil) (base *sp*)) |
| 277 | (handler-case |
| 278 | (handler-bind ((sb-sys:memory-fault-error |
| 279 | (lambda (c) (declare (ignore c)) (setf where (first (raz-frames)))))) |
| 280 | ,@body) |
| 281 | (sb-sys:memory-fault-error (c) |
| 282 | (setf *sp* base) |
| 283 | (stop (format nil "in ~a: a nil pointer or a bad address (0x~(~x~))" where |
| 284 | (fault-address c)))) |
| 285 | ((or storage-condition stack-overflow) () (setf *sp* base) (stop "a stack overflow"))))) |
| 286 | |
| 287 | (defun fault-address (c) |
| 288 | (let ((a (ignore-errors (slot-value c 'sb-kernel::address)))) |
| 289 | (if (integerp a) a 0))) |
| 290 | |
| 291 | ;;; Threads (the library's Thread): each a Lisp thread on a raz stack of |
| 292 | ;;; its own. A thread is known to raz code by a number. |
| 293 | |
| 294 | (sb-ext:defglobal *threads* (make-hash-table) "") |
| 295 | (sb-ext:defglobal *thread-count* 0 "") |
| 296 | (sb-ext:defglobal *threads-lock* (sb-thread:make-mutex) "") |
| 297 | |
| 298 | (defun thread-spawn (proc arg) |
| 299 | (let ((fn (proc-fn proc))) |
| 300 | (sb-thread:with-mutex (*threads-lock*) |
| 301 | (let ((id (incf *thread-count*))) |
| 302 | (setf (gethash id *threads*) |
| 303 | (sb-thread:make-thread (lambda () (with-raz-thread (funcall fn arg))))) |
| 304 | id)))) |
| 305 | |
| 306 | (defun thread-join (id) |
| 307 | (let ((th (sb-thread:with-mutex (*threads-lock*) (gethash id *threads*)))) |
| 308 | (when th |
| 309 | (sb-thread:join-thread th :default nil) |
| 310 | (sb-thread:with-mutex (*threads-lock*) (remhash id *threads*))))) |
| 311 | |
| 312 | ;;; Signals, for the library's Sys.catch and Sys.ignore: SBCL's run time |
| 313 | ;;; handles each signal caught, writing its number to a pipe. |
| 314 | |
| 315 | (sb-ext:defglobal *signal-pipe* nil "The fds of the pipe, read and write, once made.") |
| 316 | |
| 317 | (defun catch-signal (sig) |
| 318 | (unless *signal-pipe* |
| 319 | (let ((buf (c-call "malloc" sb-alien:unsigned-long sb-alien:unsigned-long 8))) |
| 320 | ;; pipe2(buf, O_CLOEXEC | O_NONBLOCK) |
| 321 | (syscall 293 buf (logior #x80000 #x800)) |
| 322 | (setf *signal-pipe* (cons (ld :i32 buf) (ld :i32 (+ buf 4)))))) |
| 323 | (let ((w (cdr *signal-pipe*))) |
| 324 | (sb-sys:enable-interrupt sig (lambda (&rest args) |
| 325 | (declare (ignore args)) |
| 326 | (let ((b (c-call "malloc" sb-alien:unsigned-long sb-alien:unsigned-long 1))) |
| 327 | (st :u8 b sig) |
| 328 | (syscall 1 w b 1) |
| 329 | (c-call "free" sb-alien:void sb-alien:unsigned-long b))))) |
| 330 | (car *signal-pipe*)) |
| 331 | |
| 332 | (defun ignore-signal (sig yes) |
| 333 | (sb-sys:enable-interrupt sig (if yes :ignore :default))) |
| 334 | |
| 335 | ;;; The start. The saved program begins here: the data block mapped and |
| 336 | ;;; filled, then the program run on the main thread's raz stack, and its |
| 337 | ;;; status given to Rt.exit. |
| 338 | |
| 339 | (defun start () |
| 340 | ;; the signals SBCL handles for itself do what they do in any program |
| 341 | (dolist (sig '(1 2 3 13 15)) (sb-sys:enable-interrupt sig :default)) |
| 342 | (let ((size (length *data-image*))) |
| 343 | (when (> size 0) |
| 344 | (map-memory (round-up size 4096) +data-base+) |
| 345 | (sb-sys:with-pinned-objects (*data-image*) |
| 346 | (move +data-base+ (sb-sys:sap-int (sb-sys:vector-sap *data-image*)) size)))) |
| 347 | (with-raz-thread |
| 348 | (let ((status (funcall *main*))) |
| 349 | (funcall 'razp::|Rt.exit| status))) |
| 350 | (exit-now 0)) |