06655dda1d4b9ea24a35908bebda6ad1cb66d2dd
[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 *big-compiler-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       `(prepare-for-fast-read-byte *fasl-input-stream*
100          (prog1
101           (fast-read-u-integer ,n)
102           (done-with-fast-read-byte)))))
103
104 (declaim (inline read-byte-arg read-halfword-arg read-word-arg))
105 (defun read-byte-arg ()
106   (declare (optimize (speed 0)))
107   (read-arg 1))
108
109 (defun read-halfword-arg ()
110   (declare (optimize (speed 0)))
111   (read-arg #.(/ sb!vm:n-word-bytes 2)))
112
113 (defun read-word-arg ()
114   (declare (optimize (speed 0)))
115   (read-arg #.sb!vm:n-word-bytes))
116
117 \f
118 ;;;; the fop table
119
120 ;;; The table is implemented as a simple-vector indexed by the table
121 ;;; offset. We may need to have several, since LOAD can be called
122 ;;; recursively.
123
124 ;;; a list of free fop tables for the fasloader
125 ;;;
126 ;;; FIXME: Is it really a win to have this permanently bound?
127 ;;; Couldn't we just bind it on entry to LOAD-AS-FASL?
128 (defvar *free-fop-tables* (list (make-array 1000)))
129
130 ;;; the current fop table
131 (defvar *current-fop-table*)
132 (declaim (simple-vector *current-fop-table*))
133
134 ;;; the length of the current fop table
135 (defvar *current-fop-table-size*)
136 (declaim (type index *current-fop-table-size*))
137
138 ;;; the index in the fop-table of the next entry to be used
139 (defvar *current-fop-table-index*)
140 (declaim (type index *current-fop-table-index*))
141
142 (defun grow-fop-table ()
143   (let* ((new-size (* *current-fop-table-size* 2))
144          (new-table (make-array new-size)))
145     (declare (fixnum new-size) (simple-vector new-table))
146     (replace new-table (the simple-vector *current-fop-table*))
147     (setq *current-fop-table* new-table)
148     (setq *current-fop-table-size* new-size)))
149
150 (defmacro push-fop-table (thing)
151   (let ((n-index (gensym)))
152     `(let ((,n-index *current-fop-table-index*))
153        (declare (fixnum ,n-index))
154        (when (= ,n-index (the fixnum *current-fop-table-size*))
155          (grow-fop-table))
156        (setq *current-fop-table-index* (1+ ,n-index))
157        (setf (svref *current-fop-table* ,n-index) ,thing))))
158 \f
159 ;;;; the fop stack
160
161 ;;; (This is to be bound by LOAD to an adjustable (VECTOR T) with
162 ;;; FILL-POINTER, for use as a stack with VECTOR-PUSH-EXTEND.)
163 (defvar *fop-stack*)
164 (declaim (type (vector t) *fop-stack*))
165
166 ;;; Cache information about the fop stack in local variables. Define a
167 ;;; local macro to pop from the stack. Push the result of evaluation
168 ;;; if PUSHP.
169 (defmacro with-fop-stack (pushp &body forms)
170   (aver (member pushp '(nil t :nope)))
171   (with-unique-names (fop-stack)
172     `(let ((,fop-stack *fop-stack*))
173        (declare (type (vector t) ,fop-stack))
174        (macrolet ((pop-stack ()
175                     `(vector-pop ,',fop-stack))
176                   (call-with-popped-args (fun n)
177                     `(%call-with-popped-args ,fun ,n ,',fop-stack)))
178          ,(if pushp
179               `(vector-push-extend (progn ,@forms) ,fop-stack)
180               `(progn ,@forms))))))
181
182 ;;; Call FUN with N arguments popped from STACK.
183 (defmacro %call-with-popped-args (fun n stack)
184   ;; N's integer value must be known at macroexpansion time.
185   (declare (type index n))
186   (with-unique-names (n-stack old-length new-length)
187     (let ((argtmps (make-gensym-list n)))
188       `(let* ((,n-stack ,stack)
189               (,old-length (fill-pointer ,n-stack))
190               (,new-length (- ,old-length ,n))
191               ,@(loop for i from 0 below n collecting
192                       `(,(nth i argtmps)
193                         (aref ,n-stack (+ ,new-length ,i)))))
194         (declare (type (vector t) ,n-stack))
195         (setf (fill-pointer ,n-stack) ,new-length)
196         ;; (For some applications it might be appropriate to FILL the
197         ;; popped area with NIL here, to avoid holding onto garbage. For
198         ;; sbcl-0.8.7.something, though, it shouldn't matter, because
199         ;; we're using this only to pop stuff off *FOP-STACK*, and the
200         ;; entire *FOP-STACK* can be GCed as soon as LOAD returns.)
201         (,fun ,@argtmps)))))
202 \f
203 ;;;; Conditions signalled on invalid fasls (wrong fasl version, etc),
204 ;;;; so that user code (esp. ASDF) can reasonably handle attempts to
205 ;;;; load such fasls by recompiling them, etc. For simplicity's sake
206 ;;;; make only condition INVALID-FASL part of the public interface,
207 ;;;; and keep the guts internal.
208
209 (define-condition invalid-fasl (error)
210   ((stream :reader invalid-fasl-stream :initarg :stream)
211    (expected :reader invalid-fasl-expected :initarg :expected))
212   (:report
213    (lambda (condition stream)
214      (format stream "~S is an invalid fasl file."
215              (invalid-fasl-stream condition)))))
216
217 (define-condition invalid-fasl-header (invalid-fasl)
218   ((byte :reader invalid-fasl-byte :initarg :byte)
219    (byte-nr :reader invalid-fasl-byte-nr :initarg :byte-nr))
220   (:report
221    (lambda (condition stream)
222      (format stream "~@<~S contains an illegal byte in the FASL header at ~
223                      position ~A: Expected ~A, got ~A.~:@>"
224              (invalid-fasl-stream condition)
225              (invalid-fasl-byte-nr condition)
226              (invalid-fasl-byte condition)
227              (invalid-fasl-expected condition)))))
228
229 (define-condition invalid-fasl-version (invalid-fasl)
230   ((variant :reader invalid-fasl-variant :initarg :variant)
231    (version :reader invalid-fasl-version :initarg :version))
232   (:report
233    (lambda (condition stream)
234      (format stream "~@<~S is in ~A fasl file format version ~W, ~
235                     but this version of SBCL uses format version ~W.~:@>"
236              (invalid-fasl-stream condition)
237              (invalid-fasl-variant condition)
238              (invalid-fasl-version condition)
239              (invalid-fasl-expected condition)))))
240
241 (define-condition invalid-fasl-implementation (invalid-fasl)
242   ((implementation :reader invalid-fasl-implementation
243                    :initarg :implementation))
244   (:report 
245    (lambda (condition stream)
246      (format stream "~S was compiled for implementation ~A, but this is a ~A."
247              (invalid-fasl-stream condition)
248              (invalid-fasl-implementation condition)
249              (invalid-fasl-expected condition)))))
250
251 (define-condition invalid-fasl-features (invalid-fasl)
252   ((potential-features :reader invalid-fasl-potential-features
253                        :initarg :potential-features)
254    (features :reader invalid-fasl-features :initarg :features))
255   (:report
256    (lambda (condition stream)
257      (format stream "~@<incompatible ~S in fasl file ~S: ~2I~_~
258                      Of features affecting binary compatibility, ~4I~_~S~2I~_~
259                      the fasl has ~4I~_~A,~2I~_~
260                      while the runtime expects ~4I~_~A.~:>"
261              '*features* 
262              (invalid-fasl-stream condition)
263              (invalid-fasl-potential-features condition)
264              (invalid-fasl-features condition)
265              (invalid-fasl-expected condition)))))
266
267 ;;;; LOAD-AS-FASL
268 ;;;;
269 ;;;; Note: LOAD-AS-FASL is used not only by LOAD, but also (with
270 ;;;; suitable modification of the fop table) in GENESIS. Therefore,
271 ;;;; it's needed not only in the target Lisp, but also in the
272 ;;;; cross-compilation host.
273
274 ;;; a helper function for LOAD-FASL-GROUP
275 ;;;
276 ;;; Return true if we successfully read a FASL header from the stream,
277 ;;; or NIL if EOF was hit before anything was read. Signal an error if
278 ;;; we encounter garbage.
279 (defun check-fasl-header (stream)
280
281   (let ((byte (read-byte stream nil)))
282     (when byte
283
284       ;; Read and validate constant string prefix in fasl header.
285       (let* ((fhsss *fasl-header-string-start-string*)
286              (fhsss-length (length fhsss)))
287         (unless (= byte (char-code (schar fhsss 0)))
288           (error 'invalid-fasl-header
289                  :stream stream
290                  :first-byte-p t
291                  :byte byte
292                  :expected (char-code (schar fhsss 0))))
293         (do ((byte (read-byte stream) (read-byte stream))
294              (count 1 (1+ count)))
295             ((= byte +fasl-header-string-stop-char-code+)
296              t)
297           (declare (fixnum byte count))
298           (when (and (< count fhsss-length)
299                      (not (eql byte (char-code (schar fhsss count)))))
300             (error 'invalid-fasl-header
301                    :stream stream
302                    :byte-nr count
303                    :byte byte
304                    :expected (char-code (schar fhsss count))))))
305
306       ;; Read and validate version-specific compatibility stuff.
307       (flet ((string-from-stream ()
308                (let* ((length (read-word-arg))
309                       (result (make-string length)))
310                  (read-string-as-bytes stream result)
311                  result)))
312         ;; Read and validate implementation and version.
313         (let* ((implementation (keywordicate (string-from-stream)))
314                ;; FIXME: The logic above to read a keyword from the fasl file
315                ;; could probably be shared with the read-a-keyword fop.
316                (version (read-word-arg)))
317           (flet ((check-version (variant
318                                  possible-implementation
319                                  needed-version)
320                    (when (string= possible-implementation implementation)
321                      (or (= version needed-version)
322                          (error 'invalid-fasl-version
323                                 ;; :error :wrong-version
324                                 :stream stream
325                                 :variant variant
326                                 :version version
327                                 :expected needed-version)))))
328             (or (check-version "native code"
329                                +backend-fasl-file-implementation+
330                                +fasl-file-version+)
331                 (error 'invalid-fasl-implementation
332                        :stream stream
333                        :implementation implementation
334                        :expected +backend-fasl-file-implementation+))))
335         ;; Read and validate *FEATURES* which affect binary compatibility.
336         (let ((faff-in-this-file (string-from-stream)))
337           (unless (string= faff-in-this-file *features-affecting-fasl-format*)
338             (error 'invalid-fasl-features
339                    :stream stream
340                    :potential-features *features-potentially-affecting-fasl-format*
341                    :expected *features-affecting-fasl-format*
342                    :features faff-in-this-file)))
343         ;; success
344         t))))
345
346 ;; Setting this variable gives you a trace of fops as they are loaded and
347 ;; executed.
348 #!+sb-show
349 (defvar *show-fops-p* nil)
350
351 ;; buffer for loading symbols
352 (defvar *fasl-symbol-buffer*)
353 (declaim (simple-string *fasl-symbol-buffer*))
354
355 ;;; 
356 ;;; a helper function for LOAD-AS-FASL
357 ;;;
358 ;;; Return true if we successfully load a group from the stream, or
359 ;;; NIL if EOF was encountered while trying to read from the stream.
360 ;;; Dispatch to the right function for each fop. 
361 (defun load-fasl-group (stream)
362   (when (check-fasl-header stream)
363     (catch 'fasl-group-end
364       (let ((*current-fop-table-index* 0))
365         (loop
366           (let ((byte (read-byte stream)))
367
368             ;; Do some debugging output.
369             #!+sb-show
370             (when *show-fops-p*
371               (let* ((stack *fop-stack*)
372                      (ptr (1- (fill-pointer *fop-stack*))))
373                 (fresh-line *trace-output*)
374                 ;; The FOP operations are stack based, so it's sorta
375                 ;; logical to display the operand before the operator.
376                 ;; ("reverse Polish notation")
377                 (unless (= ptr -1)
378                   (write-char #\space *trace-output*)
379                   (prin1 (aref stack ptr) *trace-output*)
380                   (terpri *trace-output*))
381                 ;; Display the operator.
382                 (format *trace-output*
383                         "~&~S (#X~X at ~D) (~S)~%"
384                         (aref *fop-names* byte)
385                         byte
386                         (1- (file-position stream))
387                         (svref *fop-funs* byte))))
388
389             ;; Actually execute the fop.
390             (funcall (the function (svref *fop-funs* byte)))))))))
391
392 (defun load-as-fasl (stream verbose print)
393   ;; KLUDGE: ANSI says it's good to do something with the :PRINT
394   ;; argument to LOAD when we're fasloading a file, but currently we
395   ;; don't. (CMU CL did, but implemented it in a non-ANSI way, and I
396   ;; just disabled that instead of rewriting it.) -- WHN 20000131
397   (declare (ignore print))
398   (when (zerop (file-length stream))
399     (error "attempt to load an empty FASL file:~%  ~S" (namestring stream)))
400   (maybe-announce-load stream verbose)
401   (sb!thread:with-recursive-lock (sb!c::*big-compiler-lock*)
402     (let* ((*fasl-input-stream* stream)
403            (*fasl-symbol-buffer* (make-string 100))
404            (*current-fop-table* (or (pop *free-fop-tables*) (make-array 1000)))
405            (*current-fop-table-size* (length *current-fop-table*))
406            (*fop-stack* (make-array 100 :fill-pointer 0 :adjustable t)))
407       (unwind-protect
408            (loop while (load-fasl-group stream))
409         (push *current-fop-table* *free-fop-tables*)
410         ;; NIL out the table, so that we don't hold onto garbage.
411         ;;
412         ;; FIXME: Could we just get rid of the free fop table pool so
413         ;; that this would go away?
414         (fill *current-fop-table* nil))))
415   t)
416
417 ;;; This is used in in target-load and also genesis, using
418 ;;; *COLD-FOREIGN-SYMBOL-TABLE*. All the speculative prefix-adding
419 ;;; code for foreign symbol lookup should be here.
420 (defun find-foreign-symbol-in-table (name table)
421   (let ((prefixes
422          #!+(or osf1 sunos linux freebsd netbsd darwin) #("" "ldso_stub__")
423          #!+openbsd #("")))
424     (declare (notinline some)) ; to suppress bug 117 bogowarning
425     (some (lambda (prefix)
426             (gethash (concatenate 'string prefix name)
427                      table
428                      nil))
429           prefixes)))
430 \f
431 ;;;; stuff for debugging/tuning by collecting statistics on FOPs (?)
432
433 #|
434 (defvar *fop-counts* (make-array 256 :initial-element 0))
435 (defvar *fop-times* (make-array 256 :initial-element 0))
436 (defvar *print-fops* nil)
437
438 (defun clear-counts ()
439   (fill (the simple-vector *fop-counts*) 0)
440   (fill (the simple-vector *fop-times*) 0)
441   t)
442
443 (defun analyze-counts ()
444   (let ((counts ())
445         (total-count 0)
446         (times ())
447         (total-time 0))
448     (macrolet ((breakdown (lvar tvar vec)
449                  `(progn
450                    (dotimes (i 255)
451                      (declare (fixnum i))
452                      (let ((n (svref ,vec i)))
453                        (push (cons (svref *fop-names* i) n) ,lvar)
454                        (incf ,tvar n)))
455                    (setq ,lvar (subseq (sort ,lvar (lambda (x y)
456                                                      (> (cdr x) (cdr y))))
457                                        0 10)))))
458
459       (breakdown counts total-count *fop-counts*)
460       (breakdown times total-time *fop-times*)
461       (format t "Total fop count is ~D~%" total-count)
462       (dolist (c counts)
463         (format t "~30S: ~4D~%" (car c) (cdr c)))
464       (format t "~%Total fop time is ~D~%" (/ (float total-time) 60.0))
465       (dolist (m times)
466         (format t "~30S: ~6,2F~%" (car m) (/ (float (cdr m)) 60.0))))))
467 |#
468