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