FAST-READ-BYTE refactoring
[sbcl.git] / src / code / load.lisp
1 ;;;; parts of the loader which make sense in the cross-compilation
2 ;;;; host (and which are useful in the host, because they're used by
3 ;;;; GENESIS)
4 ;;;;
5 ;;;; based on the CMU CL load.lisp code, written by Skef Wholey and
6 ;;;; Rob Maclachlan
7
8 ;;;; This software is part of the SBCL system. See the README file for
9 ;;;; more information.
10 ;;;;
11 ;;;; This software is derived from the CMU CL system, which was
12 ;;;; written at Carnegie Mellon University and released into the
13 ;;;; public domain. The software is in the public domain and is
14 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
15 ;;;; files for more information.
16
17 (in-package "SB!FASL")
18 \f
19 ;;;; There looks to be an exciting amount of state being modified
20 ;;;; here: certainly enough that I (dan, 2003.1.22) don't want to mess
21 ;;;; around deciding how to thread-safetify it.  So we use a Big Lock.
22 ;;;; Because this code is mutually recursive with the compiler, we use
23 ;;;; the **WORLD-LOCK**.
24
25 ;;;; miscellaneous load utilities
26
27 ;;; Output the current number of semicolons after a fresh-line.
28 ;;; FIXME: non-mnemonic name
29 (defun load-fresh-line ()
30   (fresh-line)
31   (let ((semicolons ";;;;;;;;;;;;;;;;"))
32     (do ((count *load-depth* (- count (length semicolons))))
33         ((< count (length semicolons))
34          (write-string semicolons *standard-output* :end count))
35       (declare (fixnum count))
36       (write-string semicolons))
37     (write-char #\space)))
38
39 ;;; If VERBOSE, output (to *STANDARD-OUTPUT*) a message about how
40 ;;; we're loading from STREAM-WE-ARE-LOADING-FROM.
41 (defun maybe-announce-load (stream-we-are-loading-from verbose)
42   (when verbose
43     (load-fresh-line)
44     (let ((name #-sb-xc-host (file-name stream-we-are-loading-from)
45                 #+sb-xc-host nil))
46       (if name
47           (format t "loading ~S~%" name)
48           (format t "loading stuff from ~S~%" stream-we-are-loading-from)))))
49 \f
50 ;;;; utilities for reading from fasl files
51
52 #!-sb-fluid (declaim (inline read-byte))
53
54 ;;; FIXME: why do all of these reading functions and macros declare
55 ;;; (SPEED 0)?  was there some bug in the compiler which has since
56 ;;; been fixed?  --njf, 2004-09-08
57
58 ;;; This expands into code to read an N-byte unsigned integer using
59 ;;; FAST-READ-BYTE.
60 (defmacro fast-read-u-integer (n)
61   (declare (optimize (speed 0)))
62   (do ((res '(fast-read-byte)
63             `(logior (fast-read-byte)
64                      (ash ,res 8)))
65        (cnt 1 (1+ cnt)))
66       ((>= cnt n) res)))
67
68 ;;; like FAST-READ-U-INTEGER, but the size may be determined at run time
69 (defmacro fast-read-var-u-integer (n)
70   (let ((n-pos (gensym))
71         (n-res (gensym))
72         (n-cnt (gensym)))
73     `(do ((,n-pos 8 (+ ,n-pos 8))
74           (,n-cnt (1- ,n) (1- ,n-cnt))
75           (,n-res
76            (fast-read-byte)
77            (dpb (fast-read-byte) (byte 8 ,n-pos) ,n-res)))
78          ((zerop ,n-cnt) ,n-res)
79        (declare (type index ,n-pos ,n-cnt)))))
80
81 ;;; Read a signed integer.
82 (defmacro fast-read-s-integer (n)
83   (declare (optimize (speed 0)))
84   (let ((n-last (gensym)))
85     (do ((res `(let ((,n-last (fast-read-byte)))
86                  (if (zerop (logand ,n-last #x80))
87                      ,n-last
88                      (logior ,n-last #x-100)))
89               `(logior (fast-read-byte)
90                        (ash (the (signed-byte ,(* cnt 8)) ,res) 8)))
91          (cnt 1 (1+ cnt)))
92         ((>= cnt n) res))))
93
94 ;;; Read an N-byte unsigned integer from the *FASL-INPUT-STREAM*.
95 (defmacro read-arg (n)
96   (declare (optimize (speed 0)))
97   (if (= n 1)
98       `(the (unsigned-byte 8) (read-byte *fasl-input-stream*))
99       `(with-fast-read-byte ((unsigned-byte 8) *fasl-input-stream*)
100          (fast-read-u-integer ,n))))
101
102 (declaim (inline read-byte-arg read-halfword-arg read-word-arg))
103 (defun read-byte-arg ()
104   (declare (optimize (speed 0)))
105   (read-arg 1))
106
107 (defun read-halfword-arg ()
108   (declare (optimize (speed 0)))
109   (read-arg #.(/ sb!vm:n-word-bytes 2)))
110
111 (defun read-word-arg ()
112   (declare (optimize (speed 0)))
113   (read-arg #.sb!vm:n-word-bytes))
114
115 (defun read-unsigned-byte-32-arg ()
116   (declare (optimize (speed 0)))
117   (read-arg 4))
118
119 \f
120 ;;;; the fop table
121
122 ;;; The table is implemented as a simple-vector indexed by the table
123 ;;; offset. We may need to have several, since LOAD can be called
124 ;;; recursively.
125
126 ;;; a list of free fop tables for the fasloader
127 ;;;
128 ;;; FIXME: Is it really a win to have this permanently bound?
129 ;;; Couldn't we just bind it on entry to LOAD-AS-FASL?
130 (defvar *free-fop-tables* (list (make-array 1000)))
131
132 ;;; the current fop table
133 (defvar *current-fop-table*)
134 (declaim (simple-vector *current-fop-table*))
135
136 ;;; the length of the current fop table
137 (defvar *current-fop-table-size*)
138 (declaim (type index *current-fop-table-size*))
139
140 ;;; the index in the fop-table of the next entry to be used
141 (defvar *current-fop-table-index*)
142 (declaim (type index *current-fop-table-index*))
143
144 (defun grow-fop-table ()
145   (let* ((new-size (* *current-fop-table-size* 2))
146          (new-table (make-array new-size)))
147     (declare (fixnum new-size) (simple-vector new-table))
148     (replace new-table (the simple-vector *current-fop-table*))
149     (setq *current-fop-table* new-table)
150     (setq *current-fop-table-size* new-size)))
151
152 (defmacro push-fop-table (thing)
153   (let ((n-index (gensym)))
154     `(let ((,n-index *current-fop-table-index*))
155        (declare (fixnum ,n-index))
156        (when (= ,n-index (the fixnum *current-fop-table-size*))
157          (grow-fop-table))
158        (setq *current-fop-table-index* (1+ ,n-index))
159        (setf (svref *current-fop-table* ,n-index) ,thing))))
160 \f
161 ;;;; the fop stack
162
163 ;;; (This is to be bound by LOAD to an adjustable (VECTOR T) with
164 ;;; FILL-POINTER, for use as a stack with VECTOR-PUSH-EXTEND.)
165 (defvar *fop-stack*)
166 (declaim (type (vector t) *fop-stack*))
167
168 ;;; Cache information about the fop stack in local variables. Define a
169 ;;; local macro to pop from the stack. Push the result of evaluation
170 ;;; if PUSHP.
171 (defmacro with-fop-stack (pushp &body forms)
172   (aver (member pushp '(nil t :nope)))
173   (with-unique-names (fop-stack)
174     `(let ((,fop-stack *fop-stack*))
175        (declare (type (vector t) ,fop-stack)
176                 (ignorable ,fop-stack))
177        (macrolet ((pop-stack ()
178                     `(vector-pop ,',fop-stack))
179                   (push-stack (value)
180                     `(vector-push-extend ,value ,',fop-stack))
181                   (call-with-popped-args (fun n)
182                     `(%call-with-popped-args ,fun ,n ,',fop-stack)))
183          ,(if pushp
184               `(vector-push-extend (progn ,@forms) ,fop-stack)
185               `(progn ,@forms))))))
186
187 ;;; Call FUN with N arguments popped from STACK.
188 (defmacro %call-with-popped-args (fun n stack)
189   ;; N's integer value must be known at macroexpansion time.
190   (declare (type index n))
191   (with-unique-names (n-stack old-length new-length)
192     (let ((argtmps (make-gensym-list n)))
193       `(let* ((,n-stack ,stack)
194               (,old-length (fill-pointer ,n-stack))
195               (,new-length (- ,old-length ,n))
196               ,@(loop for i from 0 below n collecting
197                       `(,(nth i argtmps)
198                         (aref ,n-stack (+ ,new-length ,i)))))
199         (declare (type (vector t) ,n-stack))
200         (setf (fill-pointer ,n-stack) ,new-length)
201         ;; (For some applications it might be appropriate to FILL the
202         ;; popped area with NIL here, to avoid holding onto garbage. For
203         ;; sbcl-0.8.7.something, though, it shouldn't matter, because
204         ;; we're using this only to pop stuff off *FOP-STACK*, and the
205         ;; entire *FOP-STACK* can be GCed as soon as LOAD returns.)
206         (,fun ,@argtmps)))))
207 \f
208 ;;;; Conditions signalled on invalid fasls (wrong fasl version, etc),
209 ;;;; so that user code (esp. ASDF) can reasonably handle attempts to
210 ;;;; load such fasls by recompiling them, etc. For simplicity's sake
211 ;;;; make only condition INVALID-FASL part of the public interface,
212 ;;;; and keep the guts internal.
213
214 (define-condition invalid-fasl (error)
215   ((stream :reader invalid-fasl-stream :initarg :stream)
216    (expected :reader invalid-fasl-expected :initarg :expected))
217   (:report
218    (lambda (condition stream)
219      (format stream "~S is an invalid fasl file."
220              (invalid-fasl-stream condition)))))
221
222 (define-condition invalid-fasl-header (invalid-fasl)
223   ((byte :reader invalid-fasl-byte :initarg :byte)
224    (byte-nr :reader invalid-fasl-byte-nr :initarg :byte-nr))
225   (:report
226    (lambda (condition stream)
227      (format stream "~@<~S contains an illegal byte in the FASL header at ~
228                      position ~A: Expected ~A, got ~A.~:@>"
229              (invalid-fasl-stream condition)
230              (invalid-fasl-byte-nr condition)
231              (invalid-fasl-expected condition)
232              (invalid-fasl-byte condition)))))
233
234 (define-condition invalid-fasl-version (invalid-fasl)
235   ((version :reader invalid-fasl-version :initarg :version))
236   (:report
237    (lambda (condition stream)
238      (format stream "~@<~S is a fasl file compiled with SBCL ~W, and ~
239                       can't be loaded into SBCL ~W.~:@>"
240              (invalid-fasl-stream condition)
241              (invalid-fasl-version condition)
242              (invalid-fasl-expected condition)))))
243
244 (define-condition invalid-fasl-implementation (invalid-fasl)
245   ((implementation :reader invalid-fasl-implementation
246                    :initarg :implementation))
247   (:report
248    (lambda (condition stream)
249      (format stream "~S was compiled for implementation ~A, but this is a ~A."
250              (invalid-fasl-stream condition)
251              (invalid-fasl-implementation condition)
252              (invalid-fasl-expected condition)))))
253
254 (define-condition invalid-fasl-features (invalid-fasl)
255   ((potential-features :reader invalid-fasl-potential-features
256                        :initarg :potential-features)
257    (features :reader invalid-fasl-features :initarg :features))
258   (:report
259    (lambda (condition stream)
260      (format stream "~@<incompatible ~S in fasl file ~S: ~2I~_~
261                      Of features affecting binary compatibility, ~4I~_~S~2I~_~
262                      the fasl has ~4I~_~A,~2I~_~
263                      while the runtime expects ~4I~_~A.~:>"
264              '*features*
265              (invalid-fasl-stream condition)
266              (invalid-fasl-potential-features condition)
267              (invalid-fasl-features condition)
268              (invalid-fasl-expected condition)))))
269
270 ;;; Skips past the shebang line on stream, if any.
271 (defun maybe-skip-shebang-line (stream)
272   (let ((p (file-position stream)))
273     (flet ((next () (read-byte stream nil)))
274       (unwind-protect
275            (when (and (eq (next) (char-code #\#))
276                       (eq (next) (char-code #\!)))
277              (setf p nil)
278              (loop for x = (next)
279                    until (or (not x) (eq x (char-code #\newline)))))
280         (when p
281           (file-position stream p))))
282     t))
283
284 ;;; Returns T if the stream is a binary input stream with a FASL header.
285 (defun fasl-header-p (stream &key errorp)
286   (unless (member (stream-element-type stream) '(character base-char))
287     (let ((p (file-position stream)))
288       (unwind-protect
289            (let* ((header *fasl-header-string-start-string*)
290                   (buffer (make-array (length header) :element-type '(unsigned-byte 8)))
291                   (n 0))
292              (flet ((scan ()
293                       (maybe-skip-shebang-line stream)
294                       (setf n (read-sequence buffer stream))))
295                (if errorp
296                    (scan)
297                    (or (ignore-errors (scan))
298                        ;; no a binary input stream
299                        (return-from fasl-header-p nil))))
300              (if (mismatch buffer header
301                            :test #'(lambda (code char) (= code (char-code char))))
302                  ;; Immediate EOF is valid -- we want to match what
303                  ;; CHECK-FASL-HEADER does...
304                  (or (zerop n)
305                      (when errorp
306                        (error 'fasl-header-missing
307                               :stream stream
308                               :fhsss buffer
309                               :expected header)))
310                  t))
311         (file-position stream p)))))
312
313
314 ;;;; LOAD-AS-FASL
315 ;;;;
316 ;;;; Note: LOAD-AS-FASL is used not only by LOAD, but also (with
317 ;;;; suitable modification of the fop table) in GENESIS. Therefore,
318 ;;;; it's needed not only in the target Lisp, but also in the
319 ;;;; cross-compilation host.
320
321 ;;; a helper function for LOAD-FASL-GROUP
322 ;;;
323 ;;; Return true if we successfully read a FASL header from the stream, or NIL
324 ;;; if EOF was hit before anything except the optional shebang line was read.
325 ;;; Signal an error if we encounter garbage.
326 (defun check-fasl-header (stream)
327   (maybe-skip-shebang-line stream)
328   (let ((byte (read-byte stream nil)))
329     (when byte
330       ;; Read and validate constant string prefix in fasl header.
331       (let* ((fhsss *fasl-header-string-start-string*)
332              (fhsss-length (length fhsss)))
333         (unless (= byte (char-code (schar fhsss 0)))
334           (error 'invalid-fasl-header
335                  :stream stream
336                  :byte-nr 0
337                  :byte byte
338                  :expected (char-code (schar fhsss 0))))
339         (do ((byte (read-byte stream) (read-byte stream))
340              (count 1 (1+ count)))
341             ((= byte +fasl-header-string-stop-char-code+)
342              t)
343           (declare (fixnum byte count))
344           (when (and (< count fhsss-length)
345                      (not (eql byte (char-code (schar fhsss count)))))
346             (error 'invalid-fasl-header
347                    :stream stream
348                    :byte-nr count
349                    :byte byte
350                    :expected (char-code (schar fhsss count))))))
351       ;; Read and validate version-specific compatibility stuff.
352       (flet ((string-from-stream ()
353                (let* ((length (read-unsigned-byte-32-arg))
354                       (result (make-string length)))
355                  (read-string-as-bytes stream result)
356                  result)))
357         ;; Read and validate implementation and version.
358         (let ((implementation (keywordicate (string-from-stream)))
359               (expected-implementation +backend-fasl-file-implementation+))
360           (unless (string= expected-implementation implementation)
361             (error 'invalid-fasl-implementation
362                    :stream stream
363                    :implementation implementation
364                    :expected expected-implementation)))
365         (let* ((fasl-version (read-word-arg))
366                (sbcl-version (if (<= fasl-version 76)
367                                  "1.0.11.18"
368                                  (string-from-stream)))
369                (expected-version (sb!xc:lisp-implementation-version)))
370           (unless (string= expected-version sbcl-version)
371             (restart-case
372                 (error 'invalid-fasl-version
373                        :stream stream
374                        :version sbcl-version
375                        :expected expected-version)
376               (continue () :report "Load the fasl file anyway"))))
377         ;; Read and validate *FEATURES* which affect binary compatibility.
378         (let ((faff-in-this-file (string-from-stream)))
379           (unless (string= faff-in-this-file *features-affecting-fasl-format*)
380             (error 'invalid-fasl-features
381                    :stream stream
382                    :potential-features *features-potentially-affecting-fasl-format*
383                    :expected *features-affecting-fasl-format*
384                    :features faff-in-this-file)))
385         ;; success
386         t))))
387
388 ;; Setting this variable gives you a trace of fops as they are loaded and
389 ;; executed.
390 #!+sb-show
391 (defvar *show-fops-p* nil)
392
393 ;; buffer for loading symbols
394 (defvar *fasl-symbol-buffer*)
395 (declaim (simple-string *fasl-symbol-buffer*))
396
397 ;;;
398 ;;; a helper function for LOAD-AS-FASL
399 ;;;
400 ;;; Return true if we successfully load a group from the stream, or
401 ;;; NIL if EOF was encountered while trying to read from the stream.
402 ;;; Dispatch to the right function for each fop.
403 (defun load-fasl-group (stream)
404   (when (check-fasl-header stream)
405     (catch 'fasl-group-end
406       (let ((*current-fop-table-index* 0)
407             (*skip-until* nil))
408         (declare (special *skip-until*))
409         (loop
410           (let ((byte (read-byte stream)))
411             ;; Do some debugging output.
412             #!+sb-show
413             (when *show-fops-p*
414               (let* ((stack *fop-stack*)
415                      (ptr (1- (fill-pointer *fop-stack*))))
416                 (fresh-line *trace-output*)
417                 ;; The FOP operations are stack based, so it's sorta
418                 ;; logical to display the operand before the operator.
419                 ;; ("reverse Polish notation")
420                 (unless (= ptr -1)
421                   (write-char #\space *trace-output*)
422                   (prin1 (aref stack ptr) *trace-output*)
423                   (terpri *trace-output*))
424                 ;; Display the operator.
425                 (format *trace-output*
426                         "~&~S (#X~X at ~D) (~S)~%"
427                         (aref *fop-names* byte)
428                         byte
429                         (1- (file-position stream))
430                         (svref *fop-funs* byte))))
431
432             ;; Actually execute the fop.
433             (funcall (the function (svref *fop-funs* byte)))))))))
434
435 (defun load-as-fasl (stream verbose print)
436   ;; KLUDGE: ANSI says it's good to do something with the :PRINT
437   ;; argument to LOAD when we're fasloading a file, but currently we
438   ;; don't. (CMU CL did, but implemented it in a non-ANSI way, and I
439   ;; just disabled that instead of rewriting it.) -- WHN 20000131
440   (declare (ignore print))
441   (when (zerop (file-length stream))
442     (error "attempt to load an empty FASL file:~%  ~S" (namestring stream)))
443   (maybe-announce-load stream verbose)
444   (with-world-lock ()
445     (let* ((*fasl-input-stream* stream)
446            (*fasl-symbol-buffer* (make-string 100))
447            (*current-fop-table* (or (pop *free-fop-tables*) (make-array 1000)))
448            (*current-fop-table-size* (length *current-fop-table*))
449            (*fop-stack* (make-array 100 :fill-pointer 0 :adjustable t)))
450       (unwind-protect
451            (loop while (load-fasl-group stream))
452         (push *current-fop-table* *free-fop-tables*)
453         ;; NIL out the table, so that we don't hold onto garbage.
454         ;;
455         ;; FIXME: Could we just get rid of the free fop table pool so
456         ;; that this would go away?
457         (fill *current-fop-table* nil))))
458   t)
459
460 (declaim (notinline read-byte)) ; Why is it even *declaimed* inline above?
461 \f
462 ;;;; stuff for debugging/tuning by collecting statistics on FOPs (?)
463
464 #|
465 (defvar *fop-counts* (make-array 256 :initial-element 0))
466 (defvar *fop-times* (make-array 256 :initial-element 0))
467 (defvar *print-fops* nil)
468
469 (defun clear-counts ()
470   (fill (the simple-vector *fop-counts*) 0)
471   (fill (the simple-vector *fop-times*) 0)
472   t)
473
474 (defun analyze-counts ()
475   (let ((counts ())
476         (total-count 0)
477         (times ())
478         (total-time 0))
479     (macrolet ((breakdown (lvar tvar vec)
480                  `(progn
481                    (dotimes (i 255)
482                      (declare (fixnum i))
483                      (let ((n (svref ,vec i)))
484                        (push (cons (svref *fop-names* i) n) ,lvar)
485                        (incf ,tvar n)))
486                    (setq ,lvar (subseq (sort ,lvar (lambda (x y)
487                                                      (> (cdr x) (cdr y))))
488                                        0 10)))))
489
490       (breakdown counts total-count *fop-counts*)
491       (breakdown times total-time *fop-times*)
492       (format t "Total fop count is ~D~%" total-count)
493       (dolist (c counts)
494         (format t "~30S: ~4D~%" (car c) (cdr c)))
495       (format t "~%Total fop time is ~D~%" (/ (float total-time) 60.0))
496       (dolist (m times)
497         (format t "~30S: ~6,2F~%" (car m) (/ (float (cdr m)) 60.0))))))
498 |#
499