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