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