ed29a41a0199bc18bd8d7bf56a4b6ccf5164f69b
[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 ;;; This expands into code to read an N-byte unsigned integer using
55 ;;; FAST-READ-BYTE.
56 (defmacro fast-read-u-integer (n)
57   (let (bytes)
58     `(let ,(loop for i from 0 below n
59                  collect (let ((name (gensym "B")))
60                            (push name bytes)
61                            `(,name ,(if (zerop i)
62                                         `(fast-read-byte)
63                                         `(ash (fast-read-byte) ,(* i 8))))))
64        (logior ,@bytes))))
65
66 ;;; like FAST-READ-U-INTEGER, but the size may be determined at run time
67 (defmacro fast-read-var-u-integer (n)
68   (let ((n-pos (gensym))
69         (n-res (gensym))
70         (n-cnt (gensym)))
71     `(do ((,n-pos 8 (+ ,n-pos 8))
72           (,n-cnt (1- ,n) (1- ,n-cnt))
73           (,n-res
74            (fast-read-byte)
75            (dpb (fast-read-byte) (byte 8 ,n-pos) ,n-res)))
76          ((zerop ,n-cnt) ,n-res)
77        (declare (type index ,n-pos ,n-cnt)))))
78
79 ;;; Read a signed integer.
80 (defmacro fast-read-s-integer (n)
81   (declare (optimize (speed 0)))
82   (let ((n-last (gensym)))
83     (do ((res `(let ((,n-last (fast-read-byte)))
84                  (if (zerop (logand ,n-last #x80))
85                      ,n-last
86                      (logior ,n-last #x-100)))
87               `(logior (fast-read-byte)
88                        (ash (the (signed-byte ,(* cnt 8)) ,res) 8)))
89          (cnt 1 (1+ cnt)))
90         ((>= cnt n) res))))
91
92 ;;; Read an N-byte unsigned integer from the *FASL-INPUT-STREAM*.
93 (defmacro read-arg (n)
94   (declare (optimize (speed 0)))
95   (if (= n 1)
96       `(the (unsigned-byte 8) (read-byte *fasl-input-stream*))
97       `(with-fast-read-byte ((unsigned-byte 8) *fasl-input-stream*)
98          (fast-read-u-integer ,n))))
99
100 (declaim (inline read-byte-arg read-halfword-arg read-word-arg))
101 (defun read-byte-arg ()
102   (declare (optimize (speed 0)))
103   (read-arg 1))
104
105 (defun read-halfword-arg ()
106   (declare (optimize (speed 0)))
107   (read-arg #.(/ sb!vm:n-word-bytes 2)))
108
109 (defun read-word-arg ()
110   (declare (optimize (speed 0)))
111   (read-arg #.sb!vm:n-word-bytes))
112
113 (defun read-unsigned-byte-32-arg ()
114   (declare (optimize (speed 0)))
115   (read-arg 4))
116
117 \f
118 ;;;; the fop table
119
120 ;;; The table is implemented as a simple-vector indexed by the table
121 ;;; offset. The offset is kept in at index 0 of the vector.
122 ;;;
123 ;;; FOPs use the table to save stuff, other FOPs refer to the table by
124 ;;; direct indexes via REF-FOP-TABLE.
125
126 (defvar *fop-table*)
127 (declaim (simple-vector *fop-table*))
128
129 (declaim (inline ref-fop-table))
130 (defun ref-fop-table (index)
131   (declare (index index))
132   (svref *fop-table* (the index (+ index 1))))
133
134 (defun get-fop-table-index ()
135   (svref *fop-table* 0))
136
137 (defun reset-fop-table ()
138   (setf (svref *fop-table* 0) 0))
139
140 (defun push-fop-table (thing)
141   (let* ((table *fop-table*)
142          (index (+ (the index (aref table 0)) 1)))
143     (declare (fixnum index)
144              (simple-vector table))
145     (when (eql index (length table))
146       (setf table (grow-fop-vector table index)
147             *fop-table* table))
148     (setf (aref table 0) index
149           (aref table index) thing)))
150
151 ;;; These three routines are used for both the stack and the table.
152 (defun make-fop-vector (size)
153   (declare (index size))
154   (let ((vector (make-array size)))
155     (setf (aref vector 0) 0)
156     vector))
157
158 (defun grow-fop-vector (old-vector old-size)
159   (declare (simple-vector old-vector)
160            (index old-size))
161   (let* ((new-size (* old-size 2))
162          (new-vector (make-array new-size)))
163     (declare (fixnum new-size)
164              (simple-vector new-vector old-vector))
165     (replace new-vector old-vector)
166     (nuke-fop-vector old-vector)
167     new-vector))
168
169 (defun nuke-fop-vector (vector)
170   (declare (simple-vector vector)
171            (optimize speed))
172   ;; Make sure we don't keep any garbage.
173   #!+gencgc
174   (fill vector 0))
175
176 \f
177 ;;;; the fop stack
178
179 ;;; Much like the table, this is bound to a simple vector whose first
180 ;;; element is the current index.
181 (defvar *fop-stack*)
182 (declaim (simple-vector *fop-stack*))
183
184 (defun fop-stack-empty-p ()
185   (eql 0 (svref *fop-stack* 0)))
186
187 (defun pop-fop-stack ()
188   (let* ((stack *fop-stack*)
189          (top (svref stack 0)))
190     (declare (index top))
191     (when (eql 0 top)
192       (error "FOP stack empty"))
193     (setf (svref stack 0) (1- top))
194     (svref stack top)))
195
196 (defun push-fop-stack (value)
197   (let* ((stack *fop-stack*)
198          (next (1+ (the index (svref stack 0)))))
199     (declare (index next))
200     (when (eql (length stack) next)
201       (setf stack (grow-fop-vector stack next)
202             *fop-stack* stack))
203     (setf (svref stack 0) next
204           (svref stack next) value)))
205
206 ;;; Define a local macro to pop from the stack. Push the result of evaluation
207 ;;; if PUSHP.
208 (defmacro with-fop-stack (pushp &body forms)
209   (aver (member pushp '(nil t :nope)))
210   `(macrolet ((pop-stack ()
211                 `(pop-fop-stack))
212               (push-stack (value)
213                 `(push-fop-stack ,value)))
214      ,(if pushp
215           `(push-fop-stack (progn ,@forms))
216           `(progn ,@forms))))
217
218 ;;; Call FUN with N arguments popped from STACK.
219 (defmacro call-with-popped-args (fun n)
220   ;; N's integer value must be known at macroexpansion time.
221   (declare (type index n))
222   (with-unique-names (n-stack old-top new-top)
223     (let ((argtmps (make-gensym-list n)))
224       `(let* ((,n-stack *fop-stack*)
225               (,old-top (svref ,n-stack 0))
226               (,new-top (- ,old-top ,n))
227               ,@(loop for i from 1 upto n collecting
228                       `(,(nth (1- i) argtmps)
229                         (aref ,n-stack (+ ,new-top ,i)))))
230          (declare (simple-vector ,n-stack))
231          (setf (svref ,n-stack 0) ,new-top)
232         ;; (For some applications it might be appropriate to FILL the
233         ;; popped area with NIL here, to avoid holding onto garbage. For
234         ;; sbcl-0.8.7.something, though, it shouldn't matter, because
235         ;; we're using this only to pop stuff off *FOP-STACK*, and the
236         ;; entire *FOP-STACK* can be GCed as soon as LOAD returns.)
237         (,fun ,@argtmps)))))
238 \f
239 ;;;; Conditions signalled on invalid fasls (wrong fasl version, etc),
240 ;;;; so that user code (esp. ASDF) can reasonably handle attempts to
241 ;;;; load such fasls by recompiling them, etc. For simplicity's sake
242 ;;;; make only condition INVALID-FASL part of the public interface,
243 ;;;; and keep the guts internal.
244
245 (define-condition invalid-fasl (error)
246   ((stream :reader invalid-fasl-stream :initarg :stream)
247    (expected :reader invalid-fasl-expected :initarg :expected))
248   (:report
249    (lambda (condition stream)
250      (format stream "~S is an invalid fasl file."
251              (invalid-fasl-stream condition)))))
252
253 (define-condition invalid-fasl-header (invalid-fasl)
254   ((byte :reader invalid-fasl-byte :initarg :byte)
255    (byte-nr :reader invalid-fasl-byte-nr :initarg :byte-nr))
256   (:report
257    (lambda (condition stream)
258      (format stream "~@<~S contains an illegal byte in the FASL header at ~
259                      position ~A: Expected ~A, got ~A.~:@>"
260              (invalid-fasl-stream condition)
261              (invalid-fasl-byte-nr condition)
262              (invalid-fasl-expected condition)
263              (invalid-fasl-byte condition)))))
264
265 (define-condition invalid-fasl-version (invalid-fasl)
266   ((version :reader invalid-fasl-version :initarg :version))
267   (:report
268    (lambda (condition stream)
269      (format stream "~@<~S is a fasl file compiled with SBCL ~W, and ~
270                       can't be loaded into SBCL ~W.~:@>"
271              (invalid-fasl-stream condition)
272              (invalid-fasl-version condition)
273              (invalid-fasl-expected condition)))))
274
275 (define-condition invalid-fasl-implementation (invalid-fasl)
276   ((implementation :reader invalid-fasl-implementation
277                    :initarg :implementation))
278   (:report
279    (lambda (condition stream)
280      (format stream "~S was compiled for implementation ~A, but this is a ~A."
281              (invalid-fasl-stream condition)
282              (invalid-fasl-implementation condition)
283              (invalid-fasl-expected condition)))))
284
285 (define-condition invalid-fasl-features (invalid-fasl)
286   ((potential-features :reader invalid-fasl-potential-features
287                        :initarg :potential-features)
288    (features :reader invalid-fasl-features :initarg :features))
289   (:report
290    (lambda (condition stream)
291      (format stream "~@<incompatible ~S in fasl file ~S: ~2I~_~
292                      Of features affecting binary compatibility, ~4I~_~S~2I~_~
293                      the fasl has ~4I~_~A,~2I~_~
294                      while the runtime expects ~4I~_~A.~:>"
295              '*features*
296              (invalid-fasl-stream condition)
297              (invalid-fasl-potential-features condition)
298              (invalid-fasl-features condition)
299              (invalid-fasl-expected condition)))))
300
301 ;;; Skips past the shebang line on stream, if any.
302 (defun maybe-skip-shebang-line (stream)
303   (let ((p (file-position stream)))
304     (flet ((next () (read-byte stream nil)))
305       (unwind-protect
306            (when (and (eq (next) (char-code #\#))
307                       (eq (next) (char-code #\!)))
308              (setf p nil)
309              (loop for x = (next)
310                    until (or (not x) (eq x (char-code #\newline)))))
311         (when p
312           (file-position stream p))))
313     t))
314
315 ;;; Returns T if the stream is a binary input stream with a FASL header.
316 (defun fasl-header-p (stream &key errorp)
317   (unless (member (stream-element-type stream) '(character base-char))
318     (let ((p (file-position stream)))
319       (unwind-protect
320            (let* ((header *fasl-header-string-start-string*)
321                   (buffer (make-array (length header) :element-type '(unsigned-byte 8)))
322                   (n 0))
323              (flet ((scan ()
324                       (maybe-skip-shebang-line stream)
325                       (setf n (read-sequence buffer stream))))
326                (if errorp
327                    (scan)
328                    (or (ignore-errors (scan))
329                        ;; no a binary input stream
330                        (return-from fasl-header-p nil))))
331              (if (mismatch buffer header
332                            :test #'(lambda (code char) (= code (char-code char))))
333                  ;; Immediate EOF is valid -- we want to match what
334                  ;; CHECK-FASL-HEADER does...
335                  (or (zerop n)
336                      (when errorp
337                        (error 'fasl-header-missing
338                               :stream stream
339                               :fhsss buffer
340                               :expected header)))
341                  t))
342         (file-position stream p)))))
343
344
345 ;;;; LOAD-AS-FASL
346 ;;;;
347 ;;;; Note: LOAD-AS-FASL is used not only by LOAD, but also (with
348 ;;;; suitable modification of the fop table) in GENESIS. Therefore,
349 ;;;; it's needed not only in the target Lisp, but also in the
350 ;;;; cross-compilation host.
351
352 ;;; a helper function for LOAD-FASL-GROUP
353 ;;;
354 ;;; Return true if we successfully read a FASL header from the stream, or NIL
355 ;;; if EOF was hit before anything except the optional shebang line was read.
356 ;;; Signal an error if we encounter garbage.
357 (defun check-fasl-header (stream)
358   (maybe-skip-shebang-line stream)
359   (let ((byte (read-byte stream nil)))
360     (when byte
361       ;; Read and validate constant string prefix in fasl header.
362       (let* ((fhsss *fasl-header-string-start-string*)
363              (fhsss-length (length fhsss)))
364         (unless (= byte (char-code (schar fhsss 0)))
365           (error 'invalid-fasl-header
366                  :stream stream
367                  :byte-nr 0
368                  :byte byte
369                  :expected (char-code (schar fhsss 0))))
370         (do ((byte (read-byte stream) (read-byte stream))
371              (count 1 (1+ count)))
372             ((= byte +fasl-header-string-stop-char-code+)
373              t)
374           (declare (fixnum byte count))
375           (when (and (< count fhsss-length)
376                      (not (eql byte (char-code (schar fhsss count)))))
377             (error 'invalid-fasl-header
378                    :stream stream
379                    :byte-nr count
380                    :byte byte
381                    :expected (char-code (schar fhsss count))))))
382       ;; Read and validate version-specific compatibility stuff.
383       (flet ((string-from-stream ()
384                (let* ((length (read-unsigned-byte-32-arg))
385                       (result (make-string length)))
386                  (read-string-as-bytes stream result)
387                  result)))
388         ;; Read and validate implementation and version.
389         (let ((implementation (keywordicate (string-from-stream)))
390               (expected-implementation +backend-fasl-file-implementation+))
391           (unless (string= expected-implementation implementation)
392             (error 'invalid-fasl-implementation
393                    :stream stream
394                    :implementation implementation
395                    :expected expected-implementation)))
396         (let* ((fasl-version (read-word-arg))
397                (sbcl-version (if (<= fasl-version 76)
398                                  "1.0.11.18"
399                                  (string-from-stream)))
400                (expected-version (sb!xc:lisp-implementation-version)))
401           (unless (string= expected-version sbcl-version)
402             (restart-case
403                 (error 'invalid-fasl-version
404                        :stream stream
405                        :version sbcl-version
406                        :expected expected-version)
407               (continue () :report "Load the fasl file anyway"))))
408         ;; Read and validate *FEATURES* which affect binary compatibility.
409         (let ((faff-in-this-file (string-from-stream)))
410           (unless (string= faff-in-this-file *features-affecting-fasl-format*)
411             (error 'invalid-fasl-features
412                    :stream stream
413                    :potential-features *features-potentially-affecting-fasl-format*
414                    :expected *features-affecting-fasl-format*
415                    :features faff-in-this-file)))
416         ;; success
417         t))))
418
419 ;; Setting this variable gives you a trace of fops as they are loaded and
420 ;; executed.
421 #!+sb-show
422 (defvar *show-fops-p* nil)
423
424 ;;;
425 ;;; a helper function for LOAD-AS-FASL
426 ;;;
427 ;;; Return true if we successfully load a group from the stream, or
428 ;;; NIL if EOF was encountered while trying to read from the stream.
429 ;;; Dispatch to the right function for each fop.
430 (defun load-fasl-group (stream)
431   (when (check-fasl-header stream)
432     (catch 'fasl-group-end
433       (reset-fop-table)
434       (let ((*skip-until* nil))
435         (declare (special *skip-until*))
436         (loop
437           (let ((byte (read-byte stream)))
438             ;; Do some debugging output.
439             #!+sb-show
440             (when *show-fops-p*
441               (let* ((stack *fop-stack*)
442                      (ptr (svref stack 0)))
443                 (fresh-line *trace-output*)
444                 ;; The FOP operations are stack based, so it's sorta
445                 ;; logical to display the operand before the operator.
446                 ;; ("reverse Polish notation")
447                 (unless (= ptr 0)
448                   (write-char #\space *trace-output*)
449                   (prin1 (aref stack ptr) *trace-output*)
450                   (terpri *trace-output*))
451                 ;; Display the operator.
452                 (format *trace-output*
453                         "~&~S (#X~X at ~D) (~S)~%"
454                         (aref *fop-names* byte)
455                         byte
456                         (1- (file-position stream))
457                         (svref *fop-funs* byte))))
458
459             ;; Actually execute the fop.
460             (funcall (the function (svref *fop-funs* byte)))))))))
461
462 (defun load-as-fasl (stream verbose print)
463   ;; KLUDGE: ANSI says it's good to do something with the :PRINT
464   ;; argument to LOAD when we're fasloading a file, but currently we
465   ;; don't. (CMU CL did, but implemented it in a non-ANSI way, and I
466   ;; just disabled that instead of rewriting it.) -- WHN 20000131
467   (declare (ignore print))
468   (when (zerop (file-length stream))
469     (error "attempt to load an empty FASL file:~%  ~S" (namestring stream)))
470   (maybe-announce-load stream verbose)
471   (with-world-lock ()
472     (let* ((*fasl-input-stream* stream)
473            (*fop-table* (make-fop-vector 1000))
474            (*fop-stack* (make-fop-vector 100)))
475       (unwind-protect
476            (loop while (load-fasl-group stream))
477         ;; Nuke the table and stack to avoid keeping garbage on
478         ;; conservatively collected platforms.
479         (nuke-fop-vector *fop-table*)
480         (nuke-fop-vector *fop-stack*))))
481   t)
482
483 (declaim (notinline read-byte)) ; Why is it even *declaimed* inline above?
484 \f
485 ;;;; stuff for debugging/tuning by collecting statistics on FOPs (?)
486
487 #|
488 (defvar *fop-counts* (make-array 256 :initial-element 0))
489 (defvar *fop-times* (make-array 256 :initial-element 0))
490 (defvar *print-fops* nil)
491
492 (defun clear-counts ()
493   (fill (the simple-vector *fop-counts*) 0)
494   (fill (the simple-vector *fop-times*) 0)
495   t)
496
497 (defun analyze-counts ()
498   (let ((counts ())
499         (total-count 0)
500         (times ())
501         (total-time 0))
502     (macrolet ((breakdown (lvar tvar vec)
503                  `(progn
504                    (dotimes (i 255)
505                      (declare (fixnum i))
506                      (let ((n (svref ,vec i)))
507                        (push (cons (svref *fop-names* i) n) ,lvar)
508                        (incf ,tvar n)))
509                    (setq ,lvar (subseq (sort ,lvar (lambda (x y)
510                                                      (> (cdr x) (cdr y))))
511                                        0 10)))))
512
513       (breakdown counts total-count *fop-counts*)
514       (breakdown times total-time *fop-times*)
515       (format t "Total fop count is ~D~%" total-count)
516       (dolist (c counts)
517         (format t "~30S: ~4D~%" (car c) (cdr c)))
518       (format t "~%Total fop time is ~D~%" (/ (float total-time) 60.0))
519       (dolist (m times)
520         (format t "~30S: ~6,2F~%" (car m) (/ (float (cdr m)) 60.0))))))
521 |#
522