0.pre8.108:
[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 ;;; This expands into code to read an N-byte unsigned integer using
55 ;;; FAST-READ-BYTE.
56 (defmacro fast-read-u-integer (n)
57   (declare (optimize (speed 0)))
58   (do ((res '(fast-read-byte)
59             `(logior (fast-read-byte)
60                      (ash ,res 8)))
61        (cnt 1 (1+ cnt)))
62       ((>= cnt n) res)))
63
64 ;;; like FAST-READ-U-INTEGER, but the size may be determined at run time
65 (defmacro fast-read-var-u-integer (n)
66   (let ((n-pos (gensym))
67         (n-res (gensym))
68         (n-cnt (gensym)))
69     `(do ((,n-pos 8 (+ ,n-pos 8))
70           (,n-cnt (1- ,n) (1- ,n-cnt))
71           (,n-res
72            (fast-read-byte)
73            (dpb (fast-read-byte) (byte 8 ,n-pos) ,n-res)))
74          ((zerop ,n-cnt) ,n-res)
75        (declare (type index ,n-pos ,n-cnt)))))
76
77 ;;; Read a signed integer.
78 (defmacro fast-read-s-integer (n)
79   (declare (optimize (speed 0)))
80   (let ((n-last (gensym)))
81     (do ((res `(let ((,n-last (fast-read-byte)))
82                  (if (zerop (logand ,n-last #x80))
83                      ,n-last
84                      (logior ,n-last #x-100)))
85               `(logior (fast-read-byte)
86                        (ash (the (signed-byte ,(* cnt 8)) ,res) 8)))
87          (cnt 1 (1+ cnt)))
88         ((>= cnt n) res))))
89
90 ;;; Read an N-byte unsigned integer from the *FASL-INPUT-STREAM*
91 (defmacro read-arg (n)
92   (declare (optimize (speed 0)))
93   (if (= n 1)
94       `(the (unsigned-byte 8) (read-byte *fasl-input-stream*))
95       `(prepare-for-fast-read-byte *fasl-input-stream*
96          (prog1
97           (fast-read-u-integer ,n)
98           (done-with-fast-read-byte)))))
99
100 ;;; FIXME: This deserves a more descriptive name, and should probably
101 ;;; be implemented as an ordinary function, not a macro.
102 ;;;
103 ;;; (for the names: There seem to be only two cases, so it could be
104 ;;; named READ-U-INTEGER-8 and READ-U-INTEGER-32 or something.)
105 \f
106 ;;;; the fop table
107
108 ;;; The table is implemented as a simple-vector indexed by the table
109 ;;; offset. We may need to have several, since LOAD can be called
110 ;;; recursively.
111
112 ;;; a list of free fop tables for the fasloader
113 ;;;
114 ;;; FIXME: Is it really a win to have this permanently bound?
115 ;;; Couldn't we just bind it on entry to LOAD-AS-FASL?
116 (defvar *free-fop-tables* (list (make-array 1000)))
117
118 ;;; the current fop table
119 (defvar *current-fop-table*)
120 (declaim (simple-vector *current-fop-table*))
121
122 ;;; the length of the current fop table
123 (defvar *current-fop-table-size*)
124 (declaim (type index *current-fop-table-size*))
125
126 ;;; the index in the fop-table of the next entry to be used
127 (defvar *current-fop-table-index*)
128 (declaim (type index *current-fop-table-index*))
129
130 (defun grow-fop-table ()
131   (let* ((new-size (* *current-fop-table-size* 2))
132          (new-table (make-array new-size)))
133     (declare (fixnum new-size) (simple-vector new-table))
134     (replace new-table (the simple-vector *current-fop-table*))
135     (setq *current-fop-table* new-table)
136     (setq *current-fop-table-size* new-size)))
137
138 (defmacro push-fop-table (thing)
139   (let ((n-index (gensym)))
140     `(let ((,n-index *current-fop-table-index*))
141        (declare (fixnum ,n-index))
142        (when (= ,n-index (the fixnum *current-fop-table-size*))
143          (grow-fop-table))
144        (setq *current-fop-table-index* (1+ ,n-index))
145        (setf (svref *current-fop-table* ,n-index) ,thing))))
146 \f
147 ;;;; the fop stack
148
149 ;;; (This is in a SIMPLE-VECTOR, but it grows down, since it is
150 ;;; somewhat cheaper to test for overflow that way.)
151 (defvar *fop-stack* (make-array 100))
152 (declaim (simple-vector *fop-stack*))
153
154 ;;; the index of the most recently pushed item on the fop stack
155 (defvar *fop-stack-pointer* 100)
156
157 ;;; the current index into the fop stack when we last recursively
158 ;;; entered LOAD
159 (defvar *fop-stack-pointer-on-entry*)
160 (declaim (type index *fop-stack-pointer* *fop-stack-pointer-on-entry*))
161
162 (defun grow-fop-stack ()
163   (let* ((size (length (the simple-vector *fop-stack*)))
164          (new-size (* size 2))
165          (new-stack (make-array new-size)))
166     (declare (fixnum size new-size) (simple-vector new-stack))
167     (replace new-stack (the simple-vector *fop-stack*) :start1 size)
168     (incf *fop-stack-pointer-on-entry* size)
169     (setq *fop-stack-pointer* size)
170     (setq *fop-stack* new-stack)))
171
172 ;;; Cache information about the fop stack in local variables. Define a
173 ;;; local macro to pop from the stack. Push the result of evaluation
174 ;;; if specified.
175 (defmacro with-fop-stack (pushp &body forms)
176   (aver (member pushp '(nil t :nope)))
177   (let ((n-stack (gensym))
178         (n-index (gensym))
179         (n-res (gensym)))
180     `(let ((,n-stack *fop-stack*)
181            (,n-index *fop-stack-pointer*))
182        (declare (simple-vector ,n-stack) (type index ,n-index))
183        (macrolet ((pop-stack ()
184                     `(prog1
185                       (svref ,',n-stack ,',n-index)
186                       (incf ,',n-index)))
187                   (call-with-popped-things (fun n)
188                     (let ((n-start (gensym)))
189                       `(let ((,n-start (+ ,',n-index ,n)))
190                          (declare (type index ,n-start))
191                          (setq ,',n-index ,n-start)
192                          (,fun ,@(make-list n :initial-element
193                                             `(svref ,',n-stack
194                                                     (decf ,n-start))))))))
195          ,(if pushp
196               `(let ((,n-res (progn ,@forms)))
197                  (when (zerop ,n-index)
198                    (grow-fop-stack)
199                    (setq ,n-index *fop-stack-pointer*
200                          ,n-stack *fop-stack*))
201                  (decf ,n-index)
202                  (setq *fop-stack-pointer* ,n-index)
203                  (setf (svref ,n-stack ,n-index) ,n-res))
204               `(prog1
205                 (progn ,@forms)
206                 (setq *fop-stack-pointer* ,n-index)))))))
207 \f
208 ;;;; LOAD-AS-FASL
209 ;;;;
210 ;;;; Note: LOAD-AS-FASL is used not only by LOAD, but also (with
211 ;;;; suitable modification of the fop table) in GENESIS. Therefore,
212 ;;;; it's needed not only in the target Lisp, but also in the
213 ;;;; cross-compilation host.
214
215 ;;; a helper function for LOAD-FASL-GROUP
216 ;;;
217 ;;; Return true if we successfully read a FASL header from the stream,
218 ;;; or NIL if EOF was hit before anything was read. Signal an error if
219 ;;; we encounter garbage.
220 (defun check-fasl-header (stream)
221
222   (let ((byte (read-byte stream nil)))
223     (when byte
224
225       ;; Read and validate constant string prefix in fasl header.
226       (let* ((fhsss *fasl-header-string-start-string*)
227              (fhsss-length (length fhsss)))
228         (unless (= byte (char-code (schar fhsss 0)))
229           (error "illegal first byte in fasl file header"))
230         (do ((byte (read-byte stream) (read-byte stream))
231              (count 1 (1+ count)))
232             ((= byte +fasl-header-string-stop-char-code+)
233              t)
234           (declare (fixnum byte count))
235           (when (and (< count fhsss-length)
236                      (not (eql byte (char-code (schar fhsss count)))))
237             (error
238              "illegal subsequent (not first) byte in fasl file header"))))
239
240       ;; Read and validate version-specific compatibility stuff.
241       (flet ((string-from-stream ()
242                (let* ((length (read-arg 4))
243                       (result (make-string length)))
244                  (read-string-as-bytes stream result)
245                  result)))
246         ;; Read and validate implementation and version.
247         (let* ((implementation (keywordicate (string-from-stream)))
248                ;; FIXME: The logic above to read a keyword from the fasl file
249                ;; could probably be shared with the read-a-keyword fop.
250                (version (read-arg 4)))
251           (flet ((check-version (variant
252                                  possible-implementation
253                                  needed-version)
254                    (when (string= possible-implementation implementation)
255                      (or (= version needed-version)
256                          (error "~@<~S is in ~A fasl file format version ~W, ~
257                                  but this version of SBCL uses ~
258                                  format version ~W.~:@>"
259                                 stream
260                                 variant
261                                 version
262                                 needed-version)))))
263             (or (check-version "native code"
264                                +backend-fasl-file-implementation+
265                                +fasl-file-version+)
266                 (error "~S was compiled for implementation ~A, ~
267                         but this is a ~A."
268                        stream
269                        implementation
270                        +backend-fasl-file-implementation+))))
271         ;; Read and validate *FEATURES* which affect binary compatibility.
272         (let ((faff-in-this-file (string-from-stream)))
273           (unless (string= faff-in-this-file *features-affecting-fasl-format*)
274             (error
275              "~@<incompatible ~S in fasl file ~S: ~2I~_~
276               Of features affecting binary compatibility, ~4I~_~S~2I~_~
277               this runtime has ~4I~_~A,~2I~_~
278               while the fasl expects ~4I~_~A.~:>"
279              '*features* 
280              stream
281              *features-potentially-affecting-fasl-format*
282              *features-affecting-fasl-format*
283              faff-in-this-file)))
284         ;; success
285         t))))
286
287 ;; Setting this variable gives you a trace of fops as they are loaded and
288 ;; executed.
289 #!+sb-show
290 (defvar *show-fops-p* nil)
291
292 ;;; a helper function for LOAD-AS-FASL
293 ;;;
294 ;;; Return true if we successfully load a group from the stream, or
295 ;;; NIL if EOF was encountered while trying to read from the stream.
296 ;;; Dispatch to the right function for each fop. Special-case
297 ;;; FOP-BYTE-PUSH since it is real common.
298 (defun load-fasl-group (stream)
299   (when (check-fasl-header stream)
300     (catch 'fasl-group-end
301       (let ((*current-fop-table-index* 0))
302         (loop
303           (let ((byte (read-byte stream)))
304
305             ;; Do some debugging output.
306             #!+sb-show
307             (when *show-fops-p*
308               (let ((ptr *fop-stack-pointer*)
309                     (stack *fop-stack*))
310                 (fresh-line *trace-output*)
311                 ;; The FOP operations are stack based, so it's sorta
312                 ;; logical to display the operand before the operator.
313                 ;; ("reverse Polish notation")
314                 (unless (= ptr (length stack))
315                   (write-char #\space *trace-output*)
316                   (prin1 (svref stack ptr) *trace-output*)
317                   (terpri *trace-output*))
318                 ;; Display the operator.
319                 (format *trace-output*
320                         "~&~S (#X~X at ~D) (~S)~%"
321                         (svref *fop-names* byte)
322                         byte
323                         (1- (file-position stream))
324                         (svref *fop-funs* byte))))
325
326             ;; Actually execute the fop.
327             (if (eql byte 3)
328               ;; FIXME: This is the special case for FOP-BYTE-PUSH.
329               ;; Benchmark to see whether it's really worth special
330               ;; casing it. If it is, at least express the test in
331               ;; terms of a symbolic name for the FOP-BYTE-PUSH code,
332               ;; not a bare '3' (!). Failing that, remove the special
333               ;; case (and the comment at the head of this function
334               ;; which mentions it).
335               (let ((index *fop-stack-pointer*))
336                 (declare (type index index))
337                 (when (zerop index)
338                   (grow-fop-stack)
339                   (setq index *fop-stack-pointer*))
340                 (decf index)
341                 (setq *fop-stack-pointer* index)
342                 (setf (svref *fop-stack* index)
343                       (svref *current-fop-table* (read-byte stream))))
344               (funcall (the function (svref *fop-funs* byte))))))))))
345
346 (defun load-as-fasl (stream verbose print)
347   ;; KLUDGE: ANSI says it's good to do something with the :PRINT
348   ;; argument to LOAD when we're fasloading a file, but currently we
349   ;; don't. (CMU CL did, but implemented it in a non-ANSI way, and I
350   ;; just disabled that instead of rewriting it.) -- WHN 20000131
351   (declare (ignore print))
352   (when (zerop (file-length stream))
353     (error "attempt to load an empty FASL file:~%  ~S" (namestring stream)))
354   (maybe-announce-load stream verbose)
355   (sb!thread:with-recursive-lock (sb!c::*big-compiler-lock*)
356     (let* ((*fasl-input-stream* stream)
357            (*current-fop-table* (or (pop *free-fop-tables*) (make-array 1000)))
358            (*current-fop-table-size* (length *current-fop-table*))
359            (*fop-stack-pointer-on-entry* *fop-stack-pointer*))
360       (unwind-protect
361            (loop while (load-fasl-group stream))
362         (setq *fop-stack-pointer* *fop-stack-pointer-on-entry*)
363         (push *current-fop-table* *free-fop-tables*)
364         ;; NIL out the stack and table, so that we don't hold onto garbage.
365         ;;
366         ;; FIXME: Couldn't we just get rid of the free fop table pool so
367         ;; that some of this NILing out would go away?
368         (fill *fop-stack* nil :end *fop-stack-pointer-on-entry*)
369         (fill *current-fop-table* nil))))
370   t)
371
372 ;;; This is used in in target-load and also genesis, using
373 ;;; *COLD-FOREIGN-SYMBOL-TABLE*. All the speculative prefix-adding
374 ;;; code for foreign symbol lookup should be here.
375 (defun find-foreign-symbol-in-table (name table)
376   (let ((prefixes
377          #!+(or osf1 sunos linux freebsd) #("" "ldso_stub__")
378          #!+openbsd #("")))
379     (declare (notinline some)) ; to suppress bug 117 bogowarning
380     (some (lambda (prefix)
381             (gethash (concatenate 'string prefix name)
382                      table
383                      nil))
384           prefixes)))
385 \f
386 ;;;; stuff for debugging/tuning by collecting statistics on FOPs (?)
387
388 #|
389 (defvar *fop-counts* (make-array 256 :initial-element 0))
390 (defvar *fop-times* (make-array 256 :initial-element 0))
391 (defvar *print-fops* nil)
392
393 (defun clear-counts ()
394   (fill (the simple-vector *fop-counts*) 0)
395   (fill (the simple-vector *fop-times*) 0)
396   t)
397
398 (defun analyze-counts ()
399   (let ((counts ())
400         (total-count 0)
401         (times ())
402         (total-time 0))
403     (macrolet ((breakdown (lvar tvar vec)
404                  `(progn
405                    (dotimes (i 255)
406                      (declare (fixnum i))
407                      (let ((n (svref ,vec i)))
408                        (push (cons (svref *fop-names* i) n) ,lvar)
409                        (incf ,tvar n)))
410                    (setq ,lvar (subseq (sort ,lvar (lambda (x y)
411                                                      (> (cdr x) (cdr y))))
412                                        0 10)))))
413
414       (breakdown counts total-count *fop-counts*)
415       (breakdown times total-time *fop-times*)
416       (format t "Total fop count is ~D~%" total-count)
417       (dolist (c counts)
418         (format t "~30S: ~4D~%" (car c) (cdr c)))
419       (format t "~%Total fop time is ~D~%" (/ (float total-time) 60.0))
420       (dolist (m times)
421         (format t "~30S: ~6,2F~%" (car m) (/ (float (cdr m)) 60.0))))))
422 |#
423