1.0.28.55: transform FILL to a UB*-BASH-FILL when possible
[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-single-float (re im file)
570   (declare (single-float re im))
571   (dump-fop 'fop-complex-single-float file)
572   (dump-integer-as-n-bytes (single-float-bits re) 4 file)
573   (dump-integer-as-n-bytes (single-float-bits im) 4 file))
574
575 (defun dump-complex-double-float (re im file)
576   (declare (double-float re im))
577   (dump-fop 'fop-complex-double-float file)
578   (dump-integer-as-n-bytes (double-float-low-bits re) 4 file)
579   (dump-integer-as-n-bytes (double-float-high-bits re) 4 file)
580   (dump-integer-as-n-bytes (double-float-low-bits im) 4 file)
581   (dump-integer-as-n-bytes (double-float-high-bits im) 4 file))
582
583 (defun dump-complex-rational (re im file)
584   (sub-dump-object re file)
585   (sub-dump-object im file)
586   (dump-fop 'fop-complex file))
587
588 #+sb-xc-host
589 (defun dump-complex (x file)
590   (let ((re (realpart x))
591         (im (imagpart x)))
592     (cond ((and (typep re 'single-float)
593                 (typep im 'single-float))
594            (dump-complex-single-float re im file))
595           ((and (typep re 'double-float)
596                 (typep im 'double-float))
597            (dump-complex-double-float re im file))
598           ((and (typep re 'rational)
599                 (typep im 'rational))
600            (dump-complex-rational re im file))
601           (t
602            (bug "Complex number too complex: ~S" x)))))
603
604 #-sb-xc-host
605 (defun dump-complex (x file)
606   (typecase x
607     ((complex single-float)
608      (dump-complex-single-float (realpart x) (imagpart x) file))
609     ((complex double-float)
610      (dump-complex-double-float (realpart x) (imagpart x) file))
611     #!+long-float
612     ((complex long-float)
613      (dump-fop 'fop-complex-long-float file)
614      (dump-long-float (realpart x) file)
615      (dump-long-float (imagpart x) file))
616     (t
617      (dump-complex-rational (realpart x) (imagpart x) file))))
618 \f
619 ;;;; symbol dumping
620
621 ;;; Return the table index of PKG, adding the package to the table if
622 ;;; necessary. During cold load, we read the string as a normal string
623 ;;; so that we can do the package lookup at cold load time.
624 ;;;
625 ;;; FIXME: Despite the parallelism in names, the functionality of
626 ;;; this function is not parallel to other functions DUMP-FOO, e.g.
627 ;;; DUMP-SYMBOL and DUMP-LIST. The mapping between names and behavior
628 ;;; should be made more consistent.
629 (declaim (ftype (function (package fasl-output) index) dump-package))
630 (defun dump-package (pkg file)
631   (declare (inline assoc))
632   (cond ((cdr (assoc pkg (fasl-output-packages file) :test #'eq)))
633         (t
634          (unless *cold-load-dump*
635            (dump-fop 'fop-normal-load file))
636          #+sb-xc-host
637          (dump-simple-base-string
638           (coerce (package-name pkg) 'simple-base-string)
639           file)
640          #-sb-xc-host
641          (#!+sb-unicode dump-simple-character-string
642           #!-sb-unicode dump-simple-base-string
643           (coerce (package-name pkg) '(simple-array character (*)))
644           file)
645          (dump-fop 'fop-package file)
646          (unless *cold-load-dump*
647            (dump-fop 'fop-maybe-cold-load file))
648          (let ((entry (dump-pop file)))
649            (push (cons pkg entry) (fasl-output-packages file))
650            entry))))
651 \f
652 ;;; dumper for lists
653
654 ;;; Dump a list, setting up patching information when there are
655 ;;; circularities. We scan down the list, checking for CDR and CAR
656 ;;; circularities.
657 ;;;
658 ;;; If there is a CDR circularity, we terminate the list with NIL and
659 ;;; make a CIRCULARITY notation for the CDR of the previous cons.
660 ;;;
661 ;;; If there is no CDR circularity, then we mark the current cons and
662 ;;; check for a CAR circularity. When there is a CAR circularity, we
663 ;;; make the CAR NIL initially, arranging for the current cons to be
664 ;;; patched later.
665 ;;;
666 ;;; Otherwise, we recursively call the dumper to dump the current
667 ;;; element.
668 ;;;
669 ;;; Marking of the conses is inhibited when *COLD-LOAD-DUMP* is true.
670 ;;; This inhibits all circularity detection.
671 (defun dump-list (list file)
672   (aver (and list
673              (not (gethash list (fasl-output-circularity-table file)))))
674   (do* ((l list (cdr l))
675         (n 0 (1+ n))
676         (circ (fasl-output-circularity-table file)))
677        ((atom l)
678         (cond ((null l)
679                (terminate-undotted-list n file))
680               (t
681                (sub-dump-object l file)
682                (terminate-dotted-list n file))))
683     (declare (type index n))
684     (let ((ref (gethash l circ)))
685       (when ref
686         (push (make-circularity :type :rplacd
687                                 :object list
688                                 :index (1- n)
689                                 :value l
690                                 :enclosing-object ref)
691               *circularities-detected*)
692         (terminate-undotted-list n file)
693         (return)))
694
695     (unless *cold-load-dump*
696       (setf (gethash l circ) list))
697
698     (let* ((obj (car l))
699            (ref (gethash obj circ)))
700       (cond (ref
701              (push (make-circularity :type :rplaca
702                                      :object list
703                                      :index n
704                                      :value obj
705                                      :enclosing-object ref)
706                    *circularities-detected*)
707              (sub-dump-object nil file))
708             (t
709              (sub-dump-object obj file))))))
710
711 (defun terminate-dotted-list (n file)
712   (declare (type index n) (type fasl-output file))
713   (case n
714     (1 (dump-fop 'fop-list*-1 file))
715     (2 (dump-fop 'fop-list*-2 file))
716     (3 (dump-fop 'fop-list*-3 file))
717     (4 (dump-fop 'fop-list*-4 file))
718     (5 (dump-fop 'fop-list*-5 file))
719     (6 (dump-fop 'fop-list*-6 file))
720     (7 (dump-fop 'fop-list*-7 file))
721     (8 (dump-fop 'fop-list*-8 file))
722     (t (do ((nn n (- nn 255)))
723            ((< nn 256)
724             (dump-fop 'fop-list* file)
725             (dump-byte nn file))
726          (declare (type index nn))
727          (dump-fop 'fop-list* file)
728          (dump-byte 255 file)))))
729
730 ;;; If N > 255, must build list with one LIST operator, then LIST*
731 ;;; operators.
732
733 (defun terminate-undotted-list (n file)
734   (declare (type index n) (type fasl-output file))
735   (case n
736     (1 (dump-fop 'fop-list-1 file))
737     (2 (dump-fop 'fop-list-2 file))
738     (3 (dump-fop 'fop-list-3 file))
739     (4 (dump-fop 'fop-list-4 file))
740     (5 (dump-fop 'fop-list-5 file))
741     (6 (dump-fop 'fop-list-6 file))
742     (7 (dump-fop 'fop-list-7 file))
743     (8 (dump-fop 'fop-list-8 file))
744     (t (cond ((< n 256)
745               (dump-fop 'fop-list file)
746               (dump-byte n file))
747              (t (dump-fop 'fop-list file)
748                 (dump-byte 255 file)
749                 (do ((nn (- n 255) (- nn 255)))
750                     ((< nn 256)
751                      (dump-fop 'fop-list* file)
752                      (dump-byte nn file))
753                   (declare (type index nn))
754                   (dump-fop 'fop-list* file)
755                   (dump-byte 255 file)))))))
756 \f
757 ;;;; array dumping
758
759 ;;; Dump the array thing.
760 (defun dump-array (x file)
761   (if (vectorp x)
762       (dump-vector x file)
763       (dump-multi-dim-array x file)))
764
765 ;;; Dump the vector object. If it's not simple, then actually dump a
766 ;;; simple version of it. But we enter the original in the EQ or EQUAL
767 ;;; tables.
768 (defun dump-vector (x file)
769   (let ((simple-version (if (array-header-p x)
770                             (coerce x `(simple-array
771                                         ,(array-element-type x)
772                                         (*)))
773                             x)))
774     (typecase simple-version
775       #+sb-xc-host
776       (simple-string
777        (unless (string-check-table x file)
778          (dump-simple-base-string simple-version file)
779          (string-save-object x file)))
780       #-sb-xc-host
781       (simple-base-string
782        (unless (string-check-table x file)
783          (dump-simple-base-string simple-version file)
784          (string-save-object x file)))
785       #-sb-xc-host
786       ((simple-array character (*))
787        #!+sb-unicode
788        (unless (string-check-table x file)
789          (dump-simple-character-string simple-version file)
790          (string-save-object x file))
791        #!-sb-unicode
792        (bug "how did we get here?"))
793       (simple-vector
794        (dump-simple-vector simple-version file)
795        (eq-save-object x file))
796       ((simple-array single-float (*))
797        (dump-single-float-vector simple-version file)
798        (eq-save-object x file))
799       ((simple-array double-float (*))
800        (dump-double-float-vector simple-version file)
801        (eq-save-object x file))
802       #!+long-float
803       ((simple-array long-float (*))
804        (dump-long-float-vector simple-version file)
805        (eq-save-object x file))
806       ((simple-array (complex single-float) (*))
807        (dump-complex-single-float-vector simple-version file)
808        (eq-save-object x file))
809       ((simple-array (complex double-float) (*))
810        (dump-complex-double-float-vector simple-version file)
811        (eq-save-object x file))
812       #!+long-float
813       ((simple-array (complex long-float) (*))
814        (dump-complex-long-float-vector simple-version file)
815        (eq-save-object x file))
816       (t
817        (dump-i-vector simple-version file)
818        (eq-save-object x file)))))
819
820 ;;; Dump a SIMPLE-VECTOR, handling any circularities.
821 (defun dump-simple-vector (v file)
822   (declare (type simple-vector v) (type fasl-output file))
823   (note-potential-circularity v file)
824   (do ((index 0 (1+ index))
825        (length (length v))
826        (circ (fasl-output-circularity-table file)))
827       ((= index length)
828        (dump-fop* length fop-small-vector fop-vector file))
829     (let* ((obj (aref v index))
830            (ref (gethash obj circ)))
831       (cond (ref
832              (push (make-circularity :type :svset
833                                      :object v
834                                      :index index
835                                      :value obj
836                                      :enclosing-object ref)
837                    *circularities-detected*)
838              (sub-dump-object nil file))
839             (t
840              (sub-dump-object obj file))))))
841
842 ;;; In the grand scheme of things I don't pretend to understand any
843 ;;; more how this works, or indeed whether.  But to write out specialized
844 ;;; vectors in the same format as fop-int-vector expects to read them
845 ;;; we need to be target-endian.  dump-integer-as-n-bytes always writes
846 ;;; little-endian (which is correct for all other integers) so for a bigendian
847 ;;; target we need to swap octets -- CSR, after DB
848
849 (defun octet-swap (word bits)
850   "BITS must be a multiple of 8"
851   (do ((input word (ash input -8))
852        (output 0 (logior (ash output 8) (logand input #xff)))
853        (bits bits (- bits 8)))
854       ((<= bits 0) output)))
855
856 (defun dump-i-vector (vec file &key data-only)
857   (declare (type (simple-array * (*)) vec))
858   (let ((len (length vec)))
859     (labels ((dump-unsigned-vector (size bytes)
860                (unless data-only
861                  (dump-fop 'fop-int-vector file)
862                  (dump-word len file)
863                  (dump-byte size file))
864                ;; The case which is easy to handle in a portable way is when
865                ;; the element size is a multiple of the output byte size, and
866                ;; happily that's the only case we need to be portable. (The
867                ;; cross-compiler has to output debug information (including
868                ;; (SIMPLE-ARRAY (UNSIGNED-BYTE 8) *).) The other cases are only
869                ;; needed in the target SBCL, so we let them be handled with
870                ;; unportable bit bashing.
871                (cond ((>= size 7) ; easy cases
872                       (multiple-value-bind (floor rem) (floor size 8)
873                         (aver (or (zerop rem) (= rem 7)))
874                         (when (= rem 7)
875                           (setq size (1+ size))
876                           (setq floor (1+ floor)))
877                         (dovector (i vec)
878                           (dump-integer-as-n-bytes
879                            (ecase sb!c:*backend-byte-order*
880                              (:little-endian i)
881                              (:big-endian (octet-swap i size)))
882                            floor file))))
883                      (t ; harder cases, not supported in cross-compiler
884                       (dump-raw-bytes vec bytes file))))
885              (dump-signed-vector (size bytes)
886                ;; Note: Dumping specialized signed vectors isn't
887                ;; supported in the cross-compiler. (All cases here end
888                ;; up trying to call DUMP-RAW-BYTES, which isn't
889                ;; provided in the cross-compilation host, only on the
890                ;; target machine.)
891                (unless data-only
892                  (dump-fop 'fop-signed-int-vector file)
893                  (dump-word len file)
894                  (dump-byte size file))
895                (dump-raw-bytes vec bytes file)))
896       (etypecase vec
897         #-sb-xc-host
898         ((simple-array nil (*))
899          (dump-unsigned-vector 0 0))
900         (simple-bit-vector
901          (dump-unsigned-vector 1 (ceiling len 8))) ; bits to bytes
902         ;; KLUDGE: This isn't the best way of expressing that the host
903         ;; may not have specializations for (unsigned-byte 2) and
904         ;; (unsigned-byte 4), which means that these types are
905         ;; type-equivalent to (simple-array (unsigned-byte 8) (*));
906         ;; the workaround is to remove them from the etypecase, since
907         ;; they can't be dumped from the cross-compiler anyway. --
908         ;; CSR, 2002-05-07
909         #-sb-xc-host
910         ((simple-array (unsigned-byte 2) (*))
911          (dump-unsigned-vector 2 (ceiling (ash len 1) 8))) ; bits to bytes
912         #-sb-xc-host
913         ((simple-array (unsigned-byte 4) (*))
914          (dump-unsigned-vector 4 (ceiling (ash len 2) 8))) ; bits to bytes
915         #-sb-xc-host
916         ((simple-array (unsigned-byte 7) (*))
917          (dump-unsigned-vector 7 len))
918         ((simple-array (unsigned-byte 8) (*))
919          (dump-unsigned-vector 8 len))
920         #-sb-xc-host
921         ((simple-array (unsigned-byte 15) (*))
922          (dump-unsigned-vector 15 (* 2 len)))
923         ((simple-array (unsigned-byte 16) (*))
924          (dump-unsigned-vector 16 (* 2 len)))
925         #-sb-xc-host
926         ((simple-array (unsigned-byte 31) (*))
927          (dump-unsigned-vector 31 (* 4 len)))
928         ((simple-array (unsigned-byte 32) (*))
929          (dump-unsigned-vector 32 (* 4 len)))
930         #-sb-xc-host
931         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
932         ((simple-array (unsigned-byte 63) (*))
933          (dump-unsigned-vector 63 (* 8 len)))
934         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
935         ((simple-array (unsigned-byte 64) (*))
936          (dump-unsigned-vector 64 (* 8 len)))
937         ((simple-array (signed-byte 8) (*))
938          (dump-signed-vector 8 len))
939         ((simple-array (signed-byte 16) (*))
940          (dump-signed-vector 16 (* 2 len)))
941         #!+#.(cl:if (cl:= 32 sb!vm:n-word-bits) '(and) '(or))
942         ((simple-array (unsigned-byte 29) (*))
943          (dump-signed-vector 29 (* 4 len)))
944         #!+#.(cl:if (cl:= 32 sb!vm:n-word-bits) '(and) '(or))
945         ((simple-array (signed-byte 30) (*))
946          (dump-signed-vector 30 (* 4 len)))
947         ((simple-array (signed-byte 32) (*))
948          (dump-signed-vector 32 (* 4 len)))
949         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
950         ((simple-array (unsigned-byte 60) (*))
951          (dump-signed-vector 60 (* 8 len)))
952         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
953         ((simple-array (signed-byte 61) (*))
954          (dump-signed-vector 61 (* 8 len)))
955         #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
956         ((simple-array (signed-byte 64) (*))
957          (dump-signed-vector 64 (* 8 len)))))))
958 \f
959 ;;; Dump characters and string-ish things.
960
961 (defun dump-character (char file)
962   (let ((code (sb!xc:char-code char)))
963     (cond
964       ((< code 256)
965        (dump-fop 'fop-short-character file)
966        (dump-byte code file))
967       (t
968        (dump-fop 'fop-character file)
969        (dump-word code file)))))
970
971 (defun dump-base-chars-of-string (s fasl-output)
972   (declare #+sb-xc-host (type simple-string s)
973            #-sb-xc-host (type simple-base-string s)
974            (type fasl-output fasl-output))
975   (dovector (c s)
976     (dump-byte (sb!xc:char-code c) fasl-output))
977   (values))
978
979
980 ;;; Dump a SIMPLE-BASE-STRING.
981 (defun dump-simple-base-string (s file)
982   #+sb-xc-host (declare (type simple-string s))
983   #-sb-xc-host (declare (type simple-base-string s))
984   (dump-fop* (length s) fop-small-base-string fop-base-string file)
985   (dump-base-chars-of-string s file)
986   (values))
987
988 ;;; If we get here, it is assumed that the symbol isn't in the table,
989 ;;; but we are responsible for putting it there when appropriate. To
990 ;;; avoid too much special-casing, we always push the symbol in the
991 ;;; table, but don't record that we have done so if *COLD-LOAD-DUMP*
992 ;;; is true.
993 (defun dump-symbol (s file)
994   (declare (type fasl-output file))
995   (let* ((pname (symbol-name s))
996          (pname-length (length pname))
997          (pkg (symbol-package s)))
998     ;; see comment in genesis: we need this here for repeatable fasls
999     #+sb-xc-host
1000     (multiple-value-bind (cl-symbol cl-status)
1001         (find-symbol (symbol-name s) sb!int:*cl-package*)
1002       (when (and (eq s cl-symbol)
1003                  (eq cl-status :external))
1004         ;; special case, to work around possible xc host "design
1005         ;; choice" weirdness in COMMON-LISP package
1006         (setq pkg sb!int:*cl-package*)))
1007
1008     (cond ((null pkg)
1009            (dump-fop* pname-length
1010                       fop-uninterned-small-symbol-save
1011                       fop-uninterned-symbol-save
1012                       file))
1013           ;; CMU CL had FOP-SYMBOL-SAVE/FOP-SMALL-SYMBOL-SAVE fops which
1014           ;; used the current value of *PACKAGE*. Unfortunately that's
1015           ;; broken w.r.t. ANSI Common Lisp semantics, so those are gone
1016           ;; from SBCL.
1017           ;;((eq pkg *package*)
1018           ;; (dump-fop* pname-length
1019           ;;        fop-small-symbol-save
1020           ;;        fop-symbol-save file))
1021           ((eq pkg sb!int:*cl-package*)
1022            (dump-fop* pname-length
1023                       fop-lisp-small-symbol-save
1024                       fop-lisp-symbol-save
1025                       file))
1026           ((eq pkg sb!int:*keyword-package*)
1027            (dump-fop* pname-length
1028                       fop-keyword-small-symbol-save
1029                       fop-keyword-symbol-save
1030                       file))
1031           ((< pname-length 256)
1032            (dump-fop* (dump-package pkg file)
1033                       fop-small-symbol-in-byte-package-save
1034                       fop-small-symbol-in-package-save
1035                       file)
1036            (dump-byte pname-length file))
1037           (t
1038            (dump-fop* (dump-package pkg file)
1039                       fop-symbol-in-byte-package-save
1040                       fop-symbol-in-package-save
1041                       file)
1042            (dump-word pname-length file)))
1043
1044     #+sb-xc-host (dump-base-chars-of-string pname file)
1045     #-sb-xc-host (#!+sb-unicode dump-characters-of-string
1046                   #!-sb-unicode dump-base-chars-of-string
1047                   pname file)
1048
1049     (unless *cold-load-dump*
1050       (setf (gethash s (fasl-output-eq-table file))
1051             (fasl-output-table-free file)))
1052
1053     (incf (fasl-output-table-free file)))
1054
1055   (values))
1056 \f
1057 ;;;; component (function) dumping
1058
1059 (defun dump-segment (segment code-length fasl-output)
1060   (declare (type sb!assem:segment segment)
1061            (type fasl-output fasl-output))
1062   (let* ((stream (fasl-output-stream fasl-output))
1063          (n-written (write-segment-contents segment stream)))
1064     ;; In CMU CL there was no enforced connection between the CODE-LENGTH
1065     ;; argument and the number of bytes actually written. I added this
1066     ;; assertion while trying to debug portable genesis. -- WHN 19990902
1067     (unless (= code-length n-written)
1068       (bug "code-length=~W, n-written=~W" code-length n-written)))
1069   (values))
1070
1071 ;;; Dump all the fixups. Currently there are three flavors of fixup:
1072 ;;;  - assembly routines: named by a symbol
1073 ;;;  - foreign (C) symbols: named by a string
1074 ;;;  - code object references: don't need a name.
1075 (defun dump-fixups (fixups fasl-output)
1076   (declare (list fixups) (type fasl-output fasl-output))
1077   (dolist (note fixups)
1078     (let* ((kind (fixup-note-kind note))
1079            (fixup (fixup-note-fixup note))
1080            (position (fixup-note-position note))
1081            (name (fixup-name fixup))
1082            (flavor (fixup-flavor fixup)))
1083       (dump-fop 'fop-normal-load fasl-output)
1084       (let ((*cold-load-dump* t))
1085         (dump-object kind fasl-output))
1086       (dump-fop 'fop-maybe-cold-load fasl-output)
1087       ;; Depending on the flavor, we may have various kinds of
1088       ;; noise before the position.
1089       (ecase flavor
1090         (:assembly-routine
1091          (aver (symbolp name))
1092          (dump-fop 'fop-normal-load fasl-output)
1093          (let ((*cold-load-dump* t))
1094            (dump-object name fasl-output))
1095          (dump-fop 'fop-maybe-cold-load fasl-output)
1096          (dump-fop 'fop-assembler-fixup fasl-output))
1097         ((:foreign :foreign-dataref)
1098          (aver (stringp name))
1099          (ecase flavor
1100            (:foreign
1101             (dump-fop 'fop-foreign-fixup fasl-output))
1102            #!+linkage-table
1103            (:foreign-dataref
1104             (dump-fop 'fop-foreign-dataref-fixup fasl-output)))
1105          (let ((len (length name)))
1106            (aver (< len 256)) ; (limit imposed by fop definition)
1107            (dump-byte len fasl-output)
1108            (dotimes (i len)
1109              (dump-byte (char-code (schar name i)) fasl-output))))
1110         (:code-object
1111          (aver (null name))
1112          (dump-fop 'fop-code-object-fixup fasl-output)))
1113       ;; No matter what the flavor, we'll always dump the position
1114       (dump-word position fasl-output)))
1115   (values))
1116
1117 ;;; Dump out the constant pool and code-vector for component, push the
1118 ;;; result in the table, and return the offset.
1119 ;;;
1120 ;;; The only tricky thing is handling constant-pool references to
1121 ;;; functions. If we have already dumped the function, then we just
1122 ;;; push the code pointer. Otherwise, we must create back-patching
1123 ;;; information so that the constant will be set when the function is
1124 ;;; eventually dumped. This is a bit awkward, since we don't have the
1125 ;;; handle for the code object being dumped while we are dumping its
1126 ;;; constants.
1127 ;;;
1128 ;;; We dump trap objects in any unused slots or forward referenced slots.
1129 (defun dump-code-object (component
1130                          code-segment
1131                          code-length
1132                          trace-table-as-list
1133                          fixups
1134                          fasl-output)
1135
1136   (declare (type component component)
1137            (list trace-table-as-list)
1138            (type index code-length)
1139            (type fasl-output fasl-output))
1140
1141   (let* ((2comp (component-info component))
1142          (constants (sb!c::ir2-component-constants 2comp))
1143          (header-length (length constants))
1144          (packed-trace-table (pack-trace-table trace-table-as-list))
1145          (total-length (+ code-length
1146                           (* (length packed-trace-table)
1147                              sb!c::tt-bytes-per-entry))))
1148
1149     (collect ((patches))
1150
1151       ;; Dump the offset of the trace table.
1152       (dump-object code-length fasl-output)
1153       ;; FIXME: As long as we don't have GENGC, the trace table is
1154       ;; hardwired to be empty. And SBCL doesn't have GENGC (and as
1155       ;; far as I know no modern CMU CL does either -- WHN
1156       ;; 2001-10-05). So might we be able to get rid of trace tables?
1157       ;;
1158       ;; Note that gencgc also does something with the trace table.
1159
1160       ;; Dump the constants, noting any :ENTRY constants that have to
1161       ;; be patched.
1162       (loop for i from sb!vm:code-constants-offset below header-length do
1163         (let ((entry (aref constants i)))
1164           (etypecase entry
1165             (constant
1166              (dump-object (sb!c::constant-value entry) fasl-output))
1167             (cons
1168              (ecase (car entry)
1169                (:entry
1170                 (let* ((info (sb!c::leaf-info (cdr entry)))
1171                        (handle (gethash info
1172                                         (fasl-output-entry-table
1173                                          fasl-output))))
1174                   (declare (type sb!c::entry-info info))
1175                   (cond
1176                    (handle
1177                     (dump-push handle fasl-output))
1178                    (t
1179                     (patches (cons info i))
1180                     (dump-fop 'fop-misc-trap fasl-output)))))
1181                (:load-time-value
1182                 (dump-push (cdr entry) fasl-output))
1183                (:fdefinition
1184                 (dump-object (cdr entry) fasl-output)
1185                 (dump-fop 'fop-fdefinition fasl-output))))
1186             (null
1187              (dump-fop 'fop-misc-trap fasl-output)))))
1188
1189       ;; Dump the debug info.
1190       (let ((info (sb!c::debug-info-for-component component))
1191             (*dump-only-valid-structures* nil))
1192         (dump-object info fasl-output)
1193         (let ((info-handle (dump-pop fasl-output)))
1194           (dump-push info-handle fasl-output)
1195           (push info-handle (fasl-output-debug-info fasl-output))))
1196
1197       (let ((num-consts (- header-length sb!vm:code-trace-table-offset-slot)))
1198         (cond ((and (< num-consts #x100) (< total-length #x10000))
1199                (dump-fop 'fop-small-code fasl-output)
1200                (dump-byte num-consts fasl-output)
1201                (dump-integer-as-n-bytes total-length (/ sb!vm:n-word-bytes 2) fasl-output))
1202               (t
1203                (dump-fop 'fop-code fasl-output)
1204                (dump-word num-consts fasl-output)
1205                (dump-word total-length fasl-output))))
1206
1207       ;; These two dumps are only ones which contribute to our
1208       ;; TOTAL-LENGTH value.
1209       (dump-segment code-segment code-length fasl-output)
1210       (dump-i-vector packed-trace-table fasl-output :data-only t)
1211
1212       ;; DUMP-FIXUPS does its own internal DUMP-FOPs: the bytes it
1213       ;; dumps aren't included in the TOTAL-LENGTH passed to our
1214       ;; FOP-CODE/FOP-SMALL-CODE fop.
1215       (dump-fixups fixups fasl-output)
1216
1217       (dump-fop 'fop-sanctify-for-execution fasl-output)
1218
1219       (let ((handle (dump-pop fasl-output)))
1220         (dolist (patch (patches))
1221           (push (cons handle (cdr patch))
1222                 (gethash (car patch)
1223                          (fasl-output-patch-table fasl-output))))
1224         handle))))
1225
1226 (defun dump-assembler-routines (code-segment length fixups routines file)
1227   (dump-fop 'fop-assembler-code file)
1228   (dump-word length file)
1229   (write-segment-contents code-segment (fasl-output-stream file))
1230   (dolist (routine routines)
1231     (dump-fop 'fop-normal-load file)
1232     (let ((*cold-load-dump* t))
1233       (dump-object (car routine) file))
1234     (dump-fop 'fop-maybe-cold-load file)
1235     (dump-fop 'fop-assembler-routine file)
1236     (dump-word (label-position (cdr routine)) file))
1237   (dump-fixups fixups file)
1238   (dump-fop 'fop-sanctify-for-execution file)
1239   (dump-pop file))
1240
1241 ;;; Dump a function entry data structure corresponding to ENTRY to
1242 ;;; FILE. CODE-HANDLE is the table offset of the code object for the
1243 ;;; component.
1244 (defun dump-one-entry (entry code-handle file)
1245   (declare (type sb!c::entry-info entry) (type index code-handle)
1246            (type fasl-output file))
1247   (let ((name (sb!c::entry-info-name entry)))
1248     (dump-push code-handle file)
1249     (dump-object name file)
1250     (dump-object (sb!c::entry-info-arguments entry) file)
1251     (dump-object (sb!c::entry-info-type entry) file)
1252     (dump-object (sb!c::entry-info-xref entry) file)
1253     (dump-fop 'fop-fun-entry file)
1254     (dump-word (label-position (sb!c::entry-info-offset entry)) file)
1255     (dump-pop file)))
1256
1257 ;;; Alter the code object referenced by CODE-HANDLE at the specified
1258 ;;; OFFSET, storing the object referenced by ENTRY-HANDLE.
1259 (defun dump-alter-code-object (code-handle offset entry-handle file)
1260   (declare (type index code-handle entry-handle offset))
1261   (declare (type fasl-output file))
1262   (dump-push code-handle file)
1263   (dump-push entry-handle file)
1264   (dump-fop* offset fop-byte-alter-code fop-alter-code file)
1265   (values))
1266
1267 ;;; Dump the code, constants, etc. for component. We pass in the
1268 ;;; assembler fixups, code vector and node info.
1269 (defun fasl-dump-component (component
1270                             code-segment
1271                             code-length
1272                             trace-table
1273                             fixups
1274                             file)
1275   (declare (type component component) (list trace-table))
1276   (declare (type fasl-output file))
1277
1278   (dump-fop 'fop-verify-table-size file)
1279   (dump-word (fasl-output-table-free file) file)
1280
1281   #!+sb-dyncount
1282   (let ((info (sb!c::ir2-component-dyncount-info (component-info component))))
1283     (when info
1284       (fasl-validate-structure info file)))
1285
1286   (let ((code-handle (dump-code-object component
1287                                        code-segment
1288                                        code-length
1289                                        trace-table
1290                                        fixups
1291                                        file))
1292         (2comp (component-info component)))
1293
1294     (dolist (entry (sb!c::ir2-component-entries 2comp))
1295       (let ((entry-handle (dump-one-entry entry code-handle file)))
1296         (setf (gethash entry (fasl-output-entry-table file)) entry-handle)
1297         (let ((old (gethash entry (fasl-output-patch-table file))))
1298           (when old
1299             (dolist (patch old)
1300               (dump-alter-code-object (car patch)
1301                                       (cdr patch)
1302                                       entry-handle
1303                                       file))
1304             (remhash entry (fasl-output-patch-table file)))))))
1305   (values))
1306
1307 (defun dump-push-previously-dumped-fun (fun fasl-output)
1308   (declare (type sb!c::clambda fun))
1309   (let ((handle (gethash (sb!c::leaf-info fun)
1310                          (fasl-output-entry-table fasl-output))))
1311     (aver handle)
1312     (dump-push handle fasl-output))
1313   (values))
1314
1315 ;;; Dump a FOP-FUNCALL to call an already-dumped top level lambda at
1316 ;;; load time.
1317 (defun fasl-dump-toplevel-lambda-call (fun fasl-output)
1318   (declare (type sb!c::clambda fun))
1319   (dump-push-previously-dumped-fun fun fasl-output)
1320   (dump-fop 'fop-funcall-for-effect fasl-output)
1321   (dump-byte 0 fasl-output)
1322   (values))
1323
1324 ;;; Dump a FOP-FSET to arrange static linkage (at cold init) between
1325 ;;; FUN-NAME and the already-dumped function whose dump handle is
1326 ;;; FUN-DUMP-HANDLE.
1327 #+sb-xc-host
1328 (defun fasl-dump-cold-fset (fun-name fun-dump-handle fasl-output)
1329   (declare (type fixnum fun-dump-handle))
1330   (aver (legal-fun-name-p fun-name))
1331   (dump-non-immediate-object fun-name fasl-output)
1332   (dump-push fun-dump-handle fasl-output)
1333   (dump-fop 'fop-fset fasl-output)
1334   (values))
1335
1336 ;;; Compute the correct list of DEBUG-SOURCE structures and backpatch
1337 ;;; all of the dumped DEBUG-INFO structures. We clear the
1338 ;;; FASL-OUTPUT-DEBUG-INFO, so that subsequent components with
1339 ;;; different source info may be dumped.
1340 (defun fasl-dump-source-info (info fasl-output)
1341   (declare (type sb!c::source-info info))
1342   (let ((res (sb!c::debug-source-for-info info))
1343         (*dump-only-valid-structures* nil))
1344     #+sb-xc-host (setf (sb!c::debug-source-created res) 0
1345                        (sb!c::debug-source-compiled res) 0)
1346     (dump-object res fasl-output)
1347     (let ((res-handle (dump-pop fasl-output)))
1348       (dolist (info-handle (fasl-output-debug-info fasl-output))
1349         (dump-push res-handle fasl-output)
1350         (dump-fop 'fop-structset fasl-output)
1351         (dump-word info-handle fasl-output)
1352         (dump-word sb!c::+debug-info-source-index+ fasl-output))
1353       #+sb-xc-host
1354       (progn
1355         (dump-push res-handle fasl-output)
1356         (dump-fop 'fop-note-debug-source fasl-output))))
1357   (setf (fasl-output-debug-info fasl-output) nil)
1358   (values))
1359 \f
1360 ;;;; dumping structures
1361
1362 (defun dump-structure (struct file)
1363   (when *dump-only-valid-structures*
1364     (unless (gethash struct (fasl-output-valid-structures file))
1365       (error "attempt to dump invalid structure:~%  ~S~%How did this happen?"
1366              struct)))
1367   (note-potential-circularity struct file)
1368   (aver (%instance-ref struct 0))
1369   (do* ((length (%instance-length struct))
1370         (ntagged (- length (layout-n-untagged-slots (%instance-ref struct 0))))
1371         (circ (fasl-output-circularity-table file))
1372         ;; last slot first on the stack, so that the layout is on top:
1373         (index (1- length) (1- index)))
1374       ((minusp index)
1375        (dump-fop* length fop-small-struct fop-struct file))
1376     (let* ((obj (if (>= index ntagged)
1377                     (%raw-instance-ref/word struct (- length index 1))
1378                     (%instance-ref struct index)))
1379            (ref (gethash obj circ)))
1380       (cond (ref
1381              (aver (not (zerop index)))
1382              (push (make-circularity :type :struct-set
1383                                      :object struct
1384                                      :index index
1385                                      :value obj
1386                                      :enclosing-object ref)
1387                    *circularities-detected*)
1388              (sub-dump-object nil file))
1389             (t
1390              (sub-dump-object obj file))))))
1391
1392 (defun dump-layout (obj file)
1393   (when (layout-invalid obj)
1394     (compiler-error "attempt to dump reference to obsolete class: ~S"
1395                     (layout-classoid obj)))
1396   (let ((name (classoid-name (layout-classoid obj))))
1397     (unless name
1398       (compiler-error "dumping anonymous layout: ~S" obj))
1399     (dump-fop 'fop-normal-load file)
1400     (let ((*cold-load-dump* t))
1401       (dump-object name file))
1402     (dump-fop 'fop-maybe-cold-load file))
1403   (sub-dump-object (layout-inherits obj) file)
1404   (sub-dump-object (layout-depthoid obj) file)
1405   (sub-dump-object (layout-length obj) file)
1406   (sub-dump-object (layout-n-untagged-slots obj) file)
1407   (dump-fop 'fop-layout file))