6cffe9117f5d2226b8f90a5650e5b8eb8b3a0d43
[sbcl.git] / src / compiler / dump.lisp
1 ;;;; stuff that knows about dumping FASL files
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!FASL")
13 ;;; KLUDGE: Even though we're IN-PACKAGE SB!FASL, some of the code in
14 ;;; here is awfully chummy with the SB!C package. CMU CL didn't have
15 ;;; any separation between the two packages, and a lot of tight
16 ;;; coupling remains. -- WHN 2001-06-04
17 \f
18 ;;;; fasl dumper state
19
20 ;;; The FASL-OUTPUT structure represents everything we need to
21 ;;; know about dumping to a fasl file. (We need to objectify the
22 ;;; state because the fasdumper must be reentrant.)
23 (defstruct (fasl-output
24             #-no-ansi-print-object
25             (:print-object (lambda (x s)
26                              (print-unreadable-object (x s :type t)
27                                (prin1 (namestring (fasl-output-stream x))
28                                       s))))
29             (:copier nil))
30   ;; the stream we dump to
31   (stream (missing-arg) :type stream)
32   ;; hashtables we use to keep track of dumped constants so that we
33   ;; can get them from the table rather than dumping them again. The
34   ;; EQUAL-TABLE is used for lists and strings, and the EQ-TABLE is
35   ;; used for everything else. We use a separate EQ table to avoid
36   ;; performance pathologies with objects for which EQUAL degenerates
37   ;; to EQL. Everything entered in the EQUAL table is also entered in
38   ;; the EQ table.
39   (equal-table (make-hash-table :test 'equal) :type hash-table)
40   (eq-table (make-hash-table :test 'eq) :type hash-table)
41   ;; the table's current free pointer: the next offset to be used
42   (table-free 0 :type index)
43   ;; an alist (PACKAGE . OFFSET) of the table offsets for each package
44   ;; we have currently located.
45   (packages () :type list)
46   ;; a table mapping from the ENTRY-INFO structures for dumped XEPs to
47   ;; the table offsets of the corresponding code pointers
48   (entry-table (make-hash-table :test 'eq) :type hash-table)
49   ;; a table holding back-patching info for forward references to XEPs.
50   ;; The key is the ENTRY-INFO structure for the XEP, and the value is
51   ;; a list of conses (<code-handle> . <offset>), where <code-handle>
52   ;; is the offset in the table of the code object needing to be
53   ;; patched, and <offset> is the offset that must be patched.
54   (patch-table (make-hash-table :test 'eq) :type hash-table)
55   ;; a list of the table handles for all of the DEBUG-INFO structures
56   ;; dumped in this file. These structures must be back-patched with
57   ;; source location information when the compilation is complete.
58   (debug-info () :type list)
59   ;; This is used to keep track of objects that we are in the process
60   ;; of dumping so that circularities can be preserved. The key is the
61   ;; object that we have previously seen, and the value is the object
62   ;; that we reference in the table to find this previously seen
63   ;; object. (The value is never NIL.)
64   ;;
65   ;; Except with list objects, the key and the value are always the
66   ;; same. In a list, the key will be some tail of the value.
67   (circularity-table (make-hash-table :test 'eq) :type hash-table)
68   ;; a hash table of structures that are allowed to be dumped. If we
69   ;; try to dump a structure that isn't in this hash table, we lose.
70   (valid-structures (make-hash-table :test 'eq) :type hash-table))
71
72 ;;; This structure holds information about a circularity.
73 (defstruct (circularity (:copier nil))
74   ;; the kind of modification to make to create circularity
75   (type (missing-arg) :type (member :rplaca :rplacd :svset :struct-set))
76   ;; the object containing circularity
77   object
78   ;; index in object for circularity
79   (index (missing-arg) :type index)
80   ;; the object to be stored at INDEX in OBJECT. This is that the key
81   ;; that we were using when we discovered the circularity.
82   value
83   ;; the value that was associated with VALUE in the
84   ;; CIRCULARITY-TABLE. This is the object that we look up in the
85   ;; EQ-TABLE to locate VALUE.
86   enclosing-object)
87
88 ;;; a list of the CIRCULARITY structures for all of the circularities
89 ;;; detected in the current top level call to DUMP-OBJECT. Setting
90 ;;; this lobotomizes circularity detection as well, since circular
91 ;;; dumping uses the table.
92 (defvar *circularities-detected*)
93
94 ;;; used to inhibit table access when dumping forms to be read by the
95 ;;; cold loader
96 (defvar *cold-load-dump* nil)
97
98 ;;; used to turn off the structure validation during dumping of source
99 ;;; info
100 (defvar *dump-only-valid-structures* t)
101 ;;;; utilities
102
103 ;;; Write the byte B to the specified FASL-OUTPUT stream.
104 (defun dump-byte (b fasl-output)
105   (declare (type (unsigned-byte 8) b) (type fasl-output fasl-output))
106   (write-byte b (fasl-output-stream fasl-output)))
107
108 ;; Dump a word-sized integer.
109 (defun dump-word (num fasl-output)
110   (declare (type sb!vm:word num))
111   (declare (type fasl-output fasl-output))
112   (let ((stream (fasl-output-stream fasl-output)))
113     (dotimes (i sb!vm:n-word-bytes)
114       (write-byte (ldb (byte 8 (* 8 i)) num) stream))))
115
116 ;; Dump a 32-bit integer.
117 (defun dump-unsigned-byte-32 (num fasl-output)
118   (declare (type sb!vm:word num))
119   (declare (type fasl-output fasl-output))
120   (let ((stream (fasl-output-stream fasl-output)))
121     (dotimes (i 4)
122       (write-byte (ldb (byte 8 (* 8 i)) num) stream))))
123
124 ;;; Dump NUM to the fasl stream, represented by N bytes. This works
125 ;;; for either signed or unsigned integers. There's no range checking
126 ;;; -- if you don't specify enough bytes for the number to fit, this
127 ;;; function cheerfully outputs the low bytes.
128 (defun dump-integer-as-n-bytes  (num bytes fasl-output)
129   (declare (integer num) (type index bytes))
130   (declare (type fasl-output fasl-output))
131   (do ((n num (ash n -8))
132        (i bytes (1- i)))
133       ((= i 0))
134     (declare (type index i))
135     (dump-byte (logand n #xff) fasl-output))
136   (values))
137
138 ;;; Setting this variable to an (UNSIGNED-BYTE 32) value causes
139 ;;; DUMP-FOP to use it as a counter and emit a FOP-NOP4 with the
140 ;;; counter value before every ordinary fop. This can make it easier
141 ;;; to follow the progress of LOAD-AS-FASL when
142 ;;; debugging/testing/experimenting.
143 #!+sb-show (defvar *fop-nop4-count* nil)
144 #!+sb-show (declaim (type (or (unsigned-byte 32) null) *fop-nop4-count*))
145
146 ;;; Dump the FOP code for the named FOP to the specified FASL-OUTPUT.
147 ;;;
148 ;;; FIXME: This should be a function, with a compiler macro expansion
149 ;;; for the common constant-FS case. (Among other things, that'll stop
150 ;;; it from EVALing ,FILE multiple times.)
151 ;;;
152 ;;; FIXME: Compiler macros, frozen classes, inlining, and similar
153 ;;; optimizations should be conditional on #!+SB-FROZEN.
154 (defmacro dump-fop (fs file)
155   (let* ((fs (eval fs))
156          (val (get fs 'fop-code)))
157     (if val
158       `(progn
159          #!+sb-show
160          (when *fop-nop4-count*
161            (dump-byte ,(get 'fop-nop4 'fop-code) ,file)
162            (dump-integer-as-n-bytes (mod (incf *fop-nop4-count*) (expt 2 32))
163                                     4 ,file))
164          (dump-byte ',val ,file))
165       (error "compiler bug: ~S is not a legal fasload operator." fs))))
166
167 ;;; Dump a FOP-CODE along with an integer argument, choosing the FOP
168 ;;; based on whether the argument will fit in a single byte.
169 ;;;
170 ;;; FIXME: This, like DUMP-FOP, should be a function with a
171 ;;; compiler-macro expansion.
172 (defmacro dump-fop* (n byte-fop word-fop file)
173   (once-only ((n-n n)
174               (n-file file))
175     `(cond ((< ,n-n 256)
176             (dump-fop ',byte-fop ,n-file)
177             (dump-byte ,n-n ,n-file))
178            (t
179             (dump-fop ',word-fop ,n-file)
180             (dump-word ,n-n ,n-file)))))
181
182 ;;; Push the object at table offset Handle on the fasl stack.
183 (defun dump-push (handle fasl-output)
184   (declare (type index handle) (type fasl-output fasl-output))
185   (dump-fop* handle fop-byte-push fop-push fasl-output)
186   (values))
187
188 ;;; Pop the object currently on the fasl stack top into the table, and
189 ;;; return the table index, incrementing the free pointer.
190 (defun dump-pop (fasl-output)
191   (prog1
192       (fasl-output-table-free fasl-output)
193     (dump-fop 'fop-pop fasl-output)
194     (incf (fasl-output-table-free fasl-output))))
195
196 ;;; If X is in File's EQUAL-TABLE, then push the object and return T,
197 ;;; otherwise NIL. If *COLD-LOAD-DUMP* is true, then do nothing and
198 ;;; return NIL.
199 (defun equal-check-table (x fasl-output)
200   (declare (type fasl-output fasl-output))
201   (unless *cold-load-dump*
202     (let ((handle (gethash x (fasl-output-equal-table fasl-output))))
203       (cond
204         (handle (dump-push handle fasl-output) t)
205         (t nil)))))
206 (defun string-check-table (x fasl-output)
207   (declare (type fasl-output fasl-output)
208            (type string x))
209   (unless *cold-load-dump*
210     (let ((handle (cdr (assoc
211                         #+sb-xc-host 'base-char ; for repeatable xc fasls
212                         #-sb-xc-host (array-element-type x)
213                         (gethash x (fasl-output-equal-table fasl-output))))))
214       (cond
215         (handle (dump-push handle fasl-output) t)
216         (t nil)))))
217
218 ;;; These functions are called after dumping an object to save the
219 ;;; object in the table. The object (also passed in as X) must already
220 ;;; be on the top of the FOP stack. If *COLD-LOAD-DUMP* is true, then
221 ;;; we don't do anything.
222 (defun eq-save-object (x fasl-output)
223   (declare (type fasl-output fasl-output))
224   (unless *cold-load-dump*
225     (let ((handle (dump-pop fasl-output)))
226       (setf (gethash x (fasl-output-eq-table fasl-output)) handle)
227       (dump-push handle fasl-output)))
228   (values))
229 (defun equal-save-object (x fasl-output)
230   (declare (type fasl-output fasl-output))
231   (unless *cold-load-dump*
232     (let ((handle (dump-pop fasl-output)))
233       (setf (gethash x (fasl-output-equal-table fasl-output)) handle)
234       (setf (gethash x (fasl-output-eq-table fasl-output)) handle)
235       (dump-push handle fasl-output)))
236   (values))
237 (defun string-save-object (x fasl-output)
238   (declare (type fasl-output fasl-output)
239            (type string x))
240   (unless *cold-load-dump*
241     (let ((handle (dump-pop fasl-output)))
242       (push (cons #+sb-xc-host 'base-char ; repeatable xc fasls
243                   #-sb-xc-host (array-element-type x)
244                   handle)
245             (gethash x (fasl-output-equal-table fasl-output)))
246       (setf (gethash x (fasl-output-eq-table fasl-output)) handle)
247       (dump-push handle fasl-output)))
248   (values))
249 ;;; Record X in File's CIRCULARITY-TABLE unless *COLD-LOAD-DUMP* is
250 ;;; true. This is called on objects that we are about to dump might
251 ;;; have a circular path through them.
252 ;;;
253 ;;; The object must not currently be in this table, since the dumper
254 ;;; should never be recursively called on a circular reference.
255 ;;; Instead, the dumping function must detect the circularity and
256 ;;; arrange for the dumped object to be patched.
257 (defun note-potential-circularity (x fasl-output)
258   (unless *cold-load-dump*
259     (let ((circ (fasl-output-circularity-table fasl-output)))
260       (aver (not (gethash x circ)))
261       (setf (gethash x circ) x)))
262   (values))
263
264 ;;; Dump FORM to a fasl file so that it evaluated at load time in normal
265 ;;; load and at cold-load time in cold load. This is used to dump package
266 ;;; frobbing forms.
267 (defun fasl-dump-cold-load-form (form fasl-output)
268   (declare (type fasl-output fasl-output))
269   (dump-fop 'fop-normal-load fasl-output)
270   (let ((*cold-load-dump* t))
271     (dump-object form fasl-output))
272   (dump-fop 'fop-eval-for-effect fasl-output)
273   (dump-fop 'fop-maybe-cold-load fasl-output)
274   (values))
275 \f
276 ;;;; opening and closing fasl files
277
278 ;;; Open a fasl file, write its header, and return a FASL-OUTPUT
279 ;;; object for dumping to it. Some human-readable information about
280 ;;; the source code is given by the string WHERE.
281 (defun open-fasl-output (name where)
282   (declare (type pathname name))
283   (flet ((fasl-write-string (string stream)
284            ;; SB-EXT:STRING-TO-OCTETS is not available while cross-compiling
285            #+sb-xc-host
286            (loop for char across string
287                  do (let ((code (char-code char)))
288                       (unless (<= 0 code 127)
289                         (setf char #\?))
290                       (write-byte code stream)))
291            ;; UTF-8 is safe to use, because +FASL-HEADER-STRING-STOP-CHAR-CODE+
292            ;; may not appear in UTF-8 encoded bytes
293            #-sb-xc-host
294            (write-sequence (string-to-octets string :external-format :utf-8)
295                            stream)))
296     (let* ((stream (open name
297                          :direction :output
298                          :if-exists :supersede
299                          :element-type 'sb!assem:assembly-unit))
300            (res (make-fasl-output :stream stream)))
301       ;; Begin the header with the constant machine-readable (and
302       ;; semi-human-readable) string which is used to identify fasl files.
303       (fasl-write-string *fasl-header-string-start-string* stream)
304       ;; The constant string which begins the header is followed by
305       ;; arbitrary human-readable text, terminated by
306       ;; +FASL-HEADER-STRING-STOP-CHAR-CODE+.
307       (fasl-write-string
308        (with-standard-io-syntax
309          (let ((*print-readably* nil)
310                (*print-pretty* nil))
311            (format nil
312                    "~%  ~
313                     compiled from ~S~%  ~
314                     at ~A~%  ~
315                     on ~A~%  ~
316                     using ~A version ~A~%"
317                    where
318                    #+sb-xc-host "cross-compile time"
319                    #-sb-xc-host (format-universal-time nil (get-universal-time))
320                    #+sb-xc-host "cross-compile host"
321                    #-sb-xc-host (machine-instance)
322                    (sb!xc:lisp-implementation-type)
323                    (sb!xc:lisp-implementation-version))))
324        stream)
325       (dump-byte +fasl-header-string-stop-char-code+ res)
326       ;; Finish the header by outputting fasl file implementation,
327       ;; version, and key *FEATURES*.
328       (flet ((dump-counted-string (string)
329                ;; The count is dumped as a 32-bit unsigned-byte even on 64-bit
330                ;; platforms. This ensures that a x86-64 SBCL can gracefully
331                ;; detect an error when trying to read a x86 fasl, instead
332                ;; of choking on a ridiculously long counted string.
333                ;;  -- JES, 2005-12-30
334                (dump-unsigned-byte-32 (length string) res)
335                (dotimes (i (length string))
336                  (dump-byte (char-code (aref string i)) res))))
337         (dump-counted-string (symbol-name +backend-fasl-file-implementation+))
338         (dump-word +fasl-file-version+ res)
339         (dump-counted-string (sb!xc:lisp-implementation-version))
340         (dump-counted-string *features-affecting-fasl-format*))
341       res)))
342
343 ;;; Close the specified FASL-OUTPUT, aborting the write if ABORT-P.
344 (defun close-fasl-output (fasl-output abort-p)
345   (declare (type fasl-output fasl-output))
346
347   (unless abort-p
348     ;; sanity checks
349     (aver (zerop (hash-table-count (fasl-output-patch-table fasl-output))))
350     ;; End the group.
351     (dump-fop 'fop-verify-empty-stack fasl-output)
352     (dump-fop 'fop-verify-table-size fasl-output)
353     (dump-word (fasl-output-table-free fasl-output)
354                fasl-output)
355     (dump-fop 'fop-end-group fasl-output))
356
357   ;; That's all, folks.
358   (close (fasl-output-stream fasl-output) :abort abort-p)
359   (values))
360 \f
361 ;;;; main entries to object dumping
362
363 ;;; This function deals with dumping objects that are complex enough
364 ;;; so that we want to cache them in the table, rather than repeatedly
365 ;;; dumping them. If the object is in the EQ-TABLE, then we push it,
366 ;;; otherwise, we do a type dispatch to a type specific dumping
367 ;;; function. The type specific branches do any appropriate
368 ;;; EQUAL-TABLE check and table entry.
369 ;;;
370 ;;; When we go to dump the object, we enter it in the CIRCULARITY-TABLE.
371 (defun dump-non-immediate-object (x file)
372   (let ((index (gethash x (fasl-output-eq-table file))))
373     (cond ((and index (not *cold-load-dump*))
374            (dump-push index file))
375           (t
376            (typecase x
377              (symbol (dump-symbol x file))
378              (list
379               ;; KLUDGE: The code in this case has been hacked
380               ;; to match Douglas Crosher's quick fix to CMU CL
381               ;; (on cmucl-imp 1999-12-27), applied in sbcl-0.6.8.11
382               ;; with help from Martin Atzmueller. This is not an
383               ;; ideal solution; to quote DTC,
384               ;;   The compiler locks up trying to coalesce the
385               ;;   constant lists. The hack below will disable the
386               ;;   coalescing of lists while dumping and allows
387               ;;   the code to compile. The real fix would be to
388               ;;   take a little more care while dumping these.
389               ;; So if better list coalescing is needed, start here.
390               ;; -- WHN 2000-11-07
391               (if (maybe-cyclic-p x)
392                   (progn
393                     (dump-list x file)
394                     (eq-save-object x file))
395                   (unless (equal-check-table x file)
396                     (dump-list x file)
397                     (equal-save-object x file))))
398              (layout
399               (dump-layout x file)
400               (eq-save-object x file))
401              (instance
402               (dump-structure x file)
403               (eq-save-object x file))
404              (array
405               ;; DUMP-ARRAY (and its callees) are responsible for
406               ;; updating the EQ and EQUAL hash tables.
407               (dump-array x file))
408              (number
409               (unless (equal-check-table x file)
410                 (etypecase x
411                   (ratio (dump-ratio x file))
412                   (complex (dump-complex x file))
413                   (float (dump-float x file))
414                   (integer (dump-integer x file)))
415                 (equal-save-object x file)))
416              (t
417               ;; This probably never happens, since bad things tend to
418               ;; be detected during IR1 conversion.
419               (error "This object cannot be dumped into a fasl file:~% ~S"
420                      x))))))
421   (values))
422
423 ;;; Dump an object of any type by dispatching to the correct
424 ;;; type-specific dumping function. We pick off immediate objects,
425 ;;; symbols and magic lists here. Other objects are handled by
426 ;;; DUMP-NON-IMMEDIATE-OBJECT.
427 ;;;
428 ;;; This is the function used for recursive calls to the fasl dumper.
429 ;;; We don't worry about creating circularities here, since it is
430 ;;; assumed that there is a top level call to DUMP-OBJECT.
431 (defun sub-dump-object (x file)
432   (cond ((listp x)
433          (if x
434              (dump-non-immediate-object x file)
435              (dump-fop 'fop-empty-list file)))
436         ((symbolp x)
437          (if (eq x t)
438              (dump-fop 'fop-truth file)
439              (dump-non-immediate-object x file)))
440         ((fixnump x) (dump-integer x file))
441         ((characterp x) (dump-character x file))
442         (t
443          (dump-non-immediate-object x file))))
444
445 ;;; Dump stuff to backpatch already dumped objects. INFOS is the list
446 ;;; of CIRCULARITY structures describing what to do. The patching FOPs
447 ;;; take the value to store on the stack. We compute this value by
448 ;;; fetching the enclosing object from the table, and then CDR'ing it
449 ;;; if necessary.
450 (defun dump-circularities (infos file)
451   (let ((table (fasl-output-eq-table file)))
452     (dolist (info infos)
453
454       (let* ((value (circularity-value info))
455              (enclosing (circularity-enclosing-object info)))
456         (dump-push (gethash enclosing table) file)
457         (unless (eq enclosing value)
458           (do ((current enclosing (cdr current))
459                (i 0 (1+ i)))
460               ((eq current value)
461                (dump-fop 'fop-nthcdr file)
462                (dump-word i file))
463             (declare (type index i)))))
464
465       (ecase (circularity-type info)
466         (:rplaca     (dump-fop 'fop-rplaca    file))
467         (:rplacd     (dump-fop 'fop-rplacd    file))
468         (:svset      (dump-fop 'fop-svset     file))
469         (:struct-set (dump-fop 'fop-structset file)))
470       (dump-word (gethash (circularity-object info) table) file)
471       (dump-word (circularity-index info) file))))
472
473 ;;; Set up stuff for circularity detection, then dump an object. All
474 ;;; shared and circular structure will be exactly preserved within a
475 ;;; single call to DUMP-OBJECT. Sharing between objects dumped by
476 ;;; separate calls is only preserved when convenient.
477 ;;;
478 ;;; We peek at the object type so that we only pay the circular
479 ;;; detection overhead on types of objects that might be circular.
480 (defun dump-object (x file)
481   (if (compound-object-p x)
482       (let ((*circularities-detected* ())
483             (circ (fasl-output-circularity-table file)))
484         (clrhash circ)
485         (sub-dump-object x file)
486         (when *circularities-detected*
487           (dump-circularities *circularities-detected* file)
488           (clrhash circ)))
489       (sub-dump-object x file)))
490 \f
491 ;;;; LOAD-TIME-VALUE and MAKE-LOAD-FORM support
492
493 ;;; Emit a funcall of the function and return the handle for the
494 ;;; result.
495 (defun fasl-dump-load-time-value-lambda (fun file)
496   (declare (type sb!c::clambda fun) (type fasl-output file))
497   (let ((handle (gethash (sb!c::leaf-info fun)
498                          (fasl-output-entry-table file))))
499     (aver handle)
500     (dump-push handle file)
501     (dump-fop 'fop-funcall file)
502     (dump-byte 0 file))
503   (dump-pop file))
504
505 ;;; Return T iff CONSTANT has already been dumped. It's been dumped if
506 ;;; it's in the EQ table.
507 ;;;
508 ;;; Note: historically (1) the above comment was "T iff ... has not been dumped",
509 ;;; (2) the test was  was also true if the constant had been validated / was in
510 ;;; the valid objects table. This led to substructures occasionally skipping the
511 ;;; validation, and hence failing the "must have been validated" test.
512 (defun fasl-constant-already-dumped-p (constant file)
513   (and (gethash constant (fasl-output-eq-table file)) t))
514
515 ;;; Use HANDLE whenever we try to dump CONSTANT. HANDLE should have been
516 ;;; returned earlier by FASL-DUMP-LOAD-TIME-VALUE-LAMBDA.
517 (defun fasl-note-handle-for-constant (constant handle file)
518   (let ((table (fasl-output-eq-table file)))
519     (when (gethash constant table)
520       (error "~S already dumped?" constant))
521     (setf (gethash constant table) handle))
522   (values))
523
524 ;;; Note that the specified structure can just be dumped by
525 ;;; enumerating the slots.
526 (defun fasl-validate-structure (structure file)
527   (setf (gethash structure (fasl-output-valid-structures file)) t)
528   (values))
529 \f
530 ;;;; number dumping
531
532 (defun dump-ratio (x file)
533   (sub-dump-object (numerator x) file)
534   (sub-dump-object (denominator x) file)
535   (dump-fop 'fop-ratio file))
536
537 (defun dump-integer (n file)
538   (typecase n
539     ((signed-byte 8)
540      (dump-fop 'fop-byte-integer file)
541      (dump-byte (logand #xFF n) file))
542     ((unsigned-byte #.(1- sb!vm:n-word-bits))
543      (dump-fop 'fop-word-integer file)
544      (dump-word n file))
545     ((signed-byte #.sb!vm:n-word-bits)
546      (dump-fop 'fop-word-integer file)
547      (dump-integer-as-n-bytes n #.sb!vm:n-word-bytes file))
548     (t
549      (let ((bytes (ceiling (1+ (integer-length n)) 8)))
550        (dump-fop* bytes fop-small-integer fop-integer file)
551        (dump-integer-as-n-bytes n bytes file)))))
552
553 (defun dump-float (x file)
554   (etypecase x
555     (single-float
556      (dump-fop 'fop-single-float file)
557      (dump-integer-as-n-bytes (single-float-bits x) 4 file))
558     (double-float
559      (dump-fop 'fop-double-float file)
560      (let ((x x))
561        (declare (double-float x))
562        (dump-integer-as-n-bytes (double-float-low-bits x) 4 file)
563        (dump-integer-as-n-bytes (double-float-high-bits x) 4 file)))
564     #!+long-float
565     (long-float
566      (dump-fop 'fop-long-float file)
567      (dump-long-float x file))))
568
569 (defun dump-complex (x file)
570   (typecase x
571     #-sb-xc-host
572     ((complex single-float)
573      (dump-fop 'fop-complex-single-float file)
574      (dump-integer-as-n-bytes (single-float-bits (realpart x)) 4 file)
575      (dump-integer-as-n-bytes (single-float-bits (imagpart x)) 4 file))
576     #-sb-xc-host
577     ((complex double-float)
578      (dump-fop 'fop-complex-double-float file)
579      (let ((re (realpart x)))
580        (declare (double-float re))
581        (dump-integer-as-n-bytes (double-float-low-bits re) 4 file)
582        (dump-integer-as-n-bytes (double-float-high-bits re) 4 file))
583      (let ((im (imagpart x)))
584        (declare (double-float im))
585        (dump-integer-as-n-bytes (double-float-low-bits im) 4 file)
586        (dump-integer-as-n-bytes (double-float-high-bits im) 4 file)))
587     #!+long-float
588     ((complex long-float)
589      ;; (There's no easy way to mix #!+LONG-FLOAT and #-SB-XC-HOST
590      ;; conditionalization at read time, so we do this SB-XC-HOST
591      ;; conditional at runtime instead.)
592      #+sb-xc-host (error "can't dump COMPLEX-LONG-FLOAT in cross-compiler")
593      (dump-fop 'fop-complex-long-float file)
594      (dump-long-float (realpart x) file)
595      (dump-long-float (imagpart x) file))
596     (t
597      (sub-dump-object (realpart x) file)
598      (sub-dump-object (imagpart x) file)
599      (dump-fop 'fop-complex file))))
600 \f
601 ;;;; symbol dumping
602
603 ;;; Return the table index of PKG, adding the package to the table if
604 ;;; necessary. During cold load, we read the string as a normal string
605 ;;; so that we can do the package lookup at cold load time.
606 ;;;
607 ;;; FIXME: Despite the parallelism in names, the functionality of
608 ;;; this function is not parallel to other functions DUMP-FOO, e.g.
609 ;;; DUMP-SYMBOL and DUMP-LIST. The mapping between names and behavior
610 ;;; should be made more consistent.
611 (declaim (ftype (function (package fasl-output) index) dump-package))
612 (defun dump-package (pkg file)
613   (declare (inline assoc))
614   (cond ((cdr (assoc pkg (fasl-output-packages file) :test #'eq)))
615         (t
616          (unless *cold-load-dump*
617            (dump-fop 'fop-normal-load file))
618          #+sb-xc-host
619          (dump-simple-base-string
620           (coerce (package-name pkg) 'simple-base-string)
621           file)
622          #-sb-xc-host
623          (#!+sb-unicode dump-simple-character-string
624           #!-sb-unicode dump-simple-base-string
625           (coerce (package-name pkg) '(simple-array character (*)))
626           file)
627          (dump-fop 'fop-package file)
628          (unless *cold-load-dump*
629            (dump-fop 'fop-maybe-cold-load file))
630          (let ((entry (dump-pop file)))
631            (push (cons pkg entry) (fasl-output-packages file))
632            entry))))
633 \f
634 ;;; dumper for lists
635
636 ;;; Dump a list, setting up patching information when there are
637 ;;; circularities. We scan down the list, checking for CDR and CAR
638 ;;; circularities.
639 ;;;
640 ;;; If there is a CDR circularity, we terminate the list with NIL and
641 ;;; make a CIRCULARITY notation for the CDR of the previous cons.
642 ;;;
643 ;;; If there is no CDR circularity, then we mark the current cons and
644 ;;; check for a CAR circularity. When there is a CAR circularity, we
645 ;;; make the CAR NIL initially, arranging for the current cons to be
646 ;;; patched later.
647 ;;;
648 ;;; Otherwise, we recursively call the dumper to dump the current
649 ;;; element.
650 ;;;
651 ;;; Marking of the conses is inhibited when *COLD-LOAD-DUMP* is true.
652 ;;; This inhibits all circularity detection.
653 (defun dump-list (list file)
654   (aver (and list
655              (not (gethash list (fasl-output-circularity-table file)))))
656   (do* ((l list (cdr l))
657         (n 0 (1+ n))
658         (circ (fasl-output-circularity-table file)))
659        ((atom l)
660         (cond ((null l)
661                (terminate-undotted-list n file))
662               (t
663                (sub-dump-object l file)
664                (terminate-dotted-list n file))))
665     (declare (type index n))
666     (let ((ref (gethash l circ)))
667       (when ref
668         (push (make-circularity :type :rplacd
669                                 :object list
670                                 :index (1- n)
671                                 :value l
672                                 :enclosing-object ref)
673               *circularities-detected*)
674         (terminate-undotted-list n file)
675         (return)))
676
677     (unless *cold-load-dump*
678       (setf (gethash l circ) list))
679
680     (let* ((obj (car l))
681            (ref (gethash obj circ)))
682       (cond (ref
683              (push (make-circularity :type :rplaca
684                                      :object list
685                                      :index n
686                                      :value obj
687                                      :enclosing-object ref)
688                    *circularities-detected*)
689              (sub-dump-object nil file))
690             (t
691              (sub-dump-object obj file))))))
692
693 (defun terminate-dotted-list (n file)
694   (declare (type index n) (type fasl-output file))
695   (case n
696     (1 (dump-fop 'fop-list*-1 file))
697     (2 (dump-fop 'fop-list*-2 file))
698     (3 (dump-fop 'fop-list*-3 file))
699     (4 (dump-fop 'fop-list*-4 file))
700     (5 (dump-fop 'fop-list*-5 file))
701     (6 (dump-fop 'fop-list*-6 file))
702     (7 (dump-fop 'fop-list*-7 file))
703     (8 (dump-fop 'fop-list*-8 file))
704     (t (do ((nn n (- nn 255)))
705            ((< nn 256)
706             (dump-fop 'fop-list* file)
707             (dump-byte nn file))
708          (declare (type index nn))
709          (dump-fop 'fop-list* file)
710          (dump-byte 255 file)))))
711
712 ;;; If N > 255, must build list with one LIST operator, then LIST*
713 ;;; operators.
714
715 (defun terminate-undotted-list (n file)
716   (declare (type index n) (type fasl-output file))
717   (case n
718     (1 (dump-fop 'fop-list-1 file))
719     (2 (dump-fop 'fop-list-2 file))
720     (3 (dump-fop 'fop-list-3 file))
721     (4 (dump-fop 'fop-list-4 file))
722     (5 (dump-fop 'fop-list-5 file))
723     (6 (dump-fop 'fop-list-6 file))
724     (7 (dump-fop 'fop-list-7 file))
725     (8 (dump-fop 'fop-list-8 file))
726     (t (cond ((< n 256)
727               (dump-fop 'fop-list file)
728               (dump-byte n file))
729              (t (dump-fop 'fop-list file)
730                 (dump-byte 255 file)
731                 (do ((nn (- n 255) (- nn 255)))
732                     ((< nn 256)
733                      (dump-fop 'fop-list* file)
734                      (dump-byte nn file))
735                   (declare (type index nn))
736                   (dump-fop 'fop-list* file)
737                   (dump-byte 255 file)))))))
738 \f
739 ;;;; array dumping
740
741 ;;; Dump the array thing.
742 (defun dump-array (x file)
743   (if (vectorp x)
744       (dump-vector x file)
745       (dump-multi-dim-array x file)))
746
747 ;;; Dump the vector object. If it's not simple, then actually dump a
748 ;;; simple version of it. But we enter the original in the EQ or EQUAL
749 ;;; tables.
750 (defun dump-vector (x file)
751   (let ((simple-version (if (array-header-p x)
752                             (coerce x `(simple-array
753                                         ,(array-element-type x)
754                                         (*)))
755                             x)))
756     (typecase simple-version
757       #+sb-xc-host
758       (simple-string
759        (unless (string-check-table x file)
760          (dump-simple-base-string simple-version file)
761          (string-save-object x file)))
762       #-sb-xc-host
763       (simple-base-string
764        (unless (string-check-table x file)
765          (dump-simple-base-string simple-version file)
766          (string-save-object x file)))
767       #-sb-xc-host
768       ((simple-array character (*))
769        #!+sb-unicode
770        (unless (string-check-table x file)
771          (dump-simple-character-string simple-version file)
772          (string-save-object x file))
773        #!-sb-unicode
774        (bug "how did we get here?"))
775       (simple-vector
776        (dump-simple-vector simple-version file)
777        (eq-save-object x file))
778       ((simple-array single-float (*))
779        (dump-single-float-vector simple-version file)
780        (eq-save-object x file))
781       ((simple-array double-float (*))
782        (dump-double-float-vector simple-version file)
783        (eq-save-object x file))
784       #!+long-float
785       ((simple-array long-float (*))
786        (dump-long-float-vector simple-version file)
787        (eq-save-object x file))
788       ((simple-array (complex single-float) (*))
789        (dump-complex-single-float-vector simple-version file)
790        (eq-save-object x file))
791       ((simple-array (complex double-float) (*))
792        (dump-complex-double-float-vector simple-version file)
793        (eq-save-object x file))
794       #!+long-float
795       ((simple-array (complex long-float) (*))
796        (dump-complex-long-float-vector simple-version file)
797        (eq-save-object x file))
798       (t
799        (dump-i-vector simple-version file)
800        (eq-save-object x file)))))
801
802 ;;; Dump a SIMPLE-VECTOR, handling any circularities.
803 (defun dump-simple-vector (v file)
804   (declare (type simple-vector v) (type fasl-output file))
805   (note-potential-circularity v file)
806   (do ((index 0 (1+ index))
807        (length (length v))
808        (circ (fasl-output-circularity-table file)))
809       ((= index length)
810        (dump-fop* length fop-small-vector fop-vector file))
811     (let* ((obj (aref v index))
812            (ref (gethash obj circ)))
813       (cond (ref
814              (push (make-circularity :type :svset
815                                      :object v
816                                      :index index
817                                      :value obj
818                                      :enclosing-object ref)
819                    *circularities-detected*)
820              (sub-dump-object nil file))
821             (t
822              (sub-dump-object obj file))))))
823
824 ;;; In the grand scheme of things I don't pretend to understand any
825 ;;; more how this works, or indeed whether.  But to write out specialized
826 ;;; vectors in the same format as fop-int-vector expects to read them
827 ;;; we need to be target-endian.  dump-integer-as-n-bytes always writes
828 ;;; little-endian (which is correct for all other integers) so for a bigendian
829 ;;; target we need to swap octets -- CSR, after DB
830
831 (defun octet-swap (word bits)
832   "BITS must be a multiple of 8"
833   (do ((input word (ash input -8))
834        (output 0 (logior (ash output 8) (logand input #xff)))
835        (bits bits (- bits 8)))
836       ((<= bits 0) output)))
837
838 (defun dump-i-vector (vec file &key data-only)
839   (declare (type (simple-array * (*)) vec))
840   (let ((len (length vec)))
841     (labels ((dump-unsigned-vector (size bytes)
842                (unless data-only
843                  (dump-fop 'fop-int-vector file)
844                  (dump-word len file)
845                  (dump-byte size file))
846                ;; The case which is easy to handle in a portable way is when
847                ;; the element size is a multiple of the output byte size, and
848                ;; happily that's the only case we need to be portable. (The
849                ;; cross-compiler has to output debug information (including
850                ;; (SIMPLE-ARRAY (UNSIGNED-BYTE 8) *).) The other cases are only
851                ;; needed in the target SBCL, so we let them be handled with
852                ;; unportable bit bashing.
853                (cond ((>= size 7) ; easy cases
854                       (multiple-value-bind (floor rem) (floor size 8)
855                         (aver (or (zerop rem) (= rem 7)))
856                         (when (= rem 7)
857                           (setq size (1+ size))
858                           (setq floor (1+ floor)))
859                         (dovector (i vec)
860                           (dump-integer-as-n-bytes
861                            (ecase sb!c:*backend-byte-order*
862                              (:little-endian i)
863                              (:big-endian (octet-swap i size)))
864                            floor file))))
865                      (t ; harder cases, not supported in cross-compiler
866                       (dump-raw-bytes vec bytes file))))
867              (dump-signed-vector (size bytes)
868                ;; Note: Dumping specialized signed vectors isn't
869                ;; supported in the cross-compiler. (All cases here end
870                ;; up trying to call DUMP-RAW-BYTES, which isn't
871                ;; provided in the cross-compilation host, only on the
872                ;; target machine.)
873                (unless data-only
874                  (dump-fop 'fop-signed-int-vector file)
875                  (dump-word len file)
876                  (dump-byte size file))
877                (dump-raw-bytes vec bytes file)))
878       (etypecase vec
879         #-sb-xc-host
880         ((simple-array nil (*))
881          (dump-unsigned-vector 0 0))
882         (simple-bit-vector
883          (dump-unsigned-vector 1 (ceiling len 8))) ; bits to bytes
884         ;; KLUDGE: This isn't the best way of expressing that the host
885         ;; may not have specializations for (unsigned-byte 2) and
886         ;; (unsigned-byte 4), which means that these types are
887         ;; type-equivalent to (simple-array (unsigned-byte 8) (*));
888         ;; the workaround is to remove them from the etypecase, since
889         ;; they can't be dumped from the cross-compiler anyway. --
890         ;; CSR, 2002-05-07
891         #-sb-xc-host
892         ((simple-array (unsigned-byte 2) (*))
893          (dump-unsigned-vector 2 (ceiling (ash len 1) 8))) ; bits to bytes
894         #-sb-xc-host
895         ((simple-array (unsigned-byte 4) (*))
896          (dump-unsigned-vector 4 (ceiling (ash len 2) 8))) ; bits to bytes
897         #-sb-xc-host
898         ((simple-array (unsigned-byte 7) (*))
899          (dump-unsigned-vector 7 len))
900         ((simple-array (unsigned-byte 8) (*))
901          (dump-unsigned-vector 8 len))
902         #-sb-xc-host
903         ((simple-array (unsigned-byte 15) (*))
904          (dump-unsigned-vector 15 (* 2 len)))
905         ((simple-array (unsigned-byte 16) (*))
906          (dump-unsigned-vector 16 (* 2 len)))
907         #-sb-xc-host
908         ((simple-array (unsigned-byte 31) (*))
909          (dump-unsigned-vector 31 (* 4 len)))
910         ((simple-array (unsigned-byte 32) (*))
911          (dump-unsigned-vector 32 (* 4 len)))
912         #-sb-xc-host
913         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
914         ((simple-array (unsigned-byte 63) (*))
915          (dump-unsigned-vector 63 (* 8 len)))
916         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
917         ((simple-array (unsigned-byte 64) (*))
918          (dump-unsigned-vector 64 (* 8 len)))
919         ((simple-array (signed-byte 8) (*))
920          (dump-signed-vector 8 len))
921         ((simple-array (signed-byte 16) (*))
922          (dump-signed-vector 16 (* 2 len)))
923         #!+#.(cl:if (cl:= 32 sb!vm:n-word-bits) '(and) '(or))
924         ((simple-array (unsigned-byte 29) (*))
925          (dump-signed-vector 29 (* 4 len)))
926         #!+#.(cl:if (cl:= 32 sb!vm:n-word-bits) '(and) '(or))
927         ((simple-array (signed-byte 30) (*))
928          (dump-signed-vector 30 (* 4 len)))
929         ((simple-array (signed-byte 32) (*))
930          (dump-signed-vector 32 (* 4 len)))
931         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
932         ((simple-array (unsigned-byte 60) (*))
933          (dump-signed-vector 60 (* 8 len)))
934         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
935         ((simple-array (signed-byte 61) (*))
936          (dump-signed-vector 61 (* 8 len)))
937         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
938         ((simple-array (signed-byte 64) (*))
939          (dump-signed-vector 64 (* 8 len)))))))
940 \f
941 ;;; Dump characters and string-ish things.
942
943 (defun dump-character (char file)
944   (let ((code (sb!xc:char-code char)))
945     (cond
946       ((< code 256)
947        (dump-fop 'fop-short-character file)
948        (dump-byte code file))
949       (t
950        (dump-fop 'fop-character file)
951        (dump-word code file)))))
952
953 (defun dump-base-chars-of-string (s fasl-output)
954   (declare #+sb-xc-host (type simple-string s)
955            #-sb-xc-host (type simple-base-string s)
956            (type fasl-output fasl-output))
957   (dovector (c s)
958     (dump-byte (sb!xc:char-code c) fasl-output))
959   (values))
960
961
962 ;;; Dump a SIMPLE-BASE-STRING.
963 (defun dump-simple-base-string (s file)
964   #+sb-xc-host (declare (type simple-string s))
965   #-sb-xc-host (declare (type simple-base-string s))
966   (dump-fop* (length s) fop-small-base-string fop-base-string file)
967   (dump-base-chars-of-string s file)
968   (values))
969
970 ;;; If we get here, it is assumed that the symbol isn't in the table,
971 ;;; but we are responsible for putting it there when appropriate. To
972 ;;; avoid too much special-casing, we always push the symbol in the
973 ;;; table, but don't record that we have done so if *COLD-LOAD-DUMP*
974 ;;; is true.
975 (defun dump-symbol (s file)
976   (declare (type fasl-output file))
977   (let* ((pname (symbol-name s))
978          (pname-length (length pname))
979          (pkg (symbol-package s)))
980     ;; see comment in genesis: we need this here for repeatable fasls
981     #+sb-xc-host
982     (multiple-value-bind (cl-symbol cl-status)
983         (find-symbol (symbol-name s) sb!int:*cl-package*)
984       (when (and (eq s cl-symbol)
985                  (eq cl-status :external))
986         ;; special case, to work around possible xc host "design
987         ;; choice" weirdness in COMMON-LISP package
988         (setq pkg sb!int:*cl-package*)))
989
990     (cond ((null pkg)
991            (dump-fop* pname-length
992                       fop-uninterned-small-symbol-save
993                       fop-uninterned-symbol-save
994                       file))
995           ;; CMU CL had FOP-SYMBOL-SAVE/FOP-SMALL-SYMBOL-SAVE fops which
996           ;; used the current value of *PACKAGE*. Unfortunately that's
997           ;; broken w.r.t. ANSI Common Lisp semantics, so those are gone
998           ;; from SBCL.
999           ;;((eq pkg *package*)
1000           ;; (dump-fop* pname-length
1001           ;;        fop-small-symbol-save
1002           ;;        fop-symbol-save file))
1003           ((eq pkg sb!int:*cl-package*)
1004            (dump-fop* pname-length
1005                       fop-lisp-small-symbol-save
1006                       fop-lisp-symbol-save
1007                       file))
1008           ((eq pkg sb!int:*keyword-package*)
1009            (dump-fop* pname-length
1010                       fop-keyword-small-symbol-save
1011                       fop-keyword-symbol-save
1012                       file))
1013           ((< pname-length 256)
1014            (dump-fop* (dump-package pkg file)
1015                       fop-small-symbol-in-byte-package-save
1016                       fop-small-symbol-in-package-save
1017                       file)
1018            (dump-byte pname-length file))
1019           (t
1020            (dump-fop* (dump-package pkg file)
1021                       fop-symbol-in-byte-package-save
1022                       fop-symbol-in-package-save
1023                       file)
1024            (dump-word pname-length file)))
1025
1026     #+sb-xc-host (dump-base-chars-of-string pname file)
1027     #-sb-xc-host (#!+sb-unicode dump-characters-of-string
1028                   #!-sb-unicode dump-base-chars-of-string
1029                   pname file)
1030
1031     (unless *cold-load-dump*
1032       (setf (gethash s (fasl-output-eq-table file))
1033             (fasl-output-table-free file)))
1034
1035     (incf (fasl-output-table-free file)))
1036
1037   (values))
1038 \f
1039 ;;;; component (function) dumping
1040
1041 (defun dump-segment (segment code-length fasl-output)
1042   (declare (type sb!assem:segment segment)
1043            (type fasl-output fasl-output))
1044   (let* ((stream (fasl-output-stream fasl-output))
1045          (n-written (write-segment-contents segment stream)))
1046     ;; In CMU CL there was no enforced connection between the CODE-LENGTH
1047     ;; argument and the number of bytes actually written. I added this
1048     ;; assertion while trying to debug portable genesis. -- WHN 19990902
1049     (unless (= code-length n-written)
1050       (bug "code-length=~W, n-written=~W" code-length n-written)))
1051   (values))
1052
1053 ;;; Dump all the fixups. Currently there are three flavors of fixup:
1054 ;;;  - assembly routines: named by a symbol
1055 ;;;  - foreign (C) symbols: named by a string
1056 ;;;  - code object references: don't need a name.
1057 (defun dump-fixups (fixups fasl-output)
1058   (declare (list fixups) (type fasl-output fasl-output))
1059   (dolist (note fixups)
1060     (let* ((kind (fixup-note-kind note))
1061            (fixup (fixup-note-fixup note))
1062            (position (fixup-note-position note))
1063            (name (fixup-name fixup))
1064            (flavor (fixup-flavor fixup)))
1065       (dump-fop 'fop-normal-load fasl-output)
1066       (let ((*cold-load-dump* t))
1067         (dump-object kind fasl-output))
1068       (dump-fop 'fop-maybe-cold-load fasl-output)
1069       ;; Depending on the flavor, we may have various kinds of
1070       ;; noise before the position.
1071       (ecase flavor
1072         (:assembly-routine
1073          (aver (symbolp name))
1074          (dump-fop 'fop-normal-load fasl-output)
1075          (let ((*cold-load-dump* t))
1076            (dump-object name fasl-output))
1077          (dump-fop 'fop-maybe-cold-load fasl-output)
1078          (dump-fop 'fop-assembler-fixup fasl-output))
1079         ((:foreign :foreign-dataref)
1080          (aver (stringp name))
1081          (ecase flavor
1082            (:foreign
1083             (dump-fop 'fop-foreign-fixup fasl-output))
1084            #!+linkage-table
1085            (:foreign-dataref
1086             (dump-fop 'fop-foreign-dataref-fixup fasl-output)))
1087          (let ((len (length name)))
1088            (aver (< len 256)) ; (limit imposed by fop definition)
1089            (dump-byte len fasl-output)
1090            (dotimes (i len)
1091              (dump-byte (char-code (schar name i)) fasl-output))))
1092         (:code-object
1093          (aver (null name))
1094          (dump-fop 'fop-code-object-fixup fasl-output)))
1095       ;; No matter what the flavor, we'll always dump the position
1096       (dump-word position fasl-output)))
1097   (values))
1098
1099 ;;; Dump out the constant pool and code-vector for component, push the
1100 ;;; result in the table, and return the offset.
1101 ;;;
1102 ;;; The only tricky thing is handling constant-pool references to
1103 ;;; functions. If we have already dumped the function, then we just
1104 ;;; push the code pointer. Otherwise, we must create back-patching
1105 ;;; information so that the constant will be set when the function is
1106 ;;; eventually dumped. This is a bit awkward, since we don't have the
1107 ;;; handle for the code object being dumped while we are dumping its
1108 ;;; constants.
1109 ;;;
1110 ;;; We dump trap objects in any unused slots or forward referenced slots.
1111 (defun dump-code-object (component
1112                          code-segment
1113                          code-length
1114                          trace-table-as-list
1115                          fixups
1116                          fasl-output)
1117
1118   (declare (type component component)
1119            (list trace-table-as-list)
1120            (type index code-length)
1121            (type fasl-output fasl-output))
1122
1123   (let* ((2comp (component-info component))
1124          (constants (sb!c::ir2-component-constants 2comp))
1125          (header-length (length constants))
1126          (packed-trace-table (pack-trace-table trace-table-as-list))
1127          (total-length (+ code-length
1128                           (* (length packed-trace-table)
1129                              sb!c::tt-bytes-per-entry))))
1130
1131     (collect ((patches))
1132
1133       ;; Dump the offset of the trace table.
1134       (dump-object code-length fasl-output)
1135       ;; FIXME: As long as we don't have GENGC, the trace table is
1136       ;; hardwired to be empty. And SBCL doesn't have GENGC (and as
1137       ;; far as I know no modern CMU CL does either -- WHN
1138       ;; 2001-10-05). So might we be able to get rid of trace tables?
1139       ;;
1140       ;; Note that gencgc also does something with the trace table.
1141
1142       ;; Dump the constants, noting any :ENTRY constants that have to
1143       ;; be patched.
1144       (loop for i from sb!vm:code-constants-offset below header-length do
1145         (let ((entry (aref constants i)))
1146           (etypecase entry
1147             (constant
1148              (dump-object (sb!c::constant-value entry) fasl-output))
1149             (cons
1150              (ecase (car entry)
1151                (:entry
1152                 (let* ((info (sb!c::leaf-info (cdr entry)))
1153                        (handle (gethash info
1154                                         (fasl-output-entry-table
1155                                          fasl-output))))
1156                   (declare (type sb!c::entry-info info))
1157                   (cond
1158                    (handle
1159                     (dump-push handle fasl-output))
1160                    (t
1161                     (patches (cons info i))
1162                     (dump-fop 'fop-misc-trap fasl-output)))))
1163                (:load-time-value
1164                 (dump-push (cdr entry) fasl-output))
1165                (:fdefinition
1166                 (dump-object (cdr entry) fasl-output)
1167                 (dump-fop 'fop-fdefinition fasl-output))))
1168             (null
1169              (dump-fop 'fop-misc-trap fasl-output)))))
1170
1171       ;; Dump the debug info.
1172       (let ((info (sb!c::debug-info-for-component component))
1173             (*dump-only-valid-structures* nil))
1174         (dump-object info fasl-output)
1175         (let ((info-handle (dump-pop fasl-output)))
1176           (dump-push info-handle fasl-output)
1177           (push info-handle (fasl-output-debug-info fasl-output))))
1178
1179       (let ((num-consts (- header-length sb!vm:code-trace-table-offset-slot)))
1180         (cond ((and (< num-consts #x100) (< total-length #x10000))
1181                (dump-fop 'fop-small-code fasl-output)
1182                (dump-byte num-consts fasl-output)
1183                (dump-integer-as-n-bytes total-length (/ sb!vm:n-word-bytes 2) fasl-output))
1184               (t
1185                (dump-fop 'fop-code fasl-output)
1186                (dump-word num-consts fasl-output)
1187                (dump-word total-length fasl-output))))
1188
1189       ;; These two dumps are only ones which contribute to our
1190       ;; TOTAL-LENGTH value.
1191       (dump-segment code-segment code-length fasl-output)
1192       (dump-i-vector packed-trace-table fasl-output :data-only t)
1193
1194       ;; DUMP-FIXUPS does its own internal DUMP-FOPs: the bytes it
1195       ;; dumps aren't included in the TOTAL-LENGTH passed to our
1196       ;; FOP-CODE/FOP-SMALL-CODE fop.
1197       (dump-fixups fixups fasl-output)
1198
1199       (dump-fop 'fop-sanctify-for-execution fasl-output)
1200
1201       (let ((handle (dump-pop fasl-output)))
1202         (dolist (patch (patches))
1203           (push (cons handle (cdr patch))
1204                 (gethash (car patch)
1205                          (fasl-output-patch-table fasl-output))))
1206         handle))))
1207
1208 (defun dump-assembler-routines (code-segment length fixups routines file)
1209   (dump-fop 'fop-assembler-code file)
1210   (dump-word length file)
1211   (write-segment-contents code-segment (fasl-output-stream file))
1212   (dolist (routine routines)
1213     (dump-fop 'fop-normal-load file)
1214     (let ((*cold-load-dump* t))
1215       (dump-object (car routine) file))
1216     (dump-fop 'fop-maybe-cold-load file)
1217     (dump-fop 'fop-assembler-routine file)
1218     (dump-word (label-position (cdr routine)) file))
1219   (dump-fixups fixups file)
1220   (dump-fop 'fop-sanctify-for-execution file)
1221   (dump-pop file))
1222
1223 ;;; Dump a function entry data structure corresponding to ENTRY to
1224 ;;; FILE. CODE-HANDLE is the table offset of the code object for the
1225 ;;; component.
1226 (defun dump-one-entry (entry code-handle file)
1227   (declare (type sb!c::entry-info entry) (type index code-handle)
1228            (type fasl-output file))
1229   (let ((name (sb!c::entry-info-name entry)))
1230     (dump-push code-handle file)
1231     (dump-object name file)
1232     (dump-object (sb!c::entry-info-arguments entry) file)
1233     (dump-object (sb!c::entry-info-type entry) file)
1234     (dump-object (sb!c::entry-info-xref entry) file)
1235     (dump-fop 'fop-fun-entry file)
1236     (dump-word (label-position (sb!c::entry-info-offset entry)) file)
1237     (dump-pop file)))
1238
1239 ;;; Alter the code object referenced by CODE-HANDLE at the specified
1240 ;;; OFFSET, storing the object referenced by ENTRY-HANDLE.
1241 (defun dump-alter-code-object (code-handle offset entry-handle file)
1242   (declare (type index code-handle entry-handle offset))
1243   (declare (type fasl-output file))
1244   (dump-push code-handle file)
1245   (dump-push entry-handle file)
1246   (dump-fop* offset fop-byte-alter-code fop-alter-code file)
1247   (values))
1248
1249 ;;; Dump the code, constants, etc. for component. We pass in the
1250 ;;; assembler fixups, code vector and node info.
1251 (defun fasl-dump-component (component
1252                             code-segment
1253                             code-length
1254                             trace-table
1255                             fixups
1256                             file)
1257   (declare (type component component) (list trace-table))
1258   (declare (type fasl-output file))
1259
1260   (dump-fop 'fop-verify-table-size file)
1261   (dump-word (fasl-output-table-free file) file)
1262
1263   #!+sb-dyncount
1264   (let ((info (sb!c::ir2-component-dyncount-info (component-info component))))
1265     (when info
1266       (fasl-validate-structure info file)))
1267
1268   (let ((code-handle (dump-code-object component
1269                                        code-segment
1270                                        code-length
1271                                        trace-table
1272                                        fixups
1273                                        file))
1274         (2comp (component-info component)))
1275
1276     (dolist (entry (sb!c::ir2-component-entries 2comp))
1277       (let ((entry-handle (dump-one-entry entry code-handle file)))
1278         (setf (gethash entry (fasl-output-entry-table file)) entry-handle)
1279         (let ((old (gethash entry (fasl-output-patch-table file))))
1280           (when old
1281             (dolist (patch old)
1282               (dump-alter-code-object (car patch)
1283                                       (cdr patch)
1284                                       entry-handle
1285                                       file))
1286             (remhash entry (fasl-output-patch-table file)))))))
1287   (values))
1288
1289 (defun dump-push-previously-dumped-fun (fun fasl-output)
1290   (declare (type sb!c::clambda fun))
1291   (let ((handle (gethash (sb!c::leaf-info fun)
1292                          (fasl-output-entry-table fasl-output))))
1293     (aver handle)
1294     (dump-push handle fasl-output))
1295   (values))
1296
1297 ;;; Dump a FOP-FUNCALL to call an already-dumped top level lambda at
1298 ;;; load time.
1299 (defun fasl-dump-toplevel-lambda-call (fun fasl-output)
1300   (declare (type sb!c::clambda fun))
1301   (dump-push-previously-dumped-fun fun fasl-output)
1302   (dump-fop 'fop-funcall-for-effect fasl-output)
1303   (dump-byte 0 fasl-output)
1304   (values))
1305
1306 ;;; Dump a FOP-FSET to arrange static linkage (at cold init) between
1307 ;;; FUN-NAME and the already-dumped function whose dump handle is
1308 ;;; FUN-DUMP-HANDLE.
1309 #+sb-xc-host
1310 (defun fasl-dump-cold-fset (fun-name fun-dump-handle fasl-output)
1311   (declare (type fixnum fun-dump-handle))
1312   (aver (legal-fun-name-p fun-name))
1313   (dump-non-immediate-object fun-name fasl-output)
1314   (dump-push fun-dump-handle fasl-output)
1315   (dump-fop 'fop-fset fasl-output)
1316   (values))
1317
1318 ;;; Compute the correct list of DEBUG-SOURCE structures and backpatch
1319 ;;; all of the dumped DEBUG-INFO structures. We clear the
1320 ;;; FASL-OUTPUT-DEBUG-INFO, so that subsequent components with
1321 ;;; different source info may be dumped.
1322 (defun fasl-dump-source-info (info fasl-output)
1323   (declare (type sb!c::source-info info))
1324   (let ((res (sb!c::debug-source-for-info info))
1325         (*dump-only-valid-structures* nil))
1326     #+sb-xc-host (setf (sb!c::debug-source-created res) 0
1327                        (sb!c::debug-source-compiled res) 0)
1328     (dump-object res fasl-output)
1329     (let ((res-handle (dump-pop fasl-output)))
1330       (dolist (info-handle (fasl-output-debug-info fasl-output))
1331         (dump-push res-handle fasl-output)
1332         (dump-fop 'fop-structset fasl-output)
1333         (dump-word info-handle fasl-output)
1334         (dump-word sb!c::+debug-info-source-index+ fasl-output))
1335       #+sb-xc-host
1336       (progn
1337         (dump-push res-handle fasl-output)
1338         (dump-fop 'fop-note-debug-source fasl-output))))
1339   (setf (fasl-output-debug-info fasl-output) nil)
1340   (values))
1341 \f
1342 ;;;; dumping structures
1343
1344 (defun dump-structure (struct file)
1345   (when *dump-only-valid-structures*
1346     (unless (gethash struct (fasl-output-valid-structures file))
1347       (error "attempt to dump invalid structure:~%  ~S~%How did this happen?"
1348              struct)))
1349   (note-potential-circularity struct file)
1350   (aver (%instance-ref struct 0))
1351   (do* ((length (%instance-length struct))
1352         (ntagged (- length (layout-n-untagged-slots (%instance-ref struct 0))))
1353         (circ (fasl-output-circularity-table file))
1354         ;; last slot first on the stack, so that the layout is on top:
1355         (index (1- length) (1- index)))
1356       ((minusp index)
1357        (dump-fop* length fop-small-struct fop-struct file))
1358     (let* ((obj (if (>= index ntagged)
1359                     (%raw-instance-ref/word struct (- length index 1))
1360                     (%instance-ref struct index)))
1361            (ref (gethash obj circ)))
1362       (cond (ref
1363              (aver (not (zerop index)))
1364              (push (make-circularity :type :struct-set
1365                                      :object struct
1366                                      :index index
1367                                      :value obj
1368                                      :enclosing-object ref)
1369                    *circularities-detected*)
1370              (sub-dump-object nil file))
1371             (t
1372              (sub-dump-object obj file))))))
1373
1374 (defun dump-layout (obj file)
1375   (when (layout-invalid obj)
1376     (compiler-error "attempt to dump reference to obsolete class: ~S"
1377                     (layout-classoid obj)))
1378   (let ((name (classoid-name (layout-classoid obj))))
1379     (unless name
1380       (compiler-error "dumping anonymous layout: ~S" obj))
1381     (dump-fop 'fop-normal-load file)
1382     (let ((*cold-load-dump* t))
1383       (dump-object name file))
1384     (dump-fop 'fop-maybe-cold-load file))
1385   (sub-dump-object (layout-inherits obj) file)
1386   (sub-dump-object (layout-depthoid obj) file)
1387   (sub-dump-object (layout-length obj) file)
1388   (sub-dump-object (layout-n-untagged-slots obj) file)
1389   (dump-fop 'fop-layout file))