0.8.20.20:
[sbcl.git] / src / compiler / generic / genesis.lisp
1 ;;;; "cold" core image builder: This is how we create a target Lisp
2 ;;;; system from scratch, by converting from fasl files to an image
3 ;;;; file in the cross-compilation host, without the help of the
4 ;;;; target Lisp system.
5 ;;;;
6 ;;;; As explained by Rob MacLachlan on the CMU CL mailing list Wed, 06
7 ;;;; Jan 1999 11:05:02 -0500, this cold load generator more or less
8 ;;;; fakes up static function linking. I.e. it makes sure that all the
9 ;;;; DEFUN-defined functions in the fasl files it reads are bound to the
10 ;;;; corresponding symbols before execution starts. It doesn't do
11 ;;;; anything to initialize variable values; instead it just arranges
12 ;;;; for !COLD-INIT to be called at cold load time. !COLD-INIT is
13 ;;;; responsible for explicitly initializing anything which has to be
14 ;;;; initialized early before it transfers control to the ordinary
15 ;;;; top level forms.
16 ;;;;
17 ;;;; (In CMU CL, and in SBCL as of 0.6.9 anyway, functions not defined
18 ;;;; by DEFUN aren't set up specially by GENESIS. In particular,
19 ;;;; structure slot accessors are not set up. Slot accessors are
20 ;;;; available at cold init time because they're usually compiled
21 ;;;; inline. They're not available as out-of-line functions until the
22 ;;;; toplevel forms installing them have run.)
23
24 ;;;; This software is part of the SBCL system. See the README file for
25 ;;;; more information.
26 ;;;;
27 ;;;; This software is derived from the CMU CL system, which was
28 ;;;; written at Carnegie Mellon University and released into the
29 ;;;; public domain. The software is in the public domain and is
30 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
31 ;;;; files for more information.
32
33 (in-package "SB!FASL")
34
35 ;;; a magic number used to identify our core files
36 (defconstant core-magic
37   (logior (ash (sb!xc:char-code #\S) 24)
38           (ash (sb!xc:char-code #\B) 16)
39           (ash (sb!xc:char-code #\C) 8)
40           (sb!xc:char-code #\L)))
41
42 ;;; the current version of SBCL core files
43 ;;;
44 ;;; FIXME: This is left over from CMU CL, and not well thought out.
45 ;;; It's good to make sure that the runtime doesn't try to run core
46 ;;; files from the wrong version, but a single number is not the ideal
47 ;;; way to do this in high level data like this (as opposed to e.g. in
48 ;;; IP packets), and in fact the CMU CL version number never ended up
49 ;;; being incremented past 0. A better approach might be to use a
50 ;;; string which is set from CVS data. (Though now as of sbcl-0.7.8 or
51 ;;; so, we have another problem that the core incompatibility
52 ;;; detection mechanisms are on such a hair trigger -- with even
53 ;;; different builds from the same sources being considered
54 ;;; incompatible -- that any coarser-grained versioning mechanisms
55 ;;; like this are largely irrelevant as long as the hair-triggering
56 ;;; persists.)
57 ;;;
58 ;;; 0: inherited from CMU CL
59 ;;; 1: rearranged static symbols for sbcl-0.6.8
60 ;;; 2: eliminated non-ANSI %DEFCONSTANT/%%DEFCONSTANT support,
61 ;;;    deleted a slot from DEBUG-SOURCE structure
62 ;;; 3: added build ID to cores to discourage sbcl/.core mismatch
63 (defconstant sbcl-core-version-integer 3)
64
65 (defun round-up (number size)
66   #!+sb-doc
67   "Round NUMBER up to be an integral multiple of SIZE."
68   (* size (ceiling number size)))
69 \f
70 ;;;; implementing the concept of "vector" in (almost) portable
71 ;;;; Common Lisp
72 ;;;;
73 ;;;; "If you only need to do such simple things, it doesn't really
74 ;;;; matter which language you use." -- _ANSI Common Lisp_, p. 1, Paul
75 ;;;; Graham (evidently not considering the abstraction "vector" to be
76 ;;;; such a simple thing:-)
77
78 (eval-when (:compile-toplevel :load-toplevel :execute)
79   (defconstant +smallvec-length+
80     (expt 2 16)))
81
82 ;;; an element of a BIGVEC -- a vector small enough that we have
83 ;;; a good chance of it being portable to other Common Lisps
84 (deftype smallvec ()
85   `(simple-array (unsigned-byte 8) (,+smallvec-length+)))
86
87 (defun make-smallvec ()
88   (make-array +smallvec-length+ :element-type '(unsigned-byte 8)))
89
90 ;;; a big vector, implemented as a vector of SMALLVECs
91 ;;;
92 ;;; KLUDGE: This implementation seems portable enough for our
93 ;;; purposes, since realistically every modern implementation is
94 ;;; likely to support vectors of at least 2^16 elements. But if you're
95 ;;; masochistic enough to read this far into the contortions imposed
96 ;;; on us by ANSI and the Lisp community, for daring to use the
97 ;;; abstraction of a large linearly addressable memory space, which is
98 ;;; after all only directly supported by the underlying hardware of at
99 ;;; least 99% of the general-purpose computers in use today, then you
100 ;;; may be titillated to hear that in fact this code isn't really
101 ;;; portable, because as of sbcl-0.7.4 we need somewhat more than
102 ;;; 16Mbytes to represent a core, and ANSI only guarantees that
103 ;;; ARRAY-DIMENSION-LIMIT is not less than 1024. -- WHN 2002-06-13
104 (defstruct bigvec
105   (outer-vector (vector (make-smallvec)) :type (vector smallvec)))
106
107 ;;; analogous to SVREF, but into a BIGVEC
108 (defun bvref (bigvec index)
109   (multiple-value-bind (outer-index inner-index)
110       (floor index +smallvec-length+)
111     (aref (the smallvec
112             (svref (bigvec-outer-vector bigvec) outer-index))
113           inner-index)))
114 (defun (setf bvref) (new-value bigvec index)
115   (multiple-value-bind (outer-index inner-index)
116       (floor index +smallvec-length+)
117     (setf (aref (the smallvec
118                   (svref (bigvec-outer-vector bigvec) outer-index))
119                 inner-index)
120           new-value)))
121
122 ;;; analogous to LENGTH, but for a BIGVEC
123 ;;;
124 ;;; the length of BIGVEC, measured in the number of BVREFable bytes it
125 ;;; can hold
126 (defun bvlength (bigvec)
127   (* (length (bigvec-outer-vector bigvec))
128      +smallvec-length+))
129
130 ;;; analogous to WRITE-SEQUENCE, but for a BIGVEC
131 (defun write-bigvec-as-sequence (bigvec stream &key (start 0) end)
132   (loop for i of-type index from start below (or end (bvlength bigvec)) do
133         (write-byte (bvref bigvec i)
134                     stream)))
135
136 ;;; analogous to READ-SEQUENCE-OR-DIE, but for a BIGVEC
137 (defun read-bigvec-as-sequence-or-die (bigvec stream &key (start 0) end)
138   (loop for i of-type index from start below (or end (bvlength bigvec)) do
139         (setf (bvref bigvec i)
140               (read-byte stream))))
141
142 ;;; Grow BIGVEC (exponentially, so that large increases in size have
143 ;;; asymptotic logarithmic cost per byte).
144 (defun expand-bigvec (bigvec)
145   (let* ((old-outer-vector (bigvec-outer-vector bigvec))
146          (length-old-outer-vector (length old-outer-vector))
147          (new-outer-vector (make-array (* 2 length-old-outer-vector))))
148     (dotimes (i length-old-outer-vector)
149       (setf (svref new-outer-vector i)
150             (svref old-outer-vector i)))
151     (loop for i from length-old-outer-vector below (length new-outer-vector) do
152           (setf (svref new-outer-vector i)
153                 (make-smallvec)))
154     (setf (bigvec-outer-vector bigvec)
155           new-outer-vector))
156   bigvec)
157 \f
158 ;;;; looking up bytes and multi-byte values in a BIGVEC (considering
159 ;;;; it as an image of machine memory on the cross-compilation target)
160
161 ;;; BVREF-32 and friends. These are like SAP-REF-n, except that
162 ;;; instead of a SAP we use a BIGVEC.
163 (macrolet ((make-bvref-n
164             (n)
165             (let* ((name (intern (format nil "BVREF-~A" n)))
166                    (number-octets (/ n 8))
167                    (ash-list-le
168                     (loop for i from 0 to (1- number-octets)
169                           collect `(ash (bvref bigvec (+ byte-index ,i))
170                                         ,(* i 8))))
171                    (ash-list-be
172                     (loop for i from 0 to (1- number-octets)
173                           collect `(ash (bvref bigvec
174                                                (+ byte-index
175                                                   ,(- number-octets 1 i)))
176                                         ,(* i 8))))
177                    (setf-list-le
178                     (loop for i from 0 to (1- number-octets)
179                           append
180                           `((bvref bigvec (+ byte-index ,i))
181                             (ldb (byte 8 ,(* i 8)) new-value))))
182                    (setf-list-be
183                     (loop for i from 0 to (1- number-octets)
184                           append
185                           `((bvref bigvec (+ byte-index ,i))
186                             (ldb (byte 8 ,(- n 8 (* i 8))) new-value)))))
187               `(progn
188                  (defun ,name (bigvec byte-index)
189                    (logior ,@(ecase sb!c:*backend-byte-order*
190                                (:little-endian ash-list-le)
191                                (:big-endian ash-list-be))))
192                  (defun (setf ,name) (new-value bigvec byte-index)
193                    (setf ,@(ecase sb!c:*backend-byte-order*
194                              (:little-endian setf-list-le)
195                              (:big-endian setf-list-be))))))))
196   (make-bvref-n 8)
197   (make-bvref-n 16)
198   (make-bvref-n 32)
199   (make-bvref-n 64))
200
201 ;; lispobj-sized word, whatever that may be
202 ;; hopefully nobody ever wants a 128-bit SBCL...
203 #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
204 (progn
205 (defun bvref-word (bytes index)
206   (bvref-64 bytes index))
207 (defun (setf bvref-word) (new-val bytes index)
208   (setf (bvref-64 bytes index) new-val)))
209
210 #!+#.(cl:if (cl:= 32 sb!vm:n-word-bits) '(and) '(or))
211 (progn
212 (defun bvref-word (bytes index)
213   (bvref-32 bytes index))
214 (defun (setf bvref-word) (new-val bytes index)
215   (setf (bvref-32 bytes index) new-val)))
216
217 \f
218 ;;;; representation of spaces in the core
219
220 ;;; If there is more than one dynamic space in memory (i.e., if a
221 ;;; copying GC is in use), then only the active dynamic space gets
222 ;;; dumped to core.
223 (defvar *dynamic*)
224 (defconstant dynamic-core-space-id 1)
225
226 (defvar *static*)
227 (defconstant static-core-space-id 2)
228
229 (defvar *read-only*)
230 (defconstant read-only-core-space-id 3)
231
232 (defconstant descriptor-low-bits 16
233   "the number of bits in the low half of the descriptor")
234 (defconstant target-space-alignment (ash 1 descriptor-low-bits)
235   "the alignment requirement for spaces in the target.
236   Must be at least (ASH 1 DESCRIPTOR-LOW-BITS)")
237
238 ;;; a GENESIS-time representation of a memory space (e.g. read-only
239 ;;; space, dynamic space, or static space)
240 (defstruct (gspace (:constructor %make-gspace)
241                    (:copier nil))
242   ;; name and identifier for this GSPACE
243   (name (missing-arg) :type symbol :read-only t)
244   (identifier (missing-arg) :type fixnum :read-only t)
245   ;; the word address where the data will be loaded
246   (word-address (missing-arg) :type unsigned-byte :read-only t)
247   ;; the data themselves. (Note that in CMU CL this was a pair of
248   ;; fields SAP and WORDS-ALLOCATED, but that wasn't very portable.)
249   ;; (And then in SBCL this was a VECTOR, but turned out to be
250   ;; unportable too, since ANSI doesn't think that arrays longer than
251   ;; 1024 (!) should needed by portable CL code...)
252   (bytes (make-bigvec) :read-only t)
253   ;; the index of the next unwritten word (i.e. chunk of
254   ;; SB!VM:N-WORD-BYTES bytes) in BYTES, or equivalently the number of
255   ;; words actually written in BYTES. In order to convert to an actual
256   ;; index into BYTES, thus must be multiplied by SB!VM:N-WORD-BYTES.
257   (free-word-index 0))
258
259 (defun gspace-byte-address (gspace)
260   (ash (gspace-word-address gspace) sb!vm:word-shift))
261
262 (def!method print-object ((gspace gspace) stream)
263   (print-unreadable-object (gspace stream :type t)
264     (format stream "~S" (gspace-name gspace))))
265
266 (defun make-gspace (name identifier byte-address)
267   (unless (zerop (rem byte-address target-space-alignment))
268     (error "The byte address #X~X is not aligned on a #X~X-byte boundary."
269            byte-address
270            target-space-alignment))
271   (%make-gspace :name name
272                 :identifier identifier
273                 :word-address (ash byte-address (- sb!vm:word-shift))))
274 \f
275 ;;;; representation of descriptors
276
277 (defstruct (descriptor
278             (:constructor make-descriptor
279                           (high low &optional gspace word-offset))
280             (:copier nil))
281   ;; the GSPACE that this descriptor is allocated in, or NIL if not set yet.
282   (gspace nil :type (or gspace null))
283   ;; the offset in words from the start of GSPACE, or NIL if not set yet
284   (word-offset nil :type (or sb!vm:word null))
285   ;; the high and low halves of the descriptor
286   ;;
287   ;; KLUDGE: Judging from the comments in genesis.lisp of the CMU CL
288   ;; old-rt compiler, this split dates back from a very early version
289   ;; of genesis where 32-bit integers were represented as conses of
290   ;; two 16-bit integers. In any system with nice (UNSIGNED-BYTE 32)
291   ;; structure slots, like CMU CL >= 17 or any version of SBCL, there
292   ;; seems to be no reason to persist in this. -- WHN 19990917
293   high
294   low)
295 (def!method print-object ((des descriptor) stream)
296   (let ((lowtag (descriptor-lowtag des)))
297     (print-unreadable-object (des stream :type t)
298       (cond ((or (= lowtag sb!vm:even-fixnum-lowtag)
299                  (= lowtag sb!vm:odd-fixnum-lowtag))
300              (let ((unsigned (logior (ash (descriptor-high des)
301                                           (1+ (- descriptor-low-bits
302                                                  sb!vm:n-lowtag-bits)))
303                                      (ash (descriptor-low des)
304                                           (- 1 sb!vm:n-lowtag-bits)))))
305                (format stream
306                        "for fixnum: ~W"
307                        (if (> unsigned #x1FFFFFFF)
308                            (- unsigned #x40000000)
309                            unsigned))))
310             ((or (= lowtag sb!vm:other-immediate-0-lowtag)
311                  (= lowtag sb!vm:other-immediate-1-lowtag)
312                  #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
313                  (= lowtag sb!vm:other-immediate-2-lowtag)
314                  #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
315                  (= lowtag sb!vm:other-immediate-3-lowtag))
316              (format stream
317                      "for other immediate: #X~X, type #b~8,'0B"
318                      (ash (descriptor-bits des) (- sb!vm:n-widetag-bits))
319                      (logand (descriptor-low des) sb!vm:widetag-mask)))
320             (t
321              (format stream
322                      "for pointer: #X~X, lowtag #b~3,'0B, ~A"
323                      (logior (ash (descriptor-high des) descriptor-low-bits)
324                              (logandc2 (descriptor-low des) sb!vm:lowtag-mask))
325                      lowtag
326                      (let ((gspace (descriptor-gspace des)))
327                        (if gspace
328                            (gspace-name gspace)
329                            "unknown"))))))))
330
331 ;;; Return a descriptor for a block of LENGTH bytes out of GSPACE. The
332 ;;; free word index is boosted as necessary, and if additional memory
333 ;;; is needed, we grow the GSPACE. The descriptor returned is a
334 ;;; pointer of type LOWTAG.
335 (defun allocate-cold-descriptor (gspace length lowtag)
336   (let* ((bytes (round-up length (ash 1 sb!vm:n-lowtag-bits)))
337          (old-free-word-index (gspace-free-word-index gspace))
338          (new-free-word-index (+ old-free-word-index
339                                  (ash bytes (- sb!vm:word-shift)))))
340     ;; Grow GSPACE as necessary until it's big enough to handle
341     ;; NEW-FREE-WORD-INDEX.
342     (do ()
343         ((>= (bvlength (gspace-bytes gspace))
344              (* new-free-word-index sb!vm:n-word-bytes)))
345       (expand-bigvec (gspace-bytes gspace)))
346     ;; Now that GSPACE is big enough, we can meaningfully grab a chunk of it.
347     (setf (gspace-free-word-index gspace) new-free-word-index)
348     (let ((ptr (+ (gspace-word-address gspace) old-free-word-index)))
349       (make-descriptor (ash ptr (- sb!vm:word-shift descriptor-low-bits))
350                        (logior (ash (logand ptr
351                                             (1- (ash 1
352                                                      (- descriptor-low-bits
353                                                         sb!vm:word-shift))))
354                                     sb!vm:word-shift)
355                                lowtag)
356                        gspace
357                        old-free-word-index))))
358
359 (defun descriptor-lowtag (des)
360   #!+sb-doc
361   "the lowtag bits for DES"
362   (logand (descriptor-low des) sb!vm:lowtag-mask))
363
364 (defun descriptor-bits (des)
365   (logior (ash (descriptor-high des) descriptor-low-bits)
366           (descriptor-low des)))
367
368 (defun descriptor-fixnum (des)
369   (let ((bits (descriptor-bits des)))
370     (if (logbitp (1- sb!vm:n-word-bits) bits)
371         ;; KLUDGE: The (- SB!VM:N-WORD-BITS 2) term here looks right to
372         ;; me, and it works, but in CMU CL it was (1- SB!VM:N-WORD-BITS),
373         ;; and although that doesn't make sense for me, or work for me,
374         ;; it's hard to see how it could have been wrong, since CMU CL
375         ;; genesis worked. It would be nice to understand how this came
376         ;; to be.. -- WHN 19990901
377         (logior (ash bits (- 1 sb!vm:n-lowtag-bits))
378                 (ash -1 (1+ sb!vm:n-positive-fixnum-bits)))
379         (ash bits (- 1 sb!vm:n-lowtag-bits)))))
380
381 ;;; common idioms
382 (defun descriptor-bytes (des)
383   (gspace-bytes (descriptor-intuit-gspace des)))
384 (defun descriptor-byte-offset (des)
385   (ash (descriptor-word-offset des) sb!vm:word-shift))
386
387 ;;; If DESCRIPTOR-GSPACE is already set, just return that. Otherwise,
388 ;;; figure out a GSPACE which corresponds to DES, set it into
389 ;;; (DESCRIPTOR-GSPACE DES), set a consistent value into
390 ;;; (DESCRIPTOR-WORD-OFFSET DES), and return the GSPACE.
391 (declaim (ftype (function (descriptor) gspace) descriptor-intuit-gspace))
392 (defun descriptor-intuit-gspace (des)
393   (if (descriptor-gspace des)
394     (descriptor-gspace des)
395     ;; KLUDGE: It's not completely clear to me what's going on here;
396     ;; this is a literal translation from of some rather mysterious
397     ;; code from CMU CL's DESCRIPTOR-SAP function. Some explanation
398     ;; would be nice. -- WHN 19990817
399     (let ((lowtag (descriptor-lowtag des))
400           (high (descriptor-high des))
401           (low (descriptor-low des)))
402       (if (or (eql lowtag sb!vm:fun-pointer-lowtag)
403               (eql lowtag sb!vm:instance-pointer-lowtag)
404               (eql lowtag sb!vm:list-pointer-lowtag)
405               (eql lowtag sb!vm:other-pointer-lowtag))
406         (dolist (gspace (list *dynamic* *static* *read-only*)
407                         (error "couldn't find a GSPACE for ~S" des))
408           ;; This code relies on the fact that GSPACEs are aligned
409           ;; such that the descriptor-low-bits low bits are zero.
410           (when (and (>= high (ash (gspace-word-address gspace)
411                                    (- sb!vm:word-shift descriptor-low-bits)))
412                      (<= high (ash (+ (gspace-word-address gspace)
413                                       (gspace-free-word-index gspace))
414                                    (- sb!vm:word-shift descriptor-low-bits))))
415             (setf (descriptor-gspace des) gspace)
416             (setf (descriptor-word-offset des)
417                   (+ (ash (- high (ash (gspace-word-address gspace)
418                                        (- sb!vm:word-shift
419                                           descriptor-low-bits)))
420                           (- descriptor-low-bits sb!vm:word-shift))
421                      (ash (logandc2 low sb!vm:lowtag-mask)
422                           (- sb!vm:word-shift))))
423             (return gspace)))
424         (error "don't even know how to look for a GSPACE for ~S" des)))))
425
426 (defun make-random-descriptor (value)
427   (make-descriptor (logand (ash value (- descriptor-low-bits))
428                            (1- (ash 1
429                                     (- sb!vm:n-word-bits
430                                        descriptor-low-bits))))
431                    (logand value (1- (ash 1 descriptor-low-bits)))))
432
433 (defun make-fixnum-descriptor (num)
434   (when (>= (integer-length num)
435             (1+ (- sb!vm:n-word-bits sb!vm:n-lowtag-bits)))
436     (error "~W is too big for a fixnum." num))
437   (make-random-descriptor (ash num (1- sb!vm:n-lowtag-bits))))
438
439 (defun make-other-immediate-descriptor (data type)
440   (make-descriptor (ash data (- sb!vm:n-widetag-bits descriptor-low-bits))
441                    (logior (logand (ash data (- descriptor-low-bits
442                                                 sb!vm:n-widetag-bits))
443                                    (1- (ash 1 descriptor-low-bits)))
444                            type)))
445
446 (defun make-character-descriptor (data)
447   (make-other-immediate-descriptor data sb!vm:character-widetag))
448
449 (defun descriptor-beyond (des offset type)
450   (let* ((low (logior (+ (logandc2 (descriptor-low des) sb!vm:lowtag-mask)
451                          offset)
452                       type))
453          (high (+ (descriptor-high des)
454                   (ash low (- descriptor-low-bits)))))
455     (make-descriptor high (logand low (1- (ash 1 descriptor-low-bits))))))
456 \f
457 ;;;; miscellaneous variables and other noise
458
459 ;;; a numeric value to be returned for undefined foreign symbols, or NIL if
460 ;;; undefined foreign symbols are to be treated as an error.
461 ;;; (In the first pass of GENESIS, needed to create a header file before
462 ;;; the C runtime can be built, various foreign symbols will necessarily
463 ;;; be undefined, but we don't need actual values for them anyway, and
464 ;;; we can just use 0 or some other placeholder. In the second pass of
465 ;;; GENESIS, all foreign symbols should be defined, so any undefined
466 ;;; foreign symbol is a problem.)
467 ;;;
468 ;;; KLUDGE: It would probably be cleaner to rewrite GENESIS so that it
469 ;;; never tries to look up foreign symbols in the first place unless
470 ;;; it's actually creating a core file (as in the second pass) instead
471 ;;; of using this hack to allow it to go through the motions without
472 ;;; causing an error. -- WHN 20000825
473 (defvar *foreign-symbol-placeholder-value*)
474
475 ;;; a handle on the trap object
476 (defvar *unbound-marker*)
477 ;; was:  (make-other-immediate-descriptor 0 sb!vm:unbound-marker-widetag)
478
479 ;;; a handle on the NIL object
480 (defvar *nil-descriptor*)
481
482 ;;; the head of a list of TOPLEVEL-THINGs describing stuff to be done
483 ;;; when the target Lisp starts up
484 ;;;
485 ;;; Each TOPLEVEL-THING can be a function to be executed or a fixup or
486 ;;; loadtime value, represented by (CONS KEYWORD ..). The FILENAME
487 ;;; tells which fasl file each list element came from, for debugging
488 ;;; purposes.
489 (defvar *current-reversed-cold-toplevels*)
490
491 ;;; the name of the object file currently being cold loaded (as a string, not a
492 ;;; pathname), or NIL if we're not currently cold loading any object file
493 (defvar *cold-load-filename* nil)
494 (declaim (type (or string null) *cold-load-filename*))
495 \f
496 ;;;; miscellaneous stuff to read and write the core memory
497
498 ;;; FIXME: should be DEFINE-MODIFY-MACRO
499 (defmacro cold-push (thing list)
500   #!+sb-doc
501   "Push THING onto the given cold-load LIST."
502   `(setq ,list (cold-cons ,thing ,list)))
503
504 (declaim (ftype (function (descriptor sb!vm:word) descriptor) read-wordindexed))
505 (defun read-wordindexed (address index)
506   #!+sb-doc
507   "Return the value which is displaced by INDEX words from ADDRESS."
508   (let* ((gspace (descriptor-intuit-gspace address))
509          (bytes (gspace-bytes gspace))
510          (byte-index (ash (+ index (descriptor-word-offset address))
511                           sb!vm:word-shift))
512          (value (bvref-word bytes byte-index)))
513     (make-random-descriptor value)))
514
515 (declaim (ftype (function (descriptor) descriptor) read-memory))
516 (defun read-memory (address)
517   #!+sb-doc
518   "Return the value at ADDRESS."
519   (read-wordindexed address 0))
520
521 ;;; (Note: In CMU CL, this function expected a SAP-typed ADDRESS
522 ;;; value, instead of the SAP-INT we use here.)
523 (declaim (ftype (function (sb!vm:word descriptor) (values))
524                 note-load-time-value-reference))
525 (defun note-load-time-value-reference (address marker)
526   (cold-push (cold-cons
527               (cold-intern :load-time-value-fixup)
528               (cold-cons (sap-int-to-core address)
529                          (cold-cons
530                           (number-to-core (descriptor-word-offset marker))
531                           *nil-descriptor*)))
532              *current-reversed-cold-toplevels*)
533   (values))
534
535 (declaim (ftype (function (descriptor sb!vm:word descriptor)) write-wordindexed))
536 (defun write-wordindexed (address index value)
537   #!+sb-doc
538   "Write VALUE displaced INDEX words from ADDRESS."
539   ;; KLUDGE: There is an algorithm (used in DESCRIPTOR-INTUIT-GSPACE)
540   ;; for calculating the value of the GSPACE slot from scratch. It
541   ;; doesn't work for all values, only some of them, but mightn't it
542   ;; be reasonable to see whether it works on VALUE before we give up
543   ;; because (DESCRIPTOR-GSPACE VALUE) isn't set? (Or failing that,
544   ;; perhaps write a comment somewhere explaining why it's not a good
545   ;; idea?) -- WHN 19990817
546   (if (and (null (descriptor-gspace value))
547            (not (null (descriptor-word-offset value))))
548     (note-load-time-value-reference (+ (logandc2 (descriptor-bits address)
549                                                  sb!vm:lowtag-mask)
550                                        (ash index sb!vm:word-shift))
551                                     value)
552     (let* ((bytes (gspace-bytes (descriptor-intuit-gspace address)))
553            (byte-index (ash (+ index (descriptor-word-offset address))
554                                sb!vm:word-shift)))
555       (setf (bvref-word bytes byte-index)
556             (descriptor-bits value)))))
557
558 (declaim (ftype (function (descriptor descriptor)) write-memory))
559 (defun write-memory (address value)
560   #!+sb-doc
561   "Write VALUE (a DESCRIPTOR) at ADDRESS (also a DESCRIPTOR)."
562   (write-wordindexed address 0 value))
563 \f
564 ;;;; allocating images of primitive objects in the cold core
565
566 ;;; There are three kinds of blocks of memory in the type system:
567 ;;; * Boxed objects (cons cells, structures, etc): These objects have no
568 ;;;   header as all slots are descriptors.
569 ;;; * Unboxed objects (bignums): There is a single header word that contains
570 ;;;   the length.
571 ;;; * Vector objects: There is a header word with the type, then a word for
572 ;;;   the length, then the data.
573 (defun allocate-boxed-object (gspace length lowtag)
574   #!+sb-doc
575   "Allocate LENGTH words in GSPACE and return a new descriptor of type LOWTAG
576   pointing to them."
577   (allocate-cold-descriptor gspace (ash length sb!vm:word-shift) lowtag))
578 (defun allocate-unboxed-object (gspace element-bits length type)
579   #!+sb-doc
580   "Allocate LENGTH units of ELEMENT-BITS bits plus a header word in GSPACE and
581   return an ``other-pointer'' descriptor to them. Initialize the header word
582   with the resultant length and TYPE."
583   (let* ((bytes (/ (* element-bits length) sb!vm:n-byte-bits))
584          (des (allocate-cold-descriptor gspace
585                                         (+ bytes sb!vm:n-word-bytes)
586                                         sb!vm:other-pointer-lowtag)))
587     (write-memory des
588                   (make-other-immediate-descriptor (ash bytes
589                                                         (- sb!vm:word-shift))
590                                                    type))
591     des))
592 (defun allocate-vector-object (gspace element-bits length type)
593   #!+sb-doc
594   "Allocate LENGTH units of ELEMENT-BITS size plus a header plus a length slot in
595   GSPACE and return an ``other-pointer'' descriptor to them. Initialize the
596   header word with TYPE and the length slot with LENGTH."
597   ;; FIXME: Here and in ALLOCATE-UNBOXED-OBJECT, BYTES is calculated using
598   ;; #'/ instead of #'CEILING, which seems wrong.
599   (let* ((bytes (/ (* element-bits length) sb!vm:n-byte-bits))
600          (des (allocate-cold-descriptor gspace
601                                         (+ bytes (* 2 sb!vm:n-word-bytes))
602                                         sb!vm:other-pointer-lowtag)))
603     (write-memory des (make-other-immediate-descriptor 0 type))
604     (write-wordindexed des
605                        sb!vm:vector-length-slot
606                        (make-fixnum-descriptor length))
607     des))
608 \f
609 ;;;; copying simple objects into the cold core
610
611 (defun base-string-to-core (string &optional (gspace *dynamic*))
612   #!+sb-doc
613   "Copy STRING (which must only contain STANDARD-CHARs) into the cold
614 core and return a descriptor to it."
615   ;; (Remember that the system convention for storage of strings leaves an
616   ;; extra null byte at the end to aid in call-out to C.)
617   (let* ((length (length string))
618          (des (allocate-vector-object gspace
619                                       sb!vm:n-byte-bits
620                                       (1+ length)
621                                       sb!vm:simple-base-string-widetag))
622          (bytes (gspace-bytes gspace))
623          (offset (+ (* sb!vm:vector-data-offset sb!vm:n-word-bytes)
624                     (descriptor-byte-offset des))))
625     (write-wordindexed des
626                        sb!vm:vector-length-slot
627                        (make-fixnum-descriptor length))
628     (dotimes (i length)
629       (setf (bvref bytes (+ offset i))
630             (sb!xc:char-code (aref string i))))
631     (setf (bvref bytes (+ offset length))
632           0) ; null string-termination character for C
633     des))
634
635 (defun bignum-to-core (n)
636   #!+sb-doc
637   "Copy a bignum to the cold core."
638   (let* ((words (ceiling (1+ (integer-length n)) sb!vm:n-word-bits))
639          (handle (allocate-unboxed-object *dynamic*
640                                           sb!vm:n-word-bits
641                                           words
642                                           sb!vm:bignum-widetag)))
643     (declare (fixnum words))
644     (do ((index 1 (1+ index))
645          (remainder n (ash remainder (- sb!vm:n-word-bits))))
646         ((> index words)
647          (unless (zerop (integer-length remainder))
648            ;; FIXME: Shouldn't this be a fatal error?
649            (warn "~W words of ~W were written, but ~W bits were left over."
650                  words n remainder)))
651       (let ((word (ldb (byte sb!vm:n-word-bits 0) remainder)))
652         (write-wordindexed handle index
653                            (make-descriptor (ash word (- descriptor-low-bits))
654                                             (ldb (byte descriptor-low-bits 0)
655                                                  word)))))
656     handle))
657
658 (defun number-pair-to-core (first second type)
659   #!+sb-doc
660   "Makes a number pair of TYPE (ratio or complex) and fills it in."
661   (let ((des (allocate-unboxed-object *dynamic* sb!vm:n-word-bits 2 type)))
662     (write-wordindexed des 1 first)
663     (write-wordindexed des 2 second)
664     des))
665
666 (defun write-double-float-bits (address index x)
667   (let ((hi (double-float-high-bits x))
668         (lo (double-float-low-bits x)))
669     (ecase sb!vm::n-word-bits
670       (32
671        (let ((high-bits (make-random-descriptor hi))
672              (low-bits (make-random-descriptor lo)))
673          (ecase sb!c:*backend-byte-order*
674            (:little-endian
675             (write-wordindexed address index low-bits)
676             (write-wordindexed address (1+ index) high-bits))
677            (:big-endian
678             (write-wordindexed address index high-bits)
679             (write-wordindexed address (1+ index) low-bits)))))
680       (64
681        (let ((bits (make-random-descriptor
682                     (ecase sb!c:*backend-byte-order*
683                       (:little-endian (logior lo (ash hi 32)))
684                       ;; Just guessing.
685                       #+nil (:big-endian (logior (logand hi #xffffffff)
686                                                  (ash lo 32)))))))
687          (write-wordindexed address index bits))))
688     address))
689
690 (defun float-to-core (x)
691   (etypecase x
692     (single-float
693      (let ((des (allocate-unboxed-object *dynamic*
694                                          sb!vm:n-word-bits
695                                          (1- sb!vm:single-float-size)
696                                          sb!vm:single-float-widetag)))
697        (write-wordindexed des
698                           sb!vm:single-float-value-slot
699                           (make-random-descriptor (single-float-bits x)))
700        des))
701     (double-float
702      (let ((des (allocate-unboxed-object *dynamic*
703                                          sb!vm:n-word-bits
704                                          (1- sb!vm:double-float-size)
705                                          sb!vm:double-float-widetag)))
706        (write-double-float-bits des sb!vm:double-float-value-slot x)))))
707
708 (defun complex-single-float-to-core (num)
709   (declare (type (complex single-float) num))
710   (let ((des (allocate-unboxed-object *dynamic* sb!vm:n-word-bits
711                                       (1- sb!vm:complex-single-float-size)
712                                       sb!vm:complex-single-float-widetag)))
713     (write-wordindexed des sb!vm:complex-single-float-real-slot
714                    (make-random-descriptor (single-float-bits (realpart num))))
715     (write-wordindexed des sb!vm:complex-single-float-imag-slot
716                    (make-random-descriptor (single-float-bits (imagpart num))))
717     des))
718
719 (defun complex-double-float-to-core (num)
720   (declare (type (complex double-float) num))
721   (let ((des (allocate-unboxed-object *dynamic* sb!vm:n-word-bits
722                                       (1- sb!vm:complex-double-float-size)
723                                       sb!vm:complex-double-float-widetag)))
724     (write-double-float-bits des sb!vm:complex-double-float-real-slot
725                              (realpart num))
726     (write-double-float-bits des sb!vm:complex-double-float-imag-slot
727                              (imagpart num))))
728
729 ;;; Copy the given number to the core.
730 (defun number-to-core (number)
731   (typecase number
732     (integer (if (< (integer-length number) 
733                     (- (1+ sb!vm:n-word-bits) sb!vm:n-lowtag-bits))
734                  (make-fixnum-descriptor number)
735                  (bignum-to-core number)))
736     (ratio (number-pair-to-core (number-to-core (numerator number))
737                                 (number-to-core (denominator number))
738                                 sb!vm:ratio-widetag))
739     ((complex single-float) (complex-single-float-to-core number))
740     ((complex double-float) (complex-double-float-to-core number))
741     #!+long-float
742     ((complex long-float)
743      (error "~S isn't a cold-loadable number at all!" number))
744     (complex (number-pair-to-core (number-to-core (realpart number))
745                                   (number-to-core (imagpart number))
746                                   sb!vm:complex-widetag))
747     (float (float-to-core number))
748     (t (error "~S isn't a cold-loadable number at all!" number))))
749
750 (declaim (ftype (function (sb!vm:word) descriptor) sap-int-to-core))
751 (defun sap-int-to-core (sap-int)
752   (let ((des (allocate-unboxed-object *dynamic*
753                                       sb!vm:n-word-bits
754                                       (1- sb!vm:sap-size)
755                                       sb!vm:sap-widetag)))
756     (write-wordindexed des
757                        sb!vm:sap-pointer-slot
758                        (make-random-descriptor sap-int))
759     des))
760
761 ;;; Allocate a cons cell in GSPACE and fill it in with CAR and CDR.
762 (defun cold-cons (car cdr &optional (gspace *dynamic*))
763   (let ((dest (allocate-boxed-object gspace 2 sb!vm:list-pointer-lowtag)))
764     (write-memory dest car)
765     (write-wordindexed dest 1 cdr)
766     dest))
767
768 ;;; Make a simple-vector on the target that holds the specified
769 ;;; OBJECTS, and return its descriptor.
770 (defun vector-in-core (&rest objects)
771   (let* ((size (length objects))
772          (result (allocate-vector-object *dynamic* sb!vm:n-word-bits size
773                                          sb!vm:simple-vector-widetag)))
774     (dotimes (index size)
775       (write-wordindexed result (+ index sb!vm:vector-data-offset)
776                          (pop objects)))
777     result))
778 \f
779 ;;;; symbol magic
780
781 ;;; FIXME: This should be a &KEY argument of ALLOCATE-SYMBOL.
782 (defvar *cold-symbol-allocation-gspace* nil)
783
784 ;;; Allocate (and initialize) a symbol.
785 (defun allocate-symbol (name)
786   (declare (simple-string name))
787   (let ((symbol (allocate-unboxed-object (or *cold-symbol-allocation-gspace*
788                                              *dynamic*)
789                                          sb!vm:n-word-bits
790                                          (1- sb!vm:symbol-size)
791                                          sb!vm:symbol-header-widetag)))
792     (write-wordindexed symbol sb!vm:symbol-value-slot *unbound-marker*)
793     (write-wordindexed symbol
794                        sb!vm:symbol-hash-slot
795                        (make-fixnum-descriptor 0))
796     (write-wordindexed symbol sb!vm:symbol-plist-slot *nil-descriptor*)
797     (write-wordindexed symbol sb!vm:symbol-name-slot
798                        (base-string-to-core name *dynamic*))
799     (write-wordindexed symbol sb!vm:symbol-package-slot *nil-descriptor*)
800     symbol))
801
802 ;;; Set the cold symbol value of SYMBOL-OR-SYMBOL-DES, which can be either a
803 ;;; descriptor of a cold symbol or (in an abbreviation for the
804 ;;; most common usage pattern) an ordinary symbol, which will be
805 ;;; automatically cold-interned.
806 (declaim (ftype (function ((or descriptor symbol) descriptor)) cold-set))
807 (defun cold-set (symbol-or-symbol-des value)
808   (let ((symbol-des (etypecase symbol-or-symbol-des
809                       (descriptor symbol-or-symbol-des)
810                       (symbol (cold-intern symbol-or-symbol-des)))))
811     (write-wordindexed symbol-des sb!vm:symbol-value-slot value)))
812 \f
813 ;;;; layouts and type system pre-initialization
814
815 ;;; Since we want to be able to dump structure constants and
816 ;;; predicates with reference layouts, we need to create layouts at
817 ;;; cold-load time. We use the name to intern layouts by, and dump a
818 ;;; list of all cold layouts in *!INITIAL-LAYOUTS* so that type system
819 ;;; initialization can find them. The only thing that's tricky [sic --
820 ;;; WHN 19990816] is initializing layout's layout, which must point to
821 ;;; itself.
822
823 ;;; a map from class names to lists of
824 ;;;    `(,descriptor ,name ,length ,inherits ,depth)
825 ;;; KLUDGE: It would be more understandable and maintainable to use
826 ;;; DEFSTRUCT (:TYPE LIST) here. -- WHN 19990823
827 (defvar *cold-layouts* (make-hash-table :test 'equal))
828
829 ;;; a map from DESCRIPTOR-BITS of cold layouts to the name, for inverting
830 ;;; mapping
831 (defvar *cold-layout-names* (make-hash-table :test 'eql))
832
833 ;;; FIXME: *COLD-LAYOUTS* and *COLD-LAYOUT-NAMES* should be
834 ;;; initialized by binding in GENESIS.
835
836 ;;; the descriptor for layout's layout (needed when making layouts)
837 (defvar *layout-layout*)
838
839 ;;; FIXME: This information should probably be pulled out of the
840 ;;; cross-compiler's tables at genesis time instead of inserted by
841 ;;; hand here as a bare numeric constant.
842 (defconstant target-layout-length 16)
843
844 ;;; Return a list of names created from the cold layout INHERITS data
845 ;;; in X.
846 (defun listify-cold-inherits (x)
847   (let ((len (descriptor-fixnum (read-wordindexed x
848                                                   sb!vm:vector-length-slot))))
849     (collect ((res))
850       (dotimes (index len)
851         (let* ((des (read-wordindexed x (+ sb!vm:vector-data-offset index)))
852                (found (gethash (descriptor-bits des) *cold-layout-names*)))
853           (if found
854             (res found)
855             (error "unknown descriptor at index ~S (bits = ~8,'0X)"
856                    index
857                    (descriptor-bits des)))))
858       (res))))
859
860 (declaim (ftype (function (symbol descriptor descriptor descriptor) descriptor)
861                 make-cold-layout))
862 (defun make-cold-layout (name length inherits depthoid)
863   (let ((result (allocate-boxed-object *dynamic*
864                                        ;; KLUDGE: Why 1+? -- WHN 19990901
865                                        (1+ target-layout-length)
866                                        sb!vm:instance-pointer-lowtag)))
867     (write-memory result
868                   (make-other-immediate-descriptor
869                    target-layout-length sb!vm:instance-header-widetag))
870
871     ;; KLUDGE: The offsets into LAYOUT below should probably be pulled out
872     ;; of the cross-compiler's tables at genesis time instead of inserted
873     ;; by hand as bare numeric constants. -- WHN ca. 19990901
874
875     ;; Set slot 0 = the layout of the layout.
876     (write-wordindexed result sb!vm:instance-slots-offset *layout-layout*)
877
878     ;; Set the immediately following slots = CLOS hash values.
879     ;;
880     ;; Note: CMU CL didn't set these in genesis, but instead arranged
881     ;; for them to be set at cold init time. That resulted in slightly
882     ;; kludgy-looking code, but there were at least two things to be
883     ;; said for it:
884     ;;   1. It put the hash values under the control of the target Lisp's
885     ;;      RANDOM function, so that CLOS behavior would be nearly
886     ;;      deterministic (instead of depending on the implementation of
887     ;;      RANDOM in the cross-compilation host, and the state of its
888     ;;      RNG when genesis begins).
889     ;;   2. It automatically ensured that all hash values in the target Lisp
890     ;;      were part of the same sequence, so that we didn't have to worry
891     ;;      about the possibility of the first hash value set in genesis
892     ;;      being precisely equal to the some hash value set in cold init time
893     ;;      (because the target Lisp RNG has advanced to precisely the same
894     ;;      state that the host Lisp RNG was in earlier).
895     ;; Point 1 should not be an issue in practice because of the way we do our
896     ;; build procedure in two steps, so that the SBCL that we end up with has
897     ;; been created by another SBCL (whose RNG is under our control).
898     ;; Point 2 is more of an issue. If ANSI had provided a way to feed
899     ;; entropy into an RNG, we would have no problem: we'd just feed
900     ;; some specialized genesis-time-only pattern into the RNG state
901     ;; before using it. However, they didn't, so we have a slight
902     ;; problem. We address it by generating the hash values using a
903     ;; different algorithm than we use in ordinary operation.
904     (dotimes (i sb!kernel:layout-clos-hash-length)
905       (let (;; The expression here is pretty arbitrary, we just want
906             ;; to make sure that it's not something which is (1)
907             ;; evenly distributed and (2) not foreordained to arise in
908             ;; the target Lisp's (RANDOM-LAYOUT-CLOS-HASH) sequence
909             ;; and show up as the CLOS-HASH value of some other
910             ;; LAYOUT.
911             ;;
912             ;; FIXME: This expression here can generate a zero value,
913             ;; and the CMU CL code goes out of its way to generate
914             ;; strictly positive values (even though the field is
915             ;; declared as an INDEX). Check that it's really OK to
916             ;; have zero values in the CLOS-HASH slots.
917             (hash-value (mod (logxor (logand   (random-layout-clos-hash) 15253)
918                                      (logandc2 (random-layout-clos-hash) 15253)
919                                      1)
920                              ;; (The MOD here is defensive programming
921                              ;; to make sure we never write an
922                              ;; out-of-range value even if some joker
923                              ;; sets LAYOUT-CLOS-HASH-MAX to other
924                              ;; than 2^n-1 at some time in the
925                              ;; future.)
926                              (1+ sb!kernel:layout-clos-hash-max))))
927         (write-wordindexed result
928                            (+ i sb!vm:instance-slots-offset 1)
929                            (make-fixnum-descriptor hash-value))))
930
931     ;; Set other slot values.
932     (let ((base (+ sb!vm:instance-slots-offset
933                    sb!kernel:layout-clos-hash-length
934                    1)))
935       ;; (Offset 0 is CLASS, "the class this is a layout for", which
936       ;; is uninitialized at this point.)
937       (write-wordindexed result (+ base 1) *nil-descriptor*) ; marked invalid
938       (write-wordindexed result (+ base 2) inherits)
939       (write-wordindexed result (+ base 3) depthoid)
940       (write-wordindexed result (+ base 4) length)
941       (write-wordindexed result (+ base 5) *nil-descriptor*) ; info
942       (write-wordindexed result (+ base 6) *nil-descriptor*)) ; pure
943
944     (setf (gethash name *cold-layouts*)
945           (list result
946                 name
947                 (descriptor-fixnum length)
948                 (listify-cold-inherits inherits)
949                 (descriptor-fixnum depthoid)))
950     (setf (gethash (descriptor-bits result) *cold-layout-names*) name)
951
952     result))
953
954 (defun initialize-layouts ()
955
956   (clrhash *cold-layouts*)
957
958   ;; We initially create the layout of LAYOUT itself with NIL as the LAYOUT and
959   ;; #() as INHERITS,
960   (setq *layout-layout* *nil-descriptor*)
961   (setq *layout-layout*
962         (make-cold-layout 'layout
963                           (number-to-core target-layout-length)
964                           (vector-in-core)
965                           ;; FIXME: hard-coded LAYOUT-DEPTHOID of LAYOUT..
966                           (number-to-core 4)))
967   (write-wordindexed *layout-layout*
968                      sb!vm:instance-slots-offset
969                      *layout-layout*)
970
971   ;; Then we create the layouts that we'll need to make a correct INHERITS
972   ;; vector for the layout of LAYOUT itself..
973   ;;
974   ;; FIXME: The various LENGTH and DEPTHOID numbers should be taken from
975   ;; the compiler's tables, not set by hand.
976   (let* ((t-layout
977           (make-cold-layout 't
978                             (number-to-core 0)
979                             (vector-in-core)
980                             (number-to-core 0)))
981          (i-layout
982           (make-cold-layout 'instance
983                             (number-to-core 0)
984                             (vector-in-core t-layout)
985                             (number-to-core 1)))
986          (so-layout
987           (make-cold-layout 'structure-object
988                             (number-to-core 1)
989                             (vector-in-core t-layout i-layout)
990                             (number-to-core 2)))
991          (bso-layout
992           (make-cold-layout 'structure!object
993                             (number-to-core 1)
994                             (vector-in-core t-layout i-layout so-layout)
995                             (number-to-core 3)))
996          (layout-inherits (vector-in-core t-layout
997                                           i-layout
998                                           so-layout
999                                           bso-layout)))
1000
1001     ;; ..and return to backpatch the layout of LAYOUT.
1002     (setf (fourth (gethash 'layout *cold-layouts*))
1003           (listify-cold-inherits layout-inherits))
1004     (write-wordindexed *layout-layout*
1005                        ;; FIXME: hardcoded offset into layout struct
1006                        (+ sb!vm:instance-slots-offset
1007                           layout-clos-hash-length
1008                           1
1009                           2)
1010                        layout-inherits)))
1011 \f
1012 ;;;; interning symbols in the cold image
1013
1014 ;;; In order to avoid having to know about the package format, we
1015 ;;; build a data structure in *COLD-PACKAGE-SYMBOLS* that holds all
1016 ;;; interned symbols along with info about their packages. The data
1017 ;;; structure is a list of sublists, where the sublists have the
1018 ;;; following format:
1019 ;;;   (<make-package-arglist>
1020 ;;;    <internal-symbols>
1021 ;;;    <external-symbols>
1022 ;;;    <imported-internal-symbols>
1023 ;;;    <imported-external-symbols>
1024 ;;;    <shadowing-symbols>
1025 ;;;    <package-documentation>)
1026 ;;;
1027 ;;; KLUDGE: It would be nice to implement the sublists as instances of
1028 ;;; a DEFSTRUCT (:TYPE LIST). (They'd still be lists, but at least we'd be
1029 ;;; using mnemonically-named operators to access them, instead of trying
1030 ;;; to remember what THIRD and FIFTH mean, and hoping that we never
1031 ;;; need to change the list layout..) -- WHN 19990825
1032
1033 ;;; an alist from packages to lists of that package's symbols to be dumped
1034 (defvar *cold-package-symbols*)
1035 (declaim (type list *cold-package-symbols*))
1036
1037 ;;; a map from descriptors to symbols, so that we can back up. The key
1038 ;;; is the address in the target core.
1039 (defvar *cold-symbols*)
1040 (declaim (type hash-table *cold-symbols*))
1041
1042 ;;; sanity check for a symbol we're about to create on the target
1043 ;;;
1044 ;;; Make sure that the symbol has an appropriate package. In
1045 ;;; particular, catch the so-easy-to-make error of typing something
1046 ;;; like SB-KERNEL:%BYTE-BLT in cold sources when what you really
1047 ;;; need is SB!KERNEL:%BYTE-BLT.
1048 (defun package-ok-for-target-symbol-p (package)
1049   (let ((package-name (package-name package)))
1050     (or
1051      ;; Cold interning things in these standard packages is OK. (Cold
1052      ;; interning things in the other standard package, CL-USER, isn't
1053      ;; OK. We just use CL-USER to expose symbols whose homes are in
1054      ;; other packages. Thus, trying to cold intern a symbol whose
1055      ;; home package is CL-USER probably means that a coding error has
1056      ;; been made somewhere.)
1057      (find package-name '("COMMON-LISP" "KEYWORD") :test #'string=)
1058      ;; Cold interning something in one of our target-code packages,
1059      ;; which are ever-so-rigorously-and-elegantly distinguished by
1060      ;; this prefix on their names, is OK too.
1061      (string= package-name "SB!" :end1 3 :end2 3)
1062      ;; This one is OK too, since it ends up being COMMON-LISP on the
1063      ;; target.
1064      (string= package-name "SB-XC")
1065      ;; Anything else looks bad. (maybe COMMON-LISP-USER? maybe an extension
1066      ;; package in the xc host? something we can't think of
1067      ;; a valid reason to cold intern, anyway...)
1068      )))
1069   
1070 ;;; like SYMBOL-PACKAGE, but safe for symbols which end up on the target
1071 ;;;
1072 ;;; Most host symbols we dump onto the target are created by SBCL
1073 ;;; itself, so that as long as we avoid gratuitously
1074 ;;; cross-compilation-unfriendly hacks, it just happens that their
1075 ;;; SYMBOL-PACKAGE in the host system corresponds to their
1076 ;;; SYMBOL-PACKAGE in the target system. However, that's not the case
1077 ;;; in the COMMON-LISP package, where we don't get to create the
1078 ;;; symbols but instead have to use the ones that the xc host created.
1079 ;;; In particular, while ANSI specifies which symbols are exported
1080 ;;; from COMMON-LISP, it doesn't specify that their home packages are
1081 ;;; COMMON-LISP, so the xc host can keep them in random packages which
1082 ;;; don't exist on the target (e.g. CLISP keeping some CL-exported
1083 ;;; symbols in the CLOS package).
1084 (defun symbol-package-for-target-symbol (symbol)
1085   ;; We want to catch weird symbols like CLISP's
1086   ;; CL:FIND-METHOD=CLOS::FIND-METHOD, but we don't want to get
1087   ;; sidetracked by ordinary symbols like :CHARACTER which happen to
1088   ;; have the same SYMBOL-NAME as exports from COMMON-LISP.
1089   (multiple-value-bind (cl-symbol cl-status)
1090       (find-symbol (symbol-name symbol) *cl-package*)
1091     (if (and (eq symbol cl-symbol)
1092              (eq cl-status :external))
1093         ;; special case, to work around possible xc host weirdness
1094         ;; in COMMON-LISP package
1095         *cl-package*
1096         ;; ordinary case
1097         (let ((result (symbol-package symbol)))
1098           (aver (package-ok-for-target-symbol-p result))
1099           result))))
1100
1101 ;;; Return a handle on an interned symbol. If necessary allocate the
1102 ;;; symbol and record which package the symbol was referenced in. When
1103 ;;; we allocate the symbol, make sure we record a reference to the
1104 ;;; symbol in the home package so that the package gets set.
1105 (defun cold-intern (symbol
1106                     &optional
1107                     (package (symbol-package-for-target-symbol symbol)))
1108
1109   (aver (package-ok-for-target-symbol-p package))
1110
1111   ;; Anything on the cross-compilation host which refers to the target
1112   ;; machinery through the host SB-XC package should be translated to
1113   ;; something on the target which refers to the same machinery
1114   ;; through the target COMMON-LISP package.
1115   (let ((p (find-package "SB-XC")))
1116     (when (eq package p)
1117       (setf package *cl-package*))
1118     (when (eq (symbol-package symbol) p)
1119       (setf symbol (intern (symbol-name symbol) *cl-package*))))
1120
1121   (let (;; Information about each cold-interned symbol is stored
1122         ;; in COLD-INTERN-INFO.
1123         ;;   (CAR COLD-INTERN-INFO) = descriptor of symbol
1124         ;;   (CDR COLD-INTERN-INFO) = list of packages, other than symbol's
1125         ;;                            own package, referring to symbol
1126         ;; (*COLD-PACKAGE-SYMBOLS* and *COLD-SYMBOLS* store basically the
1127         ;; same information, but with the mapping running the opposite way.)
1128         (cold-intern-info (get symbol 'cold-intern-info)))
1129     (unless cold-intern-info
1130       (cond ((eq (symbol-package-for-target-symbol symbol) package)
1131              (let ((handle (allocate-symbol (symbol-name symbol))))
1132                (setf (gethash (descriptor-bits handle) *cold-symbols*) symbol)
1133                (when (eq package *keyword-package*)
1134                  (cold-set handle handle))
1135                (setq cold-intern-info
1136                      (setf (get symbol 'cold-intern-info) (cons handle nil)))))
1137             (t
1138              (cold-intern symbol)
1139              (setq cold-intern-info (get symbol 'cold-intern-info)))))
1140     (unless (or (null package)
1141                 (member package (cdr cold-intern-info)))
1142       (push package (cdr cold-intern-info))
1143       (let* ((old-cps-entry (assoc package *cold-package-symbols*))
1144              (cps-entry (or old-cps-entry
1145                             (car (push (list package)
1146                                        *cold-package-symbols*)))))
1147         (unless old-cps-entry
1148           (/show "created *COLD-PACKAGE-SYMBOLS* entry for" package symbol))
1149         (push symbol (rest cps-entry))))
1150     (car cold-intern-info)))
1151
1152 ;;; Construct and return a value for use as *NIL-DESCRIPTOR*.
1153 (defun make-nil-descriptor ()
1154   (let* ((des (allocate-unboxed-object
1155                *static*
1156                sb!vm:n-word-bits
1157                sb!vm:symbol-size
1158                0))
1159          (result (make-descriptor (descriptor-high des)
1160                                   (+ (descriptor-low des)
1161                                      (* 2 sb!vm:n-word-bytes)
1162                                      (- sb!vm:list-pointer-lowtag
1163                                         sb!vm:other-pointer-lowtag)))))
1164     (write-wordindexed des
1165                        1
1166                        (make-other-immediate-descriptor
1167                         0
1168                         sb!vm:symbol-header-widetag))
1169     (write-wordindexed des
1170                        (+ 1 sb!vm:symbol-value-slot)
1171                        result)
1172     (write-wordindexed des
1173                        (+ 2 sb!vm:symbol-value-slot)
1174                        result)
1175     (write-wordindexed des
1176                        (+ 1 sb!vm:symbol-plist-slot)
1177                        result)
1178     (write-wordindexed des
1179                        (+ 1 sb!vm:symbol-name-slot)
1180                        ;; This is *DYNAMIC*, and DES is *STATIC*,
1181                        ;; because that's the way CMU CL did it; I'm
1182                        ;; not sure whether there's an underlying
1183                        ;; reason. -- WHN 1990826
1184                        (base-string-to-core "NIL" *dynamic*))
1185     (write-wordindexed des
1186                        (+ 1 sb!vm:symbol-package-slot)
1187                        result)
1188     (setf (get nil 'cold-intern-info)
1189           (cons result nil))
1190     (cold-intern nil)
1191     result))
1192
1193 ;;; Since the initial symbols must be allocated before we can intern
1194 ;;; anything else, we intern those here. We also set the value of T.
1195 (defun initialize-non-nil-symbols ()
1196   #!+sb-doc
1197   "Initialize the cold load symbol-hacking data structures."
1198   (let ((*cold-symbol-allocation-gspace* *static*))
1199     ;; Intern the others.
1200     (dolist (symbol sb!vm:*static-symbols*)
1201       (let* ((des (cold-intern symbol))
1202              (offset-wanted (sb!vm:static-symbol-offset symbol))
1203              (offset-found (- (descriptor-low des)
1204                               (descriptor-low *nil-descriptor*))))
1205         (unless (= offset-wanted offset-found)
1206           ;; FIXME: should be fatal
1207           (warn "Offset from ~S to ~S is ~W, not ~W"
1208                 symbol
1209                 nil
1210                 offset-found
1211                 offset-wanted))))
1212     ;; Establish the value of T.
1213     (let ((t-symbol (cold-intern t)))
1214       (cold-set t-symbol t-symbol))))
1215
1216 ;;; a helper function for FINISH-SYMBOLS: Return a cold alist suitable
1217 ;;; to be stored in *!INITIAL-LAYOUTS*.
1218 (defun cold-list-all-layouts ()
1219   (let ((result *nil-descriptor*))
1220     (maphash (lambda (key stuff)
1221                (cold-push (cold-cons (cold-intern key)
1222                                      (first stuff))
1223                           result))
1224              *cold-layouts*)
1225     result))
1226
1227 ;;; Establish initial values for magic symbols.
1228 ;;;
1229 ;;; Scan over all the symbols referenced in each package in
1230 ;;; *COLD-PACKAGE-SYMBOLS* making that for each one there's an
1231 ;;; appropriate entry in the *!INITIAL-SYMBOLS* data structure to
1232 ;;; intern it.
1233 (defun finish-symbols ()
1234
1235   ;; I think the point of setting these functions into SYMBOL-VALUEs
1236   ;; here, instead of using SYMBOL-FUNCTION, is that in CMU CL
1237   ;; SYMBOL-FUNCTION reduces to FDEFINITION, which is a pretty
1238   ;; hairy operation (involving globaldb.lisp etc.) which we don't
1239   ;; want to invoke early in cold init. -- WHN 2001-12-05
1240   ;;
1241   ;; FIXME: So OK, that's a reasonable reason to do something weird like
1242   ;; this, but this is still a weird thing to do, and we should change
1243   ;; the names to highlight that something weird is going on. Perhaps
1244   ;; *MAYBE-GC-FUN*, *INTERNAL-ERROR-FUN*, *HANDLE-BREAKPOINT-FUN*,
1245   ;; and *HANDLE-FUN-END-BREAKPOINT-FUN*...
1246   (macrolet ((frob (symbol)
1247                `(cold-set ',symbol
1248                           (cold-fdefinition-object (cold-intern ',symbol)))))
1249     (frob sub-gc)
1250     (frob internal-error)
1251     (frob sb!kernel::control-stack-exhausted-error)
1252     (frob sb!kernel::undefined-alien-variable-error)
1253     (frob sb!kernel::undefined-alien-function-error)
1254     (frob sb!kernel::memory-fault-error)
1255     (frob sb!di::handle-breakpoint)
1256     (frob sb!di::handle-fun-end-breakpoint)
1257     (frob sb!thread::handle-thread-exit))
1258
1259   (cold-set 'sb!vm::*current-catch-block*          (make-fixnum-descriptor 0))
1260   (cold-set 'sb!vm::*current-unwind-protect-block* (make-fixnum-descriptor 0))
1261
1262   (cold-set '*free-interrupt-context-index* (make-fixnum-descriptor 0))
1263
1264   (cold-set '*!initial-layouts* (cold-list-all-layouts))
1265
1266   (/show "dumping packages" (mapcar #'car *cold-package-symbols*))
1267   (let ((initial-symbols *nil-descriptor*))
1268     (dolist (cold-package-symbols-entry *cold-package-symbols*)
1269       (let* ((cold-package (car cold-package-symbols-entry))
1270              (symbols (cdr cold-package-symbols-entry))
1271              (shadows (package-shadowing-symbols cold-package))
1272              (documentation (base-string-to-core (documentation cold-package t)))
1273              (internal *nil-descriptor*)
1274              (external *nil-descriptor*)
1275              (imported-internal *nil-descriptor*)
1276              (imported-external *nil-descriptor*)
1277              (shadowing *nil-descriptor*))
1278         (declare (type package cold-package)) ; i.e. not a target descriptor
1279         (/show "dumping" cold-package symbols)
1280
1281         ;; FIXME: Add assertions here to make sure that inappropriate stuff
1282         ;; isn't being dumped:
1283         ;;   * the CL-USER package
1284         ;;   * the SB-COLD package
1285         ;;   * any internal symbols in the CL package
1286         ;;   * basically any package other than CL, KEYWORD, or the packages
1287         ;;     in package-data-list.lisp-expr
1288         ;; and that the structure of the KEYWORD package (e.g. whether
1289         ;; any symbols are internal to it) matches what we want in the
1290         ;; target SBCL.
1291
1292         ;; FIXME: It seems possible that by looking at the contents of
1293         ;; packages in the target SBCL we could find which symbols in
1294         ;; package-data-lisp.lisp-expr are now obsolete. (If I
1295         ;; understand correctly, only symbols which actually have
1296         ;; definitions or which are otherwise referred to actually end
1297         ;; up in the target packages.)
1298
1299         (dolist (symbol symbols)
1300           (let ((handle (car (get symbol 'cold-intern-info)))
1301                 (imported-p (not (eq (symbol-package-for-target-symbol symbol)
1302                                      cold-package))))
1303             (multiple-value-bind (found where)
1304                 (find-symbol (symbol-name symbol) cold-package)
1305               (unless (and where (eq found symbol))
1306                 (error "The symbol ~S is not available in ~S."
1307                        symbol
1308                        cold-package))
1309               (when (memq symbol shadows)
1310                 (cold-push handle shadowing))
1311               (case where
1312                 (:internal (if imported-p
1313                                (cold-push handle imported-internal)
1314                                (cold-push handle internal)))
1315                 (:external (if imported-p
1316                                (cold-push handle imported-external)
1317                                (cold-push handle external)))))))
1318         (let ((r *nil-descriptor*))
1319           (cold-push documentation r)
1320           (cold-push shadowing r)
1321           (cold-push imported-external r)
1322           (cold-push imported-internal r)
1323           (cold-push external r)
1324           (cold-push internal r)
1325           (cold-push (make-make-package-args cold-package) r)
1326           ;; FIXME: It would be more space-efficient to use vectors
1327           ;; instead of lists here, and space-efficiency here would be
1328           ;; nice, since it would reduce the peak memory usage in
1329           ;; genesis and cold init.
1330           (cold-push r initial-symbols))))
1331     (cold-set '*!initial-symbols* initial-symbols))
1332
1333   (cold-set '*!initial-fdefn-objects* (list-all-fdefn-objects))
1334
1335   (cold-set '*!reversed-cold-toplevels* *current-reversed-cold-toplevels*)
1336
1337   #!+(or x86 x86-64)
1338   (progn
1339     (cold-set 'sb!vm::*fp-constant-0d0* (number-to-core 0d0))
1340     (cold-set 'sb!vm::*fp-constant-1d0* (number-to-core 1d0))
1341     (cold-set 'sb!vm::*fp-constant-0f0* (number-to-core 0f0))
1342     (cold-set 'sb!vm::*fp-constant-1f0* (number-to-core 1f0))))
1343
1344 ;;; Make a cold list that can be used as the arg list to MAKE-PACKAGE in order
1345 ;;; to make a package that is similar to PKG.
1346 (defun make-make-package-args (pkg)
1347   (let* ((use *nil-descriptor*)
1348          (cold-nicknames *nil-descriptor*)
1349          (res *nil-descriptor*))
1350     (dolist (u (package-use-list pkg))
1351       (when (assoc u *cold-package-symbols*)
1352         (cold-push (base-string-to-core (package-name u)) use)))
1353     (let* ((pkg-name (package-name pkg))
1354            ;; Make the package nickname lists for the standard packages
1355            ;; be the minimum specified by ANSI, regardless of what value
1356            ;; the cross-compilation host happens to use.
1357            (warm-nicknames (cond ((string= pkg-name "COMMON-LISP")
1358                                   '("CL"))
1359                                  ((string= pkg-name "COMMON-LISP-USER")
1360                                   '("CL-USER"))
1361                                  ((string= pkg-name "KEYWORD")
1362                                   '())
1363                                  ;; For packages other than the
1364                                  ;; standard packages, the nickname
1365                                  ;; list was specified by our package
1366                                  ;; setup code, not by properties of
1367                                  ;; what cross-compilation host we
1368                                  ;; happened to use, and we can just
1369                                  ;; propagate it into the target.
1370                                  (t
1371                                   (package-nicknames pkg)))))
1372       (dolist (warm-nickname warm-nicknames)
1373         (cold-push (base-string-to-core warm-nickname) cold-nicknames)))
1374
1375     (cold-push (number-to-core (truncate (package-internal-symbol-count pkg)
1376                                          0.8))
1377                res)
1378     (cold-push (cold-intern :internal-symbols) res)
1379     (cold-push (number-to-core (truncate (package-external-symbol-count pkg)
1380                                          0.8))
1381                res)
1382     (cold-push (cold-intern :external-symbols) res)
1383
1384     (cold-push cold-nicknames res)
1385     (cold-push (cold-intern :nicknames) res)
1386
1387     (cold-push use res)
1388     (cold-push (cold-intern :use) res)
1389
1390     (cold-push (base-string-to-core (package-name pkg)) res)
1391     res))
1392 \f
1393 ;;;; functions and fdefinition objects
1394
1395 ;;; a hash table mapping from fdefinition names to descriptors of cold
1396 ;;; objects
1397 ;;;
1398 ;;; Note: Since fdefinition names can be lists like '(SETF FOO), and
1399 ;;; we want to have only one entry per name, this must be an 'EQUAL
1400 ;;; hash table, not the default 'EQL.
1401 (defvar *cold-fdefn-objects*)
1402
1403 (defvar *cold-fdefn-gspace* nil)
1404
1405 ;;; Given a cold representation of a symbol, return a warm
1406 ;;; representation. 
1407 (defun warm-symbol (des)
1408   ;; Note that COLD-INTERN is responsible for keeping the
1409   ;; *COLD-SYMBOLS* table up to date, so if DES happens to refer to an
1410   ;; uninterned symbol, the code below will fail. But as long as we
1411   ;; don't need to look up uninterned symbols during bootstrapping,
1412   ;; that's OK..
1413   (multiple-value-bind (symbol found-p)
1414       (gethash (descriptor-bits des) *cold-symbols*)
1415     (declare (type symbol symbol))
1416     (unless found-p
1417       (error "no warm symbol"))
1418     symbol))
1419   
1420 ;;; like CL:CAR, CL:CDR, and CL:NULL but for cold values
1421 (defun cold-car (des)
1422   (aver (= (descriptor-lowtag des) sb!vm:list-pointer-lowtag))
1423   (read-wordindexed des sb!vm:cons-car-slot))
1424 (defun cold-cdr (des)
1425   (aver (= (descriptor-lowtag des) sb!vm:list-pointer-lowtag))
1426   (read-wordindexed des sb!vm:cons-cdr-slot))
1427 (defun cold-null (des)
1428   (= (descriptor-bits des)
1429      (descriptor-bits *nil-descriptor*)))
1430   
1431 ;;; Given a cold representation of a function name, return a warm
1432 ;;; representation.
1433 (declaim (ftype (function (descriptor) (or symbol list)) warm-fun-name))
1434 (defun warm-fun-name (des)
1435   (let ((result
1436          (ecase (descriptor-lowtag des)
1437            (#.sb!vm:list-pointer-lowtag
1438             (aver (not (cold-null des))) ; function named NIL? please no..
1439             ;; Do cold (DESTRUCTURING-BIND (COLD-CAR COLD-CADR) DES ..).
1440             (let* ((car-des (cold-car des))
1441                    (cdr-des (cold-cdr des))
1442                    (cadr-des (cold-car cdr-des))
1443                    (cddr-des (cold-cdr cdr-des)))
1444               (aver (cold-null cddr-des))
1445               (list (warm-symbol car-des)
1446                     (warm-symbol cadr-des))))
1447            (#.sb!vm:other-pointer-lowtag
1448             (warm-symbol des)))))
1449     (legal-fun-name-or-type-error result)
1450     result))
1451
1452 (defun cold-fdefinition-object (cold-name &optional leave-fn-raw)
1453   (declare (type descriptor cold-name))
1454   (/show0 "/cold-fdefinition-object")
1455   (let ((warm-name (warm-fun-name cold-name)))
1456     (or (gethash warm-name *cold-fdefn-objects*)
1457         (let ((fdefn (allocate-boxed-object (or *cold-fdefn-gspace* *dynamic*)
1458                                             (1- sb!vm:fdefn-size)
1459                                             sb!vm:other-pointer-lowtag)))
1460
1461           (setf (gethash warm-name *cold-fdefn-objects*) fdefn)
1462           (write-memory fdefn (make-other-immediate-descriptor
1463                                (1- sb!vm:fdefn-size) sb!vm:fdefn-widetag))
1464           (write-wordindexed fdefn sb!vm:fdefn-name-slot cold-name)
1465           (unless leave-fn-raw
1466             (write-wordindexed fdefn sb!vm:fdefn-fun-slot
1467                                *nil-descriptor*)
1468             (write-wordindexed fdefn
1469                                sb!vm:fdefn-raw-addr-slot
1470                                (make-random-descriptor
1471                                 (cold-foreign-symbol-address-as-integer
1472                                  (sb!vm:extern-alien-name "undefined_tramp")))))
1473           fdefn))))
1474
1475 ;;; Handle the at-cold-init-time, fset-for-static-linkage operation
1476 ;;; requested by FOP-FSET.
1477 (defun static-fset (cold-name defn)
1478   (declare (type descriptor cold-name))
1479   (let ((fdefn (cold-fdefinition-object cold-name t))
1480         (type (logand (descriptor-low (read-memory defn)) sb!vm:widetag-mask)))
1481     (write-wordindexed fdefn sb!vm:fdefn-fun-slot defn)
1482     (write-wordindexed fdefn
1483                        sb!vm:fdefn-raw-addr-slot
1484                        (ecase type
1485                          (#.sb!vm:simple-fun-header-widetag
1486                           (/show0 "static-fset (simple-fun)")
1487                           #!+sparc
1488                           defn
1489                           #!-sparc
1490                           (make-random-descriptor
1491                            (+ (logandc2 (descriptor-bits defn)
1492                                         sb!vm:lowtag-mask)
1493                               (ash sb!vm:simple-fun-code-offset
1494                                    sb!vm:word-shift))))
1495                          (#.sb!vm:closure-header-widetag
1496                           (/show0 "/static-fset (closure)")
1497                           (make-random-descriptor
1498                            (cold-foreign-symbol-address-as-integer
1499                             (sb!vm:extern-alien-name "closure_tramp"))))))
1500     fdefn))
1501
1502 (defun initialize-static-fns ()
1503   (let ((*cold-fdefn-gspace* *static*))
1504     (dolist (sym sb!vm:*static-funs*)
1505       (let* ((fdefn (cold-fdefinition-object (cold-intern sym)))
1506              (offset (- (+ (- (descriptor-low fdefn)
1507                               sb!vm:other-pointer-lowtag)
1508                            (* sb!vm:fdefn-raw-addr-slot sb!vm:n-word-bytes))
1509                         (descriptor-low *nil-descriptor*)))
1510              (desired (sb!vm:static-fun-offset sym)))
1511         (unless (= offset desired)
1512           ;; FIXME: should be fatal
1513           (error "Offset from FDEFN ~S to ~S is ~W, not ~W."
1514                  sym nil offset desired))))))
1515
1516 (defun list-all-fdefn-objects ()
1517   (let ((result *nil-descriptor*))
1518     (maphash (lambda (key value)
1519                (declare (ignore key))
1520                (cold-push value result))
1521              *cold-fdefn-objects*)
1522     result))
1523 \f
1524 ;;;; fixups and related stuff
1525
1526 ;;; an EQUAL hash table
1527 (defvar *cold-foreign-symbol-table*)
1528 (declaim (type hash-table *cold-foreign-symbol-table*))
1529
1530 ;; Read the sbcl.nm file to find the addresses for foreign-symbols in
1531 ;; the C runtime.
1532 (defun load-cold-foreign-symbol-table (filename)
1533   (/show "load-cold-foreign-symbol-table" filename)
1534   (with-open-file (file filename)
1535     (loop for line = (read-line file nil nil)
1536           while line do   
1537           ;; UNIX symbol tables might have tabs in them, and tabs are
1538           ;; not in Common Lisp STANDARD-CHAR, so there seems to be no
1539           ;; nice portable way to deal with them within Lisp, alas.
1540           ;; Fortunately, it's easy to use UNIX command line tools like
1541           ;; sed to remove the problem, so it's not too painful for us
1542           ;; to push responsibility for converting tabs to spaces out to
1543           ;; the caller.
1544           ;;
1545           ;; Other non-STANDARD-CHARs are problematic for the same reason.
1546           ;; Make sure that there aren't any..
1547           (let ((ch (find-if (lambda (char)
1548                                (not (typep char 'standard-char)))
1549                              line)))
1550             (when ch
1551               (error "non-STANDARD-CHAR ~S found in foreign symbol table:~%~S"
1552                      ch
1553                      line)))
1554           (setf line (string-trim '(#\space) line))
1555           (let ((p1 (position #\space line :from-end nil))
1556                 (p2 (position #\space line :from-end t)))
1557             (if (not (and p1 p2 (< p1 p2)))
1558                 ;; KLUDGE: It's too messy to try to understand all
1559                 ;; possible output from nm, so we just punt the lines we
1560                 ;; don't recognize. We realize that there's some chance
1561                 ;; that might get us in trouble someday, so we warn
1562                 ;; about it.
1563                 (warn "ignoring unrecognized line ~S in ~A" line filename)
1564                 (multiple-value-bind (value name)
1565                     (if (string= "0x" line :end2 2)
1566                         (values (parse-integer line :start 2 :end p1 :radix 16)
1567                                 (subseq line (1+ p2)))
1568                         (values (parse-integer line :end p1 :radix 16)
1569                                 (subseq line (1+ p2))))
1570                   (multiple-value-bind (old-value found)
1571                       (gethash name *cold-foreign-symbol-table*)
1572                     (when (and found
1573                                (not (= old-value value)))
1574                       (warn "redefining ~S from #X~X to #X~X"
1575                             name old-value value)))
1576                   (/show "adding to *cold-foreign-symbol-table*:" name value)
1577                   (setf (gethash name *cold-foreign-symbol-table*) value))))))
1578   (values))     ;; PROGN
1579
1580 (defun cold-foreign-symbol-address-as-integer (name)
1581   (or (find-foreign-symbol-in-table name *cold-foreign-symbol-table*)
1582       *foreign-symbol-placeholder-value*
1583       (progn
1584         (format *error-output* "~&The foreign symbol table is:~%")
1585         (maphash (lambda (k v)
1586                    (format *error-output* "~&~S = #X~8X~%" k v))
1587                  *cold-foreign-symbol-table*)
1588         (error "The foreign symbol ~S is undefined." name))))
1589
1590 (defvar *cold-assembler-routines*)
1591
1592 (defvar *cold-assembler-fixups*)
1593
1594 (defun record-cold-assembler-routine (name address)
1595   (/xhow "in RECORD-COLD-ASSEMBLER-ROUTINE" name address)
1596   (push (cons name address)
1597         *cold-assembler-routines*))
1598
1599 (defun record-cold-assembler-fixup (routine
1600                                     code-object
1601                                     offset
1602                                     &optional
1603                                     (kind :both))
1604   (push (list routine code-object offset kind)
1605         *cold-assembler-fixups*))
1606
1607 (defun lookup-assembler-reference (symbol)
1608   (let ((value (cdr (assoc symbol *cold-assembler-routines*))))
1609     ;; FIXME: Should this be ERROR instead of WARN?
1610     (unless value
1611       (warn "Assembler routine ~S not defined." symbol))
1612     value))
1613
1614 ;;; The x86 port needs to store code fixups along with code objects if
1615 ;;; they are to be moved, so fixups for code objects in the dynamic
1616 ;;; heap need to be noted.
1617 #!+(or x86 x86-64)
1618 (defvar *load-time-code-fixups*)
1619
1620 #!+(or x86 x86-64)
1621 (defun note-load-time-code-fixup (code-object offset value kind)
1622   ;; If CODE-OBJECT might be moved
1623   (when (= (gspace-identifier (descriptor-intuit-gspace code-object))
1624            dynamic-core-space-id)
1625     ;; FIXME: pushed thing should be a structure, not just a list
1626     (push (list code-object offset value kind) *load-time-code-fixups*))
1627   (values))
1628
1629 #!+(or x86 x86-64)
1630 (defun output-load-time-code-fixups ()
1631   (dolist (fixups *load-time-code-fixups*)
1632     (let ((code-object (first fixups))
1633           (offset (second fixups))
1634           (value (third fixups))
1635           (kind (fourth fixups)))
1636       (cold-push (cold-cons
1637                   (cold-intern :load-time-code-fixup)
1638                   (cold-cons
1639                    code-object
1640                    (cold-cons
1641                     (number-to-core offset)
1642                     (cold-cons
1643                      (number-to-core value)
1644                      (cold-cons
1645                       (cold-intern kind)
1646                       *nil-descriptor*)))))
1647                  *current-reversed-cold-toplevels*))))
1648
1649 ;;; Given a pointer to a code object and an offset relative to the
1650 ;;; tail of the code object's header, return an offset relative to the
1651 ;;; (beginning of the) code object.
1652 ;;;
1653 ;;; FIXME: It might be clearer to reexpress
1654 ;;;    (LET ((X (CALC-OFFSET CODE-OBJECT OFFSET0))) ..)
1655 ;;; as
1656 ;;;    (LET ((X (+ OFFSET0 (CODE-OBJECT-HEADER-N-BYTES CODE-OBJECT)))) ..).
1657 (declaim (ftype (function (descriptor sb!vm:word)) calc-offset))
1658 (defun calc-offset (code-object offset-from-tail-of-header)
1659   (let* ((header (read-memory code-object))
1660          (header-n-words (ash (descriptor-bits header)
1661                               (- sb!vm:n-widetag-bits)))
1662          (header-n-bytes (ash header-n-words sb!vm:word-shift))
1663          (result (+ offset-from-tail-of-header header-n-bytes)))
1664     result))
1665
1666 (declaim (ftype (function (descriptor sb!vm:word sb!vm:word keyword))
1667                 do-cold-fixup))
1668 (defun do-cold-fixup (code-object after-header value kind)
1669   (let* ((offset-within-code-object (calc-offset code-object after-header))
1670          (gspace-bytes (descriptor-bytes code-object))
1671          (gspace-byte-offset (+ (descriptor-byte-offset code-object)
1672                                 offset-within-code-object))
1673          (gspace-byte-address (gspace-byte-address
1674                                (descriptor-gspace code-object))))
1675     (ecase +backend-fasl-file-implementation+
1676       ;; See CMU CL source for other formerly-supported architectures
1677       ;; (and note that you have to rewrite them to use BVREF-X
1678       ;; instead of SAP-REF).
1679       (:alpha
1680          (ecase kind
1681          (:jmp-hint
1682           (assert (zerop (ldb (byte 2 0) value))))
1683          (:bits-63-48
1684           (let* ((value (if (logbitp 15 value) (+ value (ash 1 16)) value))
1685                  (value (if (logbitp 31 value) (+ value (ash 1 32)) value))
1686                  (value (if (logbitp 47 value) (+ value (ash 1 48)) value)))
1687             (setf (bvref-8 gspace-bytes gspace-byte-offset)
1688                   (ldb (byte 8 48) value)
1689                   (bvref-8 gspace-bytes (1+ gspace-byte-offset))
1690                   (ldb (byte 8 56) value))))
1691          (:bits-47-32
1692           (let* ((value (if (logbitp 15 value) (+ value (ash 1 16)) value))
1693                  (value (if (logbitp 31 value) (+ value (ash 1 32)) value)))
1694             (setf (bvref-8 gspace-bytes gspace-byte-offset)
1695                   (ldb (byte 8 32) value)
1696                   (bvref-8 gspace-bytes (1+ gspace-byte-offset))
1697                   (ldb (byte 8 40) value))))
1698          (:ldah
1699           (let ((value (if (logbitp 15 value) (+ value (ash 1 16)) value)))
1700             (setf (bvref-8 gspace-bytes gspace-byte-offset)
1701                   (ldb (byte 8 16) value)
1702                   (bvref-8 gspace-bytes (1+ gspace-byte-offset))
1703                   (ldb (byte 8 24) value))))
1704          (:lda
1705           (setf (bvref-8 gspace-bytes gspace-byte-offset)
1706                 (ldb (byte 8 0) value)
1707                 (bvref-8 gspace-bytes (1+ gspace-byte-offset))
1708                 (ldb (byte 8 8) value)))))
1709       (:hppa
1710        (ecase kind
1711          (:load
1712           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1713                 (logior (ash (ldb (byte 11 0) value) 1)
1714                         (logand (bvref-32 gspace-bytes gspace-byte-offset) 
1715                                 #xffffc000))))
1716          (:load-short
1717           (let ((low-bits (ldb (byte 11 0) value)))
1718             (assert (<= 0 low-bits (1- (ash 1 4))))
1719             (setf (bvref-32 gspace-bytes gspace-byte-offset)
1720                   (logior (ash low-bits 17)
1721                           (logand (bvref-32 gspace-bytes gspace-byte-offset)
1722                                   #xffe0ffff)))))
1723          (:hi
1724           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1725                 (logior (ash (ldb (byte 5 13) value) 16)
1726                         (ash (ldb (byte 2 18) value) 14)
1727                         (ash (ldb (byte 2 11) value) 12)
1728                         (ash (ldb (byte 11 20) value) 1)
1729                         (ldb (byte 1 31) value)
1730                         (logand (bvref-32 gspace-bytes gspace-byte-offset)
1731                                 #xffe00000))))
1732          (:branch
1733           (let ((bits (ldb (byte 9 2) value)))
1734             (assert (zerop (ldb (byte 2 0) value)))
1735             (setf (bvref-32 gspace-bytes gspace-byte-offset)
1736                   (logior (ash bits 3)
1737                           (logand (bvref-32 gspace-bytes gspace-byte-offset)
1738                                   #xffe0e002)))))))
1739       (:mips
1740        (ecase kind
1741          (:jump
1742           (assert (zerop (ash value -28)))
1743           (setf (ldb (byte 26 0) 
1744                      (bvref-32 gspace-bytes gspace-byte-offset))
1745                 (ash value -2)))
1746          (:lui
1747           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1748                 (logior (mask-field (byte 16 16)
1749                                     (bvref-32 gspace-bytes gspace-byte-offset))
1750                         (+ (ash value -16)
1751                            (if (logbitp 15 value) 1 0)))))
1752          (:addi
1753           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1754                 (logior (mask-field (byte 16 16)
1755                                     (bvref-32 gspace-bytes gspace-byte-offset))
1756                         (ldb (byte 16 0) value))))))
1757        (:ppc
1758        (ecase kind
1759          (:ba
1760           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1761                 (dpb (ash value -2) (byte 24 2) 
1762                      (bvref-32 gspace-bytes gspace-byte-offset))))
1763          (:ha
1764           (let* ((h (ldb (byte 16 16) value))
1765                  (l (ldb (byte 16 0) value)))
1766             (setf (bvref-16 gspace-bytes (+ gspace-byte-offset 2))
1767                   (if (logbitp 15 l) (ldb (byte 16 0) (1+ h)) h))))
1768          (:l
1769           (setf (bvref-16 gspace-bytes (+ gspace-byte-offset 2))
1770                 (ldb (byte 16 0) value)))))     
1771       (:sparc
1772        (ecase kind
1773          (:call
1774           (error "can't deal with call fixups yet"))
1775          (:sethi
1776           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1777                 (dpb (ldb (byte 22 10) value)
1778                      (byte 22 0)
1779                      (bvref-32 gspace-bytes gspace-byte-offset))))
1780          (:add
1781           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1782                 (dpb (ldb (byte 10 0) value)
1783                      (byte 10 0)
1784                      (bvref-32 gspace-bytes gspace-byte-offset))))))
1785       ((:x86 :x86-64)
1786        (let* ((un-fixed-up (bvref-word gspace-bytes
1787                                                gspace-byte-offset))
1788               (code-object-start-addr (logandc2 (descriptor-bits code-object)
1789                                                 sb!vm:lowtag-mask)))
1790          (assert (= code-object-start-addr
1791                   (+ gspace-byte-address
1792                      (descriptor-byte-offset code-object))))
1793          (ecase kind
1794            (:absolute
1795             (let ((fixed-up (+ value un-fixed-up)))
1796               (setf (bvref-32 gspace-bytes gspace-byte-offset)
1797                     fixed-up)
1798               ;; comment from CMU CL sources:
1799               ;;
1800               ;; Note absolute fixups that point within the object.
1801               ;; KLUDGE: There seems to be an implicit assumption in
1802               ;; the old CMU CL code here, that if it doesn't point
1803               ;; before the object, it must point within the object
1804               ;; (not beyond it). It would be good to add an
1805               ;; explanation of why that's true, or an assertion that
1806               ;; it's really true, or both.
1807               (unless (< fixed-up code-object-start-addr)
1808                 (note-load-time-code-fixup code-object
1809                                            after-header
1810                                            value
1811                                            kind))))
1812            (:relative ; (used for arguments to X86 relative CALL instruction)
1813             (let ((fixed-up (- (+ value un-fixed-up)
1814                                gspace-byte-address
1815                                gspace-byte-offset
1816                                4))) ; "length of CALL argument"
1817               (setf (bvref-32 gspace-bytes gspace-byte-offset)
1818                     fixed-up)
1819               ;; Note relative fixups that point outside the code
1820               ;; object, which is to say all relative fixups, since
1821               ;; relative addressing within a code object never needs
1822               ;; a fixup.
1823               (note-load-time-code-fixup code-object
1824                                          after-header
1825                                          value
1826                                          kind))))))))
1827   (values))
1828
1829 (defun resolve-assembler-fixups ()
1830   (dolist (fixup *cold-assembler-fixups*)
1831     (let* ((routine (car fixup))
1832            (value (lookup-assembler-reference routine)))
1833       (when value
1834         (do-cold-fixup (second fixup) (third fixup) value (fourth fixup))))))
1835
1836 ;;; *COLD-FOREIGN-SYMBOL-TABLE* becomes *!INITIAL-FOREIGN-SYMBOLS* in
1837 ;;; the core. When the core is loaded, !LOADER-COLD-INIT uses this to
1838 ;;; create *STATIC-FOREIGN-SYMBOLS*, which the code in
1839 ;;; target-load.lisp refers to.
1840 (defun foreign-symbols-to-core ()
1841   (let ((result *nil-descriptor*))
1842     (maphash (lambda (symbol value)
1843                (cold-push (cold-cons (base-string-to-core symbol)
1844                                      (number-to-core value))
1845                           result))
1846              *cold-foreign-symbol-table*)
1847     (cold-set (cold-intern 'sb!kernel:*!initial-foreign-symbols*) result))
1848   (let ((result *nil-descriptor*))
1849     (dolist (rtn *cold-assembler-routines*)
1850       (cold-push (cold-cons (cold-intern (car rtn))
1851                             (number-to-core (cdr rtn)))
1852                  result))
1853     (cold-set (cold-intern '*!initial-assembler-routines*) result)))
1854
1855 \f
1856 ;;;; general machinery for cold-loading FASL files
1857
1858 ;;; FOP functions for cold loading
1859 (defvar *cold-fop-funs*
1860   ;; We start out with a copy of the ordinary *FOP-FUNS*. The ones
1861   ;; which aren't appropriate for cold load will be destructively
1862   ;; modified.
1863   (copy-seq *fop-funs*))
1864
1865 (defvar *normal-fop-funs*)
1866
1867 ;;; Cause a fop to have a special definition for cold load.
1868 ;;; 
1869 ;;; This is similar to DEFINE-FOP, but unlike DEFINE-FOP, this version
1870 ;;;   (1) looks up the code for this name (created by a previous
1871 ;;        DEFINE-FOP) instead of creating a code, and
1872 ;;;   (2) stores its definition in the *COLD-FOP-FUNS* vector,
1873 ;;;       instead of storing in the *FOP-FUNS* vector.
1874 (defmacro define-cold-fop ((name &key (pushp t) (stackp t)) &rest forms)
1875   (aver (member pushp '(nil t)))
1876   (aver (member stackp '(nil t)))
1877   (let ((code (get name 'fop-code))
1878         (fname (symbolicate "COLD-" name)))
1879     (unless code
1880       (error "~S is not a defined FOP." name))
1881     `(progn
1882        (defun ,fname ()
1883          ,@(if stackp
1884                `((with-fop-stack ,pushp ,@forms))
1885                forms))
1886        (setf (svref *cold-fop-funs* ,code) #',fname))))
1887
1888 (defmacro clone-cold-fop ((name &key (pushp t) (stackp t))
1889                           (small-name)
1890                           &rest forms)
1891   (aver (member pushp '(nil t)))
1892   (aver (member stackp '(nil t)))
1893   `(progn
1894     (macrolet ((clone-arg () '(read-word-arg)))
1895       (define-cold-fop (,name :pushp ,pushp :stackp ,stackp) ,@forms))
1896     (macrolet ((clone-arg () '(read-byte-arg)))
1897       (define-cold-fop (,small-name :pushp ,pushp :stackp ,stackp) ,@forms))))
1898
1899 ;;; Cause a fop to be undefined in cold load.
1900 (defmacro not-cold-fop (name)
1901   `(define-cold-fop (,name)
1902      (error "The fop ~S is not supported in cold load." ',name)))
1903
1904 ;;; COLD-LOAD loads stuff into the core image being built by calling
1905 ;;; LOAD-AS-FASL with the fop function table rebound to a table of cold
1906 ;;; loading functions.
1907 (defun cold-load (filename)
1908   #!+sb-doc
1909   "Load the file named by FILENAME into the cold load image being built."
1910   (let* ((*normal-fop-funs* *fop-funs*)
1911          (*fop-funs* *cold-fop-funs*)
1912          (*cold-load-filename* (etypecase filename
1913                                  (string filename)
1914                                  (pathname (namestring filename)))))
1915     (with-open-file (s filename :element-type '(unsigned-byte 8))
1916       (load-as-fasl s nil nil))))
1917 \f
1918 ;;;; miscellaneous cold fops
1919
1920 (define-cold-fop (fop-misc-trap) *unbound-marker*)
1921
1922 (define-cold-fop (fop-short-character)
1923   (make-character-descriptor (read-byte-arg)))
1924
1925 (define-cold-fop (fop-empty-list) *nil-descriptor*)
1926 (define-cold-fop (fop-truth) (cold-intern t))
1927
1928 (define-cold-fop (fop-normal-load :stackp nil)
1929   (setq *fop-funs* *normal-fop-funs*))
1930
1931 (define-fop (fop-maybe-cold-load 82 :stackp nil)
1932   (when *cold-load-filename*
1933     (setq *fop-funs* *cold-fop-funs*)))
1934
1935 (define-cold-fop (fop-maybe-cold-load :stackp nil))
1936
1937 (clone-cold-fop (fop-struct)
1938                 (fop-small-struct)
1939   (let* ((size (clone-arg))
1940          (result (allocate-boxed-object *dynamic*
1941                                         (1+ size)
1942                                         sb!vm:instance-pointer-lowtag)))
1943     (write-memory result (make-other-immediate-descriptor
1944                           size sb!vm:instance-header-widetag))
1945     (do ((index (1- size) (1- index)))
1946         ((minusp index))
1947       (declare (fixnum index))
1948       (write-wordindexed result
1949                          (+ index sb!vm:instance-slots-offset)
1950                          (pop-stack)))
1951     result))
1952
1953 (define-cold-fop (fop-layout)
1954   (let* ((length-des (pop-stack))
1955          (depthoid-des (pop-stack))
1956          (cold-inherits (pop-stack))
1957          (name (pop-stack))
1958          (old (gethash name *cold-layouts*)))
1959     (declare (type descriptor length-des depthoid-des cold-inherits))
1960     (declare (type symbol name))
1961     ;; If a layout of this name has been defined already
1962     (if old
1963       ;; Enforce consistency between the previous definition and the
1964       ;; current definition, then return the previous definition.
1965       (destructuring-bind
1966           ;; FIXME: This would be more maintainable if we used
1967           ;; DEFSTRUCT (:TYPE LIST) to define COLD-LAYOUT. -- WHN 19990825
1968           (old-layout-descriptor
1969            old-name
1970            old-length
1971            old-inherits-list
1972            old-depthoid)
1973           old
1974         (declare (type descriptor old-layout-descriptor))
1975         (declare (type index old-length))
1976         (declare (type fixnum old-depthoid))
1977         (declare (type list old-inherits-list))
1978         (aver (eq name old-name))
1979         (let ((length (descriptor-fixnum length-des))
1980               (inherits-list (listify-cold-inherits cold-inherits))
1981               (depthoid (descriptor-fixnum depthoid-des)))
1982           (unless (= length old-length)
1983             (error "cold loading a reference to class ~S when the compile~%~
1984                     time length was ~S and current length is ~S"
1985                    name
1986                    length
1987                    old-length))
1988           (unless (equal inherits-list old-inherits-list)
1989             (error "cold loading a reference to class ~S when the compile~%~
1990                     time inherits were ~S~%~
1991                     and current inherits are ~S"
1992                    name
1993                    inherits-list
1994                    old-inherits-list))
1995           (unless (= depthoid old-depthoid)
1996             (error "cold loading a reference to class ~S when the compile~%~
1997                     time inheritance depthoid was ~S and current inheritance~%~
1998                     depthoid is ~S"
1999                    name
2000                    depthoid
2001                    old-depthoid)))
2002         old-layout-descriptor)
2003       ;; Make a new definition from scratch.
2004       (make-cold-layout name length-des cold-inherits depthoid-des))))
2005 \f
2006 ;;;; cold fops for loading symbols
2007
2008 ;;; Load a symbol SIZE characters long from *FASL-INPUT-STREAM* and
2009 ;;; intern that symbol in PACKAGE.
2010 (defun cold-load-symbol (size package)
2011   (let ((string (make-string size)))
2012     (read-string-as-bytes *fasl-input-stream* string)
2013     (cold-intern (intern string package))))
2014
2015 (macrolet ((frob (name pname-len package-len)
2016              `(define-cold-fop (,name)
2017                 (let ((index (read-arg ,package-len)))
2018                   (push-fop-table
2019                    (cold-load-symbol (read-arg ,pname-len)
2020                                      (svref *current-fop-table* index)))))))
2021   (frob fop-symbol-in-package-save #.sb!vm:n-word-bytes #.sb!vm:n-word-bytes)
2022   (frob fop-small-symbol-in-package-save 1 #.sb!vm:n-word-bytes)
2023   (frob fop-symbol-in-byte-package-save #.sb!vm:n-word-bytes 1)
2024   (frob fop-small-symbol-in-byte-package-save 1 1))
2025
2026 (clone-cold-fop (fop-lisp-symbol-save)
2027                 (fop-lisp-small-symbol-save)
2028   (push-fop-table (cold-load-symbol (clone-arg) *cl-package*)))
2029
2030 (clone-cold-fop (fop-keyword-symbol-save)
2031                 (fop-keyword-small-symbol-save)
2032   (push-fop-table (cold-load-symbol (clone-arg) *keyword-package*)))
2033
2034 (clone-cold-fop (fop-uninterned-symbol-save)
2035                 (fop-uninterned-small-symbol-save)
2036   (let* ((size (clone-arg))
2037          (name (make-string size)))
2038     (read-string-as-bytes *fasl-input-stream* name)
2039     (let ((symbol-des (allocate-symbol name)))
2040       (push-fop-table symbol-des))))
2041 \f
2042 ;;;; cold fops for loading lists
2043
2044 ;;; Make a list of the top LENGTH things on the fop stack. The last
2045 ;;; cdr of the list is set to LAST.
2046 (defmacro cold-stack-list (length last)
2047   `(do* ((index ,length (1- index))
2048          (result ,last (cold-cons (pop-stack) result)))
2049         ((= index 0) result)
2050      (declare (fixnum index))))
2051
2052 (define-cold-fop (fop-list)
2053   (cold-stack-list (read-byte-arg) *nil-descriptor*))
2054 (define-cold-fop (fop-list*)
2055   (cold-stack-list (read-byte-arg) (pop-stack)))
2056 (define-cold-fop (fop-list-1)
2057   (cold-stack-list 1 *nil-descriptor*))
2058 (define-cold-fop (fop-list-2)
2059   (cold-stack-list 2 *nil-descriptor*))
2060 (define-cold-fop (fop-list-3)
2061   (cold-stack-list 3 *nil-descriptor*))
2062 (define-cold-fop (fop-list-4)
2063   (cold-stack-list 4 *nil-descriptor*))
2064 (define-cold-fop (fop-list-5)
2065   (cold-stack-list 5 *nil-descriptor*))
2066 (define-cold-fop (fop-list-6)
2067   (cold-stack-list 6 *nil-descriptor*))
2068 (define-cold-fop (fop-list-7)
2069   (cold-stack-list 7 *nil-descriptor*))
2070 (define-cold-fop (fop-list-8)
2071   (cold-stack-list 8 *nil-descriptor*))
2072 (define-cold-fop (fop-list*-1)
2073   (cold-stack-list 1 (pop-stack)))
2074 (define-cold-fop (fop-list*-2)
2075   (cold-stack-list 2 (pop-stack)))
2076 (define-cold-fop (fop-list*-3)
2077   (cold-stack-list 3 (pop-stack)))
2078 (define-cold-fop (fop-list*-4)
2079   (cold-stack-list 4 (pop-stack)))
2080 (define-cold-fop (fop-list*-5)
2081   (cold-stack-list 5 (pop-stack)))
2082 (define-cold-fop (fop-list*-6)
2083   (cold-stack-list 6 (pop-stack)))
2084 (define-cold-fop (fop-list*-7)
2085   (cold-stack-list 7 (pop-stack)))
2086 (define-cold-fop (fop-list*-8)
2087   (cold-stack-list 8 (pop-stack)))
2088 \f
2089 ;;;; cold fops for loading vectors
2090
2091 (clone-cold-fop (fop-base-string)
2092                 (fop-small-base-string)
2093   (let* ((len (clone-arg))
2094          (string (make-string len)))
2095     (read-string-as-bytes *fasl-input-stream* string)
2096     (base-string-to-core string)))
2097
2098 #!+sb-unicode
2099 (clone-cold-fop (fop-character-string)
2100                 (fop-small-character-string)
2101   (bug "CHARACTER-STRING dumped by cross-compiler."))
2102
2103 (clone-cold-fop (fop-vector)
2104                 (fop-small-vector)
2105   (let* ((size (clone-arg))
2106          (result (allocate-vector-object *dynamic*
2107                                          sb!vm:n-word-bits
2108                                          size
2109                                          sb!vm:simple-vector-widetag)))
2110     (do ((index (1- size) (1- index)))
2111         ((minusp index))
2112       (declare (fixnum index))
2113       (write-wordindexed result
2114                          (+ index sb!vm:vector-data-offset)
2115                          (pop-stack)))
2116     result))
2117
2118 (define-cold-fop (fop-int-vector)
2119   (let* ((len (read-word-arg))
2120          (sizebits (read-byte-arg))
2121          (type (case sizebits
2122                  (0 sb!vm:simple-array-nil-widetag)
2123                  (1 sb!vm:simple-bit-vector-widetag)
2124                  (2 sb!vm:simple-array-unsigned-byte-2-widetag)
2125                  (4 sb!vm:simple-array-unsigned-byte-4-widetag)
2126                  (7 (prog1 sb!vm:simple-array-unsigned-byte-7-widetag
2127                       (setf sizebits 8)))
2128                  (8 sb!vm:simple-array-unsigned-byte-8-widetag)
2129                  (15 (prog1 sb!vm:simple-array-unsigned-byte-15-widetag
2130                        (setf sizebits 16)))
2131                  (16 sb!vm:simple-array-unsigned-byte-16-widetag)
2132                  (31 (prog1 sb!vm:simple-array-unsigned-byte-31-widetag
2133                        (setf sizebits 32)))
2134                  (32 sb!vm:simple-array-unsigned-byte-32-widetag)
2135                  #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
2136                  (63 (prog1 sb!vm:simple-array-unsigned-byte-63-widetag
2137                        (setf sizebits 64)))
2138                  #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
2139                  (64 sb!vm:simple-array-unsigned-byte-64-widetag)
2140                  (t (error "losing element size: ~W" sizebits))))
2141          (result (allocate-vector-object *dynamic* sizebits len type))
2142          (start (+ (descriptor-byte-offset result)
2143                    (ash sb!vm:vector-data-offset sb!vm:word-shift)))
2144          (end (+ start
2145                  (ceiling (* len sizebits)
2146                           sb!vm:n-byte-bits))))
2147     (read-bigvec-as-sequence-or-die (descriptor-bytes result)
2148                                     *fasl-input-stream*
2149                                     :start start
2150                                     :end end)
2151     result))
2152
2153 (define-cold-fop (fop-single-float-vector)
2154   (let* ((len (read-word-arg))
2155          (result (allocate-vector-object
2156                   *dynamic*
2157                   sb!vm:n-word-bits
2158                   len
2159                   sb!vm:simple-array-single-float-widetag))
2160          (start (+ (descriptor-byte-offset result)
2161                    (ash sb!vm:vector-data-offset sb!vm:word-shift)))
2162          (end (+ start (* len 4))))
2163     (read-bigvec-as-sequence-or-die (descriptor-bytes result)
2164                                     *fasl-input-stream*
2165                                     :start start
2166                                     :end end)
2167     result))
2168
2169 (not-cold-fop fop-double-float-vector)
2170 #!+long-float (not-cold-fop fop-long-float-vector)
2171 (not-cold-fop fop-complex-single-float-vector)
2172 (not-cold-fop fop-complex-double-float-vector)
2173 #!+long-float (not-cold-fop fop-complex-long-float-vector)
2174
2175 (define-cold-fop (fop-array)
2176   (let* ((rank (read-word-arg))
2177          (data-vector (pop-stack))
2178          (result (allocate-boxed-object *dynamic*
2179                                         (+ sb!vm:array-dimensions-offset rank)
2180                                         sb!vm:other-pointer-lowtag)))
2181     (write-memory result
2182                   (make-other-immediate-descriptor rank
2183                                                    sb!vm:simple-array-widetag))
2184     (write-wordindexed result sb!vm:array-fill-pointer-slot *nil-descriptor*)
2185     (write-wordindexed result sb!vm:array-data-slot data-vector)
2186     (write-wordindexed result sb!vm:array-displacement-slot *nil-descriptor*)
2187     (write-wordindexed result sb!vm:array-displaced-p-slot *nil-descriptor*)
2188     (let ((total-elements 1))
2189       (dotimes (axis rank)
2190         (let ((dim (pop-stack)))
2191           (unless (or (= (descriptor-lowtag dim) sb!vm:even-fixnum-lowtag)
2192                       (= (descriptor-lowtag dim) sb!vm:odd-fixnum-lowtag))
2193             (error "non-fixnum dimension? (~S)" dim))
2194           (setf total-elements
2195                 (* total-elements
2196                    (logior (ash (descriptor-high dim)
2197                                 (- descriptor-low-bits
2198                                    (1- sb!vm:n-lowtag-bits)))
2199                            (ash (descriptor-low dim)
2200                                 (- 1 sb!vm:n-lowtag-bits)))))
2201           (write-wordindexed result
2202                              (+ sb!vm:array-dimensions-offset axis)
2203                              dim)))
2204       (write-wordindexed result
2205                          sb!vm:array-elements-slot
2206                          (make-fixnum-descriptor total-elements)))
2207     result))
2208
2209 \f
2210 ;;;; cold fops for loading numbers
2211
2212 (defmacro define-cold-number-fop (fop)
2213   `(define-cold-fop (,fop :stackp nil)
2214      ;; Invoke the ordinary warm version of this fop to push the
2215      ;; number.
2216      (,fop)
2217      ;; Replace the warm fop result with the cold image of the warm
2218      ;; fop result.
2219      (with-fop-stack t
2220        (let ((number (pop-stack)))
2221          (number-to-core number)))))
2222
2223 (define-cold-number-fop fop-single-float)
2224 (define-cold-number-fop fop-double-float)
2225 (define-cold-number-fop fop-integer)
2226 (define-cold-number-fop fop-small-integer)
2227 (define-cold-number-fop fop-word-integer)
2228 (define-cold-number-fop fop-byte-integer)
2229 (define-cold-number-fop fop-complex-single-float)
2230 (define-cold-number-fop fop-complex-double-float)
2231
2232 (define-cold-fop (fop-ratio)
2233   (let ((den (pop-stack)))
2234     (number-pair-to-core (pop-stack) den sb!vm:ratio-widetag)))
2235
2236 (define-cold-fop (fop-complex)
2237   (let ((im (pop-stack)))
2238     (number-pair-to-core (pop-stack) im sb!vm:complex-widetag)))
2239 \f
2240 ;;;; cold fops for calling (or not calling)
2241
2242 (not-cold-fop fop-eval)
2243 (not-cold-fop fop-eval-for-effect)
2244
2245 (defvar *load-time-value-counter*)
2246
2247 (define-cold-fop (fop-funcall)
2248   (unless (= (read-byte-arg) 0)
2249     (error "You can't FOP-FUNCALL arbitrary stuff in cold load."))
2250   (let ((counter *load-time-value-counter*))
2251     (cold-push (cold-cons
2252                 (cold-intern :load-time-value)
2253                 (cold-cons
2254                  (pop-stack)
2255                  (cold-cons
2256                   (number-to-core counter)
2257                   *nil-descriptor*)))
2258                *current-reversed-cold-toplevels*)
2259     (setf *load-time-value-counter* (1+ counter))
2260     (make-descriptor 0 0 nil counter)))
2261
2262 (defun finalize-load-time-value-noise ()
2263   (cold-set (cold-intern '*!load-time-values*)
2264             (allocate-vector-object *dynamic*
2265                                     sb!vm:n-word-bits
2266                                     *load-time-value-counter*
2267                                     sb!vm:simple-vector-widetag)))
2268
2269 (define-cold-fop (fop-funcall-for-effect :pushp nil)
2270   (if (= (read-byte-arg) 0)
2271       (cold-push (pop-stack)
2272                  *current-reversed-cold-toplevels*)
2273       (error "You can't FOP-FUNCALL arbitrary stuff in cold load.")))
2274 \f
2275 ;;;; cold fops for fixing up circularities
2276
2277 (define-cold-fop (fop-rplaca :pushp nil)
2278   (let ((obj (svref *current-fop-table* (read-word-arg)))
2279         (idx (read-word-arg)))
2280     (write-memory (cold-nthcdr idx obj) (pop-stack))))
2281
2282 (define-cold-fop (fop-rplacd :pushp nil)
2283   (let ((obj (svref *current-fop-table* (read-word-arg)))
2284         (idx (read-word-arg)))
2285     (write-wordindexed (cold-nthcdr idx obj) 1 (pop-stack))))
2286
2287 (define-cold-fop (fop-svset :pushp nil)
2288   (let ((obj (svref *current-fop-table* (read-word-arg)))
2289         (idx (read-word-arg)))
2290     (write-wordindexed obj
2291                    (+ idx
2292                       (ecase (descriptor-lowtag obj)
2293                         (#.sb!vm:instance-pointer-lowtag 1)
2294                         (#.sb!vm:other-pointer-lowtag 2)))
2295                    (pop-stack))))
2296
2297 (define-cold-fop (fop-structset :pushp nil)
2298   (let ((obj (svref *current-fop-table* (read-word-arg)))
2299         (idx (read-word-arg)))
2300     (write-wordindexed obj (1+ idx) (pop-stack))))
2301
2302 ;;; In the original CMUCL code, this actually explicitly declared PUSHP
2303 ;;; to be T, even though that's what it defaults to in DEFINE-COLD-FOP.
2304 (define-cold-fop (fop-nthcdr)
2305   (cold-nthcdr (read-word-arg) (pop-stack)))
2306
2307 (defun cold-nthcdr (index obj)
2308   (dotimes (i index)
2309     (setq obj (read-wordindexed obj 1)))
2310   obj)
2311 \f
2312 ;;;; cold fops for loading code objects and functions
2313
2314 ;;; the names of things which have had COLD-FSET used on them already
2315 ;;; (used to make sure that we don't try to statically link a name to
2316 ;;; more than one definition)
2317 (defparameter *cold-fset-warm-names*
2318   ;; This can't be an EQL hash table because names can be conses, e.g.
2319   ;; (SETF CAR).
2320   (make-hash-table :test 'equal))
2321
2322 (define-cold-fop (fop-fset :pushp nil)
2323   (let* ((fn (pop-stack))
2324          (cold-name (pop-stack))
2325          (warm-name (warm-fun-name cold-name)))
2326     (if (gethash warm-name *cold-fset-warm-names*)
2327         (error "duplicate COLD-FSET for ~S" warm-name)
2328         (setf (gethash warm-name *cold-fset-warm-names*) t))
2329     (static-fset cold-name fn)))
2330
2331 (define-cold-fop (fop-fdefinition)
2332   (cold-fdefinition-object (pop-stack)))
2333
2334 (define-cold-fop (fop-sanctify-for-execution)
2335   (pop-stack))
2336
2337 ;;; Setting this variable shows what code looks like before any
2338 ;;; fixups (or function headers) are applied.
2339 #!+sb-show (defvar *show-pre-fixup-code-p* nil)
2340
2341 ;;; FIXME: The logic here should be converted into a function
2342 ;;; COLD-CODE-FOP-GUTS (NCONST CODE-SIZE) called by DEFINE-COLD-FOP
2343 ;;; FOP-CODE and DEFINE-COLD-FOP FOP-SMALL-CODE, so that
2344 ;;; variable-capture nastiness like (LET ((NCONST ,NCONST) ..) ..)
2345 ;;; doesn't keep me awake at night.
2346 (defmacro define-cold-code-fop (name nconst code-size)
2347   `(define-cold-fop (,name)
2348      (let* ((nconst ,nconst)
2349             (code-size ,code-size)
2350             (raw-header-n-words (+ sb!vm:code-trace-table-offset-slot nconst))
2351             (header-n-words
2352              ;; Note: we round the number of constants up to ensure
2353              ;; that the code vector will be properly aligned.
2354              (round-up raw-header-n-words 2))
2355             (des (allocate-cold-descriptor *dynamic*
2356                                            (+ (ash header-n-words
2357                                                    sb!vm:word-shift)
2358                                               code-size)
2359                                            sb!vm:other-pointer-lowtag)))
2360        (write-memory des
2361                      (make-other-immediate-descriptor
2362                       header-n-words sb!vm:code-header-widetag))
2363        (write-wordindexed des
2364                           sb!vm:code-code-size-slot
2365                           (make-fixnum-descriptor
2366                            (ash (+ code-size (1- (ash 1 sb!vm:word-shift)))
2367                                 (- sb!vm:word-shift))))
2368        (write-wordindexed des sb!vm:code-entry-points-slot *nil-descriptor*)
2369        (write-wordindexed des sb!vm:code-debug-info-slot (pop-stack))
2370        (when (oddp raw-header-n-words)
2371          (write-wordindexed des
2372                             raw-header-n-words
2373                             (make-random-descriptor 0)))
2374        (do ((index (1- raw-header-n-words) (1- index)))
2375            ((< index sb!vm:code-trace-table-offset-slot))
2376          (write-wordindexed des index (pop-stack)))
2377        (let* ((start (+ (descriptor-byte-offset des)
2378                         (ash header-n-words sb!vm:word-shift)))
2379               (end (+ start code-size)))
2380          (read-bigvec-as-sequence-or-die (descriptor-bytes des)
2381                                          *fasl-input-stream*
2382                                          :start start
2383                                          :end end)
2384          #!+sb-show
2385          (when *show-pre-fixup-code-p*
2386            (format *trace-output*
2387                    "~&/raw code from code-fop ~W ~W:~%"
2388                    nconst
2389                    code-size)
2390            (do ((i start (+ i sb!vm:n-word-bytes)))
2391                ((>= i end))
2392              (format *trace-output*
2393                      "/#X~8,'0x: #X~8,'0x~%"
2394                      (+ i (gspace-byte-address (descriptor-gspace des)))
2395                      (bvref-32 (descriptor-bytes des) i)))))
2396        des)))
2397
2398 (define-cold-code-fop fop-code (read-word-arg) (read-word-arg))
2399
2400 (define-cold-code-fop fop-small-code (read-byte-arg) (read-halfword-arg))
2401
2402 (clone-cold-fop (fop-alter-code :pushp nil)
2403                 (fop-byte-alter-code)
2404   (let ((slot (clone-arg))
2405         (value (pop-stack))
2406         (code (pop-stack)))
2407     (write-wordindexed code slot value)))
2408
2409 (define-cold-fop (fop-fun-entry)
2410   (let* ((type (pop-stack))
2411          (arglist (pop-stack))
2412          (name (pop-stack))
2413          (code-object (pop-stack))
2414          (offset (calc-offset code-object (read-word-arg)))
2415          (fn (descriptor-beyond code-object
2416                                 offset
2417                                 sb!vm:fun-pointer-lowtag))
2418          (next (read-wordindexed code-object sb!vm:code-entry-points-slot)))
2419     (unless (zerop (logand offset sb!vm:lowtag-mask))
2420       (error "unaligned function entry: ~S at #X~X" name offset))
2421     (write-wordindexed code-object sb!vm:code-entry-points-slot fn)
2422     (write-memory fn
2423                   (make-other-immediate-descriptor
2424                    (ash offset (- sb!vm:word-shift))
2425                    sb!vm:simple-fun-header-widetag))
2426     (write-wordindexed fn
2427                        sb!vm:simple-fun-self-slot
2428                        ;; KLUDGE: Wiring decisions like this in at
2429                        ;; this level ("if it's an x86") instead of a
2430                        ;; higher level of abstraction ("if it has such
2431                        ;; and such relocation peculiarities (which
2432                        ;; happen to be confined to the x86)") is bad.
2433                        ;; It would be nice if the code were instead
2434                        ;; conditional on some more descriptive
2435                        ;; feature, :STICKY-CODE or
2436                        ;; :LOAD-GC-INTERACTION or something.
2437                        ;;
2438                        ;; FIXME: The X86 definition of the function
2439                        ;; self slot breaks everything object.tex says
2440                        ;; about it. (As far as I can tell, the X86
2441                        ;; definition makes it a pointer to the actual
2442                        ;; code instead of a pointer back to the object
2443                        ;; itself.) Ask on the mailing list whether
2444                        ;; this is documented somewhere, and if not,
2445                        ;; try to reverse engineer some documentation.
2446                        #!-(or x86 x86-64)
2447                        ;; a pointer back to the function object, as
2448                        ;; described in CMU CL
2449                        ;; src/docs/internals/object.tex
2450                        fn
2451                        #!+(or x86 x86-64)
2452                        ;; KLUDGE: a pointer to the actual code of the
2453                        ;; object, as described nowhere that I can find
2454                        ;; -- WHN 19990907
2455                        (make-random-descriptor
2456                         (+ (descriptor-bits fn)
2457                            (- (ash sb!vm:simple-fun-code-offset
2458                                    sb!vm:word-shift)
2459                               ;; FIXME: We should mask out the type
2460                               ;; bits, not assume we know what they
2461                               ;; are and subtract them out this way.
2462                               sb!vm:fun-pointer-lowtag))))
2463     (write-wordindexed fn sb!vm:simple-fun-next-slot next)
2464     (write-wordindexed fn sb!vm:simple-fun-name-slot name)
2465     (write-wordindexed fn sb!vm:simple-fun-arglist-slot arglist)
2466     (write-wordindexed fn sb!vm:simple-fun-type-slot type)
2467     fn))
2468
2469 (define-cold-fop (fop-foreign-fixup)
2470   (let* ((kind (pop-stack))
2471          (code-object (pop-stack))
2472          (len (read-byte-arg))
2473          (sym (make-string len)))
2474     (read-string-as-bytes *fasl-input-stream* sym)
2475     (let ((offset (read-word-arg))
2476           (value (cold-foreign-symbol-address-as-integer sym)))
2477       (do-cold-fixup code-object offset value kind))
2478    code-object))
2479
2480 #!+linkage-table
2481 (define-cold-fop (fop-foreign-dataref-fixup)
2482   (let* ((kind (pop-stack))
2483          (code-object (pop-stack))
2484          (len (read-byte-arg))
2485          (sym (make-string len)))
2486     (read-string-as-bytes *fasl-input-stream* sym)
2487     (maphash (lambda (k v)
2488                (format *error-output* "~&~S = #X~8X~%" k v))
2489              *cold-foreign-symbol-table*)
2490     (error "shared foreign symbol in cold load: ~S (~S)" sym kind)))
2491
2492 (define-cold-fop (fop-assembler-code)
2493   (let* ((length (read-word-arg))
2494          (header-n-words
2495           ;; Note: we round the number of constants up to ensure that
2496           ;; the code vector will be properly aligned.
2497           (round-up sb!vm:code-constants-offset 2))
2498          (des (allocate-cold-descriptor *read-only*
2499                                         (+ (ash header-n-words
2500                                                 sb!vm:word-shift)
2501                                            length)
2502                                         sb!vm:other-pointer-lowtag)))
2503     (write-memory des
2504                   (make-other-immediate-descriptor
2505                    header-n-words sb!vm:code-header-widetag))
2506     (write-wordindexed des
2507                        sb!vm:code-code-size-slot
2508                        (make-fixnum-descriptor
2509                         (ash (+ length (1- (ash 1 sb!vm:word-shift)))
2510                              (- sb!vm:word-shift))))
2511     (write-wordindexed des sb!vm:code-entry-points-slot *nil-descriptor*)
2512     (write-wordindexed des sb!vm:code-debug-info-slot *nil-descriptor*)
2513
2514     (let* ((start (+ (descriptor-byte-offset des)
2515                      (ash header-n-words sb!vm:word-shift)))
2516            (end (+ start length)))
2517       (read-bigvec-as-sequence-or-die (descriptor-bytes des)
2518                                       *fasl-input-stream*
2519                                       :start start
2520                                       :end end))
2521     des))
2522
2523 (define-cold-fop (fop-assembler-routine)
2524   (let* ((routine (pop-stack))
2525          (des (pop-stack))
2526          (offset (calc-offset des (read-word-arg))))
2527     (record-cold-assembler-routine
2528      routine
2529      (+ (logandc2 (descriptor-bits des) sb!vm:lowtag-mask) offset))
2530     des))
2531
2532 (define-cold-fop (fop-assembler-fixup)
2533   (let* ((routine (pop-stack))
2534          (kind (pop-stack))
2535          (code-object (pop-stack))
2536          (offset (read-word-arg)))
2537     (record-cold-assembler-fixup routine code-object offset kind)
2538     code-object))
2539
2540 (define-cold-fop (fop-code-object-fixup)
2541   (let* ((kind (pop-stack))
2542          (code-object (pop-stack))
2543          (offset (read-word-arg))
2544          (value (descriptor-bits code-object)))
2545     (do-cold-fixup code-object offset value kind)
2546     code-object))
2547 \f
2548 ;;;; emitting C header file
2549
2550 (defun tailwise-equal (string tail)
2551   (and (>= (length string) (length tail))
2552        (string= string tail :start1 (- (length string) (length tail)))))
2553
2554 (defun write-boilerplate ()
2555   (format t "/*~%")
2556   (dolist (line
2557            '("This is a machine-generated file. Please do not edit it by hand."
2558              "(As of sbcl-0.8.14, it came from WRITE-CONFIG-H in genesis.lisp.)"
2559              ""
2560              "This file contains low-level information about the"
2561              "internals of a particular version and configuration"
2562              "of SBCL. It is used by the C compiler to create a runtime"
2563              "support environment, an executable program in the host"
2564              "operating system's native format, which can then be used to"
2565              "load and run 'core' files, which are basically programs"
2566              "in SBCL's own format."))
2567     (format t " * ~A~%" line))
2568   (format t " */~%"))
2569
2570 (defun write-config-h ()
2571   ;; propagating *SHEBANG-FEATURES* into C-level #define's
2572   (dolist (shebang-feature-name (sort (mapcar #'symbol-name
2573                                               sb-cold:*shebang-features*)
2574                                       #'string<))
2575     (format t
2576             "#define LISP_FEATURE_~A~%"
2577             (substitute #\_ #\- shebang-feature-name)))
2578   (terpri)
2579   ;; and miscellaneous constants
2580   (format t "#define SBCL_CORE_VERSION_INTEGER ~D~%" sbcl-core-version-integer)
2581   (format t
2582           "#define SBCL_VERSION_STRING ~S~%"
2583           (sb!xc:lisp-implementation-version))
2584   (format t "#define CORE_MAGIC 0x~X~%" core-magic)
2585   (format t "#ifndef LANGUAGE_ASSEMBLY~2%")
2586   (format t "#define LISPOBJ(x) ((lispobj)x)~2%")
2587   (format t "#else /* LANGUAGE_ASSEMBLY */~2%")
2588   (format t "#define LISPOBJ(thing) thing~2%")
2589   (format t "#endif /* LANGUAGE_ASSEMBLY */~2%")
2590   (terpri))
2591
2592 (defun write-constants-h ()
2593   ;; writing entire families of named constants 
2594   (let ((constants nil))
2595     (dolist (package-name '(;; Even in CMU CL, constants from VM
2596                             ;; were automatically propagated
2597                             ;; into the runtime.
2598                             "SB!VM"
2599                             ;; In SBCL, we also propagate various
2600                             ;; magic numbers related to file format,
2601                             ;; which live here instead of SB!VM.
2602                             "SB!FASL"))
2603       (do-external-symbols (symbol (find-package package-name))
2604         (when (constantp symbol)
2605           (let ((name (symbol-name symbol)))
2606             (labels (;; shared machinery
2607                      (record (string priority)
2608                        (push (list string
2609                                    priority
2610                                    (symbol-value symbol)
2611                                    (documentation symbol 'variable))
2612                              constants))
2613                      ;; machinery for old-style CMU CL Lisp-to-C
2614                      ;; arbitrary renaming, being phased out in favor of
2615                      ;; the newer systematic RECORD-WITH-TRANSLATED-NAME
2616                      ;; renaming
2617                      (record-with-munged-name (prefix string priority)
2618                        (record (concatenate
2619                                 'simple-string
2620                                 prefix
2621                                 (delete #\- (string-capitalize string)))
2622                                priority))
2623                      (maybe-record-with-munged-name (tail prefix priority)
2624                        (when (tailwise-equal name tail)
2625                          (record-with-munged-name prefix
2626                                                   (subseq name 0
2627                                                           (- (length name)
2628                                                              (length tail)))
2629                                                   priority)))
2630                      ;; machinery for new-style SBCL Lisp-to-C naming
2631                      (record-with-translated-name (priority)
2632                        (record (substitute #\_ #\- name)
2633                                priority))
2634                      (maybe-record-with-translated-name (suffixes priority)
2635                        (when (some (lambda (suffix)
2636                                      (tailwise-equal name suffix))
2637                                    suffixes)
2638                          (record-with-translated-name priority))))
2639   
2640               (maybe-record-with-translated-name '("-LOWTAG") 0)
2641               (maybe-record-with-translated-name '("-WIDETAG") 1)
2642               (maybe-record-with-munged-name "-FLAG" "flag_" 2)
2643               (maybe-record-with-munged-name "-TRAP" "trap_" 3)
2644               (maybe-record-with-munged-name "-SUBTYPE" "subtype_" 4)
2645               (maybe-record-with-munged-name "-SC-NUMBER" "sc_" 5)
2646               (maybe-record-with-translated-name '("-START" "-END" "-SIZE") 6)
2647               (maybe-record-with-translated-name '("-CORE-ENTRY-TYPE-CODE") 7)
2648               (maybe-record-with-translated-name '("-CORE-SPACE-ID") 8))))))
2649     ;; KLUDGE: these constants are sort of important, but there's no
2650     ;; pleasing way to inform the code above about them.  So we fake
2651     ;; it for now.  nikodemus on #lisp (2004-08-09) suggested simply
2652     ;; exporting every numeric constant from SB!VM; that would work,
2653     ;; but the C runtime would have to be altered to use Lisp-like names
2654     ;; rather than the munged names currently exported.  --njf, 2004-08-09
2655     (dolist (c '(sb!vm:n-word-bits sb!vm:n-word-bytes
2656                  sb!vm:n-lowtag-bits sb!vm:lowtag-mask
2657                  sb!vm:n-widetag-bits sb!vm:widetag-mask
2658                  sb!vm:n-fixnum-tag-bits sb!vm:fixnum-tag-mask))
2659       (push (list (substitute #\_ #\- (symbol-name c))
2660                   -1                    ; invent a new priority
2661                   (symbol-value c)
2662                   nil)
2663             constants))
2664
2665     (setf constants
2666           (sort constants
2667                 (lambda (const1 const2)
2668                   (if (= (second const1) (second const2))
2669                       (< (third const1) (third const2))
2670                       (< (second const1) (second const2))))))
2671     (let ((prev-priority (second (car constants))))
2672       (dolist (const constants)
2673         (destructuring-bind (name priority value doc) const
2674           (unless (= prev-priority priority)
2675             (terpri)
2676             (setf prev-priority priority))
2677           (format t "#define ~A " name)
2678           (format t 
2679                   ;; KLUDGE: As of sbcl-0.6.7.14, we're dumping two
2680                   ;; different kinds of values here, (1) small codes
2681                   ;; and (2) machine addresses. The small codes can be
2682                   ;; dumped as bare integer values. The large machine
2683                   ;; addresses might cause problems if they're large
2684                   ;; and represented as (signed) C integers, so we
2685                   ;; want to force them to be unsigned. We do that by
2686                   ;; wrapping them in the LISPOBJ macro. (We could do
2687                   ;; it with a bare "(unsigned)" cast, except that
2688                   ;; this header file is used not only in C files, but
2689                   ;; also in assembly files, which don't understand
2690                   ;; the cast syntax. The LISPOBJ macro goes away in
2691                   ;; assembly files, but that shouldn't matter because
2692                   ;; we don't do arithmetic on address constants in
2693                   ;; assembly files. See? It really is a kludge..) --
2694                   ;; WHN 2000-10-18
2695                   (let (;; cutoff for treatment as a small code
2696                         (cutoff (expt 2 16)))
2697                     (cond ((minusp value)
2698                            (error "stub: negative values unsupported"))
2699                           ((< value cutoff)
2700                            "~D")
2701                           (t
2702                            "LISPOBJ(~D)")))
2703                   value)
2704           (format t " /* 0x~X */~@[  /* ~A */~]~%" value doc))))
2705     (terpri))
2706
2707   ;; writing information about internal errors
2708   (let ((internal-errors sb!c:*backend-internal-errors*))
2709     (dotimes (i (length internal-errors))
2710       (let ((current-error (aref internal-errors i)))
2711         ;; FIXME: this UNLESS should go away (see also FIXME in
2712         ;; interr.lisp) -- APD, 2002-03-05
2713         (unless (eq nil (car current-error))
2714           (format t "#define ~A ~D~%"
2715                   (substitute #\_ #\- (symbol-name (car current-error)))
2716                   i)))))
2717   (terpri)
2718
2719   ;; FIXME: The SPARC has a PSEUDO-ATOMIC-TRAP that differs between
2720   ;; platforms. If we export this from the SB!VM package, it gets
2721   ;; written out as #define trap_PseudoAtomic, which is confusing as
2722   ;; the runtime treats trap_ as the prefix for illegal instruction
2723   ;; type things. We therefore don't export it, but instead do
2724   #!+sparc
2725   (when (boundp 'sb!vm::pseudo-atomic-trap)
2726     (format t
2727             "#define PSEUDO_ATOMIC_TRAP ~D /* 0x~:*~X */~%"
2728             sb!vm::pseudo-atomic-trap)
2729     (terpri))
2730   ;; possibly this is another candidate for a rename (to
2731   ;; pseudo-atomic-trap-number or pseudo-atomic-magic-constant
2732   ;; [possibly applicable to other platforms])
2733
2734   (dolist (symbol '(sb!vm::float-traps-byte
2735                     sb!vm::float-exceptions-byte
2736                     sb!vm::float-sticky-bits
2737                     sb!vm::float-rounding-mode))
2738     (format t "#define ~A_POSITION ~A /* ~:*0x~X */~%"
2739             (substitute #\_ #\- (symbol-name symbol))
2740             (sb!xc:byte-position (symbol-value symbol)))
2741     (format t "#define ~A_MASK 0x~X /* ~:*~A */~%"
2742             (substitute #\_ #\- (symbol-name symbol))
2743             (sb!xc:mask-field (symbol-value symbol) -1))))
2744
2745
2746
2747 (defun write-primitive-object (obj)  
2748   ;; writing primitive object layouts
2749     (format t "#ifndef LANGUAGE_ASSEMBLY~2%")
2750       (format t
2751               "struct ~A {~%"
2752               (substitute #\_ #\-
2753               (string-downcase (string (sb!vm:primitive-object-name obj)))))
2754       (when (sb!vm:primitive-object-widetag obj)
2755         (format t "    lispobj header;~%"))
2756       (dolist (slot (sb!vm:primitive-object-slots obj))
2757         (format t "    ~A ~A~@[[1]~];~%"
2758         (getf (sb!vm:slot-options slot) :c-type "lispobj")
2759         (substitute #\_ #\-
2760                     (string-downcase (string (sb!vm:slot-name slot))))
2761         (sb!vm:slot-rest-p slot)))
2762   (format t "};~2%")
2763     (format t "#else /* LANGUAGE_ASSEMBLY */~2%")
2764       (let ((name (sb!vm:primitive-object-name obj))
2765       (lowtag (eval (sb!vm:primitive-object-lowtag obj))))
2766         (when lowtag
2767         (dolist (slot (sb!vm:primitive-object-slots obj))
2768           (format t "#define ~A_~A_OFFSET ~D~%"
2769                   (substitute #\_ #\- (string name))
2770                   (substitute #\_ #\- (string (sb!vm:slot-name slot)))
2771                   (- (* (sb!vm:slot-offset slot) sb!vm:n-word-bytes) lowtag)))
2772       (terpri)))
2773     (format t "#endif /* LANGUAGE_ASSEMBLY */~2%"))
2774
2775 (defun write-static-symbols ()
2776   (dolist (symbol (cons nil sb!vm:*static-symbols*))
2777     ;; FIXME: It would be nice to use longer names than NIL and
2778     ;; (particularly) T in #define statements.
2779     (format t "#define ~A LISPOBJ(0x~X)~%"
2780             (substitute #\_ #\-
2781                         (remove-if (lambda (char)
2782                                      (member char '(#\% #\* #\. #\!)))
2783                                    (symbol-name symbol)))
2784             (if *static*                ; if we ran GENESIS
2785               ;; We actually ran GENESIS, use the real value.
2786               (descriptor-bits (cold-intern symbol))
2787               ;; We didn't run GENESIS, so guess at the address.
2788               (+ sb!vm:static-space-start
2789                  sb!vm:n-word-bytes
2790                  sb!vm:other-pointer-lowtag
2791                    (if symbol (sb!vm:static-symbol-offset symbol) 0))))))
2792
2793 \f
2794 ;;;; writing map file
2795
2796 ;;; Write a map file describing the cold load. Some of this
2797 ;;; information is subject to change due to relocating GC, but even so
2798 ;;; it can be very handy when attempting to troubleshoot the early
2799 ;;; stages of cold load.
2800 (defun write-map ()
2801   (let ((*print-pretty* nil)
2802         (*print-case* :upcase))
2803     (format t "assembler routines defined in core image:~2%")
2804     (dolist (routine (sort (copy-list *cold-assembler-routines*) #'<
2805                            :key #'cdr))
2806       (format t "#X~8,'0X: ~S~%" (cdr routine) (car routine)))
2807     (let ((funs nil)
2808           (undefs nil))
2809       (maphash (lambda (name fdefn)
2810                  (let ((fun (read-wordindexed fdefn
2811                                               sb!vm:fdefn-fun-slot)))
2812                    (if (= (descriptor-bits fun)
2813                           (descriptor-bits *nil-descriptor*))
2814                        (push name undefs)
2815                        (let ((addr (read-wordindexed
2816                                     fdefn sb!vm:fdefn-raw-addr-slot)))
2817                          (push (cons name (descriptor-bits addr))
2818                                funs)))))
2819                *cold-fdefn-objects*)
2820       (format t "~%~|~%initially defined functions:~2%")
2821       (setf funs (sort funs #'< :key #'cdr))
2822       (dolist (info funs)
2823         (format t "0x~8,'0X: ~S   #X~8,'0X~%" (cdr info) (car info)
2824                 (- (cdr info) #x17)))
2825       (format t
2826 "~%~|
2827 (a note about initially undefined function references: These functions
2828 are referred to by code which is installed by GENESIS, but they are not
2829 installed by GENESIS. This is not necessarily a problem; functions can
2830 be defined later, by cold init toplevel forms, or in files compiled and
2831 loaded at warm init, or elsewhere. As long as they are defined before
2832 they are called, everything should be OK. Things are also OK if the
2833 cross-compiler knew their inline definition and used that everywhere
2834 that they were called before the out-of-line definition is installed,
2835 as is fairly common for structure accessors.)
2836 initially undefined function references:~2%")
2837
2838       (setf undefs (sort undefs #'string< :key #'fun-name-block-name))
2839       (dolist (name undefs)
2840         (format t "~S~%" name)))
2841
2842     (format t "~%~|~%layout names:~2%")
2843     (collect ((stuff))
2844       (maphash (lambda (name gorp)
2845                  (declare (ignore name))
2846                  (stuff (cons (descriptor-bits (car gorp))
2847                               (cdr gorp))))
2848                *cold-layouts*)
2849       (dolist (x (sort (stuff) #'< :key #'car))
2850         (apply #'format t "~8,'0X: ~S[~D]~%~10T~S~%" x))))
2851
2852   (values))
2853 \f
2854 ;;;; writing core file
2855
2856 (defvar *core-file*)
2857 (defvar *data-page*)
2858
2859 ;;; magic numbers to identify entries in a core file
2860 ;;;
2861 ;;; (In case you were wondering: No, AFAIK there's no special magic about
2862 ;;; these which requires them to be in the 38xx range. They're just
2863 ;;; arbitrary words, tested not for being in a particular range but just
2864 ;;; for equality. However, if you ever need to look at a .core file and
2865 ;;; figure out what's going on, it's slightly convenient that they're
2866 ;;; all in an easily recognizable range, and displacing the range away from
2867 ;;; zero seems likely to reduce the chance that random garbage will be
2868 ;;; misinterpreted as a .core file.)
2869 (defconstant version-core-entry-type-code 3860)
2870 (defconstant build-id-core-entry-type-code 3899)
2871 (defconstant new-directory-core-entry-type-code 3861)
2872 (defconstant initial-fun-core-entry-type-code 3863)
2873 (defconstant end-core-entry-type-code 3840)
2874
2875 (declaim (ftype (function (sb!vm:word) sb!vm:word) write-word))
2876 (defun write-word (num)
2877   (ecase sb!c:*backend-byte-order*
2878     (:little-endian
2879      (dotimes (i sb!vm:n-word-bytes)
2880        (write-byte (ldb (byte 8 (* i 8)) num) *core-file*)))
2881     (:big-endian
2882      (dotimes (i sb!vm:n-word-bytes)
2883        (write-byte (ldb (byte 8 (* (- (1- sb!vm:n-word-bytes) i) 8)) num) 
2884                    *core-file*))))
2885   num)
2886
2887 (defun advance-to-page ()
2888   (force-output *core-file*)
2889   (file-position *core-file*
2890                  (round-up (file-position *core-file*)
2891                            sb!c:*backend-page-size*)))
2892
2893 (defun output-gspace (gspace)
2894   (force-output *core-file*)
2895   (let* ((posn (file-position *core-file*))
2896          (bytes (* (gspace-free-word-index gspace) sb!vm:n-word-bytes))
2897          (pages (ceiling bytes sb!c:*backend-page-size*))
2898          (total-bytes (* pages sb!c:*backend-page-size*)))
2899
2900     (file-position *core-file*
2901                    (* sb!c:*backend-page-size* (1+ *data-page*)))
2902     (format t
2903             "writing ~S byte~:P [~S page~:P] from ~S~%"
2904             total-bytes
2905             pages
2906             gspace)
2907     (force-output)
2908
2909     ;; Note: It is assumed that the GSPACE allocation routines always
2910     ;; allocate whole pages (of size *target-page-size*) and that any
2911     ;; empty gspace between the free pointer and the end of page will
2912     ;; be zero-filled. This will always be true under Mach on machines
2913     ;; where the page size is equal. (RT is 4K, PMAX is 4K, Sun 3 is
2914     ;; 8K).
2915     (write-bigvec-as-sequence (gspace-bytes gspace)
2916                               *core-file*
2917                               :end total-bytes)
2918     (force-output *core-file*)
2919     (file-position *core-file* posn)
2920
2921     ;; Write part of a (new) directory entry which looks like this:
2922     ;;   GSPACE IDENTIFIER
2923     ;;   WORD COUNT
2924     ;;   DATA PAGE
2925     ;;   ADDRESS
2926     ;;   PAGE COUNT
2927     (write-word (gspace-identifier gspace))
2928     (write-word (gspace-free-word-index gspace))
2929     (write-word *data-page*)
2930     (multiple-value-bind (floor rem)
2931         (floor (gspace-byte-address gspace) sb!c:*backend-page-size*)
2932       (aver (zerop rem))
2933       (write-word floor))
2934     (write-word pages)
2935
2936     (incf *data-page* pages)))
2937
2938 ;;; Create a core file created from the cold loaded image. (This is
2939 ;;; the "initial core file" because core files could be created later
2940 ;;; by executing SAVE-LISP in a running system, perhaps after we've
2941 ;;; added some functionality to the system.)
2942 (declaim (ftype (function (string)) write-initial-core-file))
2943 (defun write-initial-core-file (filename)
2944
2945   (let ((filenamestring (namestring filename))
2946         (*data-page* 0))
2947
2948     (format t
2949             "[building initial core file in ~S: ~%"
2950             filenamestring)
2951     (force-output)
2952
2953     (with-open-file (*core-file* filenamestring
2954                                  :direction :output
2955                                  :element-type '(unsigned-byte 8)
2956                                  :if-exists :rename-and-delete)
2957
2958       ;; Write the magic number.
2959       (write-word core-magic)
2960
2961       ;; Write the Version entry.
2962       (write-word version-core-entry-type-code)
2963       (write-word 3)
2964       (write-word sbcl-core-version-integer)
2965
2966       ;; Write the build ID.
2967       (write-word build-id-core-entry-type-code)
2968       (let ((build-id (with-open-file (s "output/build-id.tmp"
2969                                          :direction :input)
2970                         (read s))))
2971         (declare (type simple-string build-id))
2972         (/show build-id (length build-id))
2973         ;; Write length of build ID record: BUILD-ID-CORE-ENTRY-TYPE-CODE
2974         ;; word, this length word, and one word for each char of BUILD-ID.
2975         (write-word (+ 2 (length build-id)))
2976         (dovector (char build-id)
2977           ;; (We write each character as a word in order to avoid
2978           ;; having to think about word alignment issues in the
2979           ;; sbcl-0.7.8 version of coreparse.c.)
2980           (write-word (sb!xc:char-code char))))
2981
2982       ;; Write the New Directory entry header.
2983       (write-word new-directory-core-entry-type-code)
2984       (write-word 17) ; length = (5 words/space) * 3 spaces + 2 for header.
2985
2986       (output-gspace *read-only*)
2987       (output-gspace *static*)
2988       (output-gspace *dynamic*)
2989
2990       ;; Write the initial function.
2991       (write-word initial-fun-core-entry-type-code)
2992       (write-word 3)
2993       (let* ((cold-name (cold-intern '!cold-init))
2994              (cold-fdefn (cold-fdefinition-object cold-name))
2995              (initial-fun (read-wordindexed cold-fdefn
2996                                             sb!vm:fdefn-fun-slot)))
2997         (format t
2998                 "~&/(DESCRIPTOR-BITS INITIAL-FUN)=#X~X~%"
2999                 (descriptor-bits initial-fun))
3000         (write-word (descriptor-bits initial-fun)))
3001
3002       ;; Write the End entry.
3003       (write-word end-core-entry-type-code)
3004       (write-word 2)))
3005
3006   (format t "done]~%")
3007   (force-output)
3008   (/show "leaving WRITE-INITIAL-CORE-FILE")
3009   (values))
3010 \f
3011 ;;;; the actual GENESIS function
3012
3013 ;;; Read the FASL files in OBJECT-FILE-NAMES and produce a Lisp core,
3014 ;;; and/or information about a Lisp core, therefrom.
3015 ;;;
3016 ;;; input file arguments:
3017 ;;;   SYMBOL-TABLE-FILE-NAME names a UNIX-style .nm file *with* *any*
3018 ;;;     *tab* *characters* *converted* *to* *spaces*. (We push
3019 ;;;     responsibility for removing tabs out to the caller it's
3020 ;;;     trivial to remove them using UNIX command line tools like
3021 ;;;     sed, whereas it's a headache to do it portably in Lisp because
3022 ;;;     #\TAB is not a STANDARD-CHAR.) If this file is not supplied,
3023 ;;;     a core file cannot be built (but a C header file can be).
3024 ;;;
3025 ;;; output files arguments (any of which may be NIL to suppress output):
3026 ;;;   CORE-FILE-NAME gets a Lisp core.
3027 ;;;   C-HEADER-FILE-NAME gets a C header file, traditionally called
3028 ;;;     internals.h, which is used by the C compiler when constructing
3029 ;;;     the executable which will load the core.
3030 ;;;   MAP-FILE-NAME gets (?) a map file. (dunno about this -- WHN 19990815)
3031 ;;;
3032 ;;; FIXME: GENESIS doesn't belong in SB!VM. Perhaps in %KERNEL for now,
3033 ;;; perhaps eventually in SB-LD or SB-BOOT.
3034 (defun sb!vm:genesis (&key
3035                       object-file-names
3036                       symbol-table-file-name
3037                       core-file-name
3038                       map-file-name
3039                       c-header-dir-name)
3040
3041   (format t
3042           "~&beginning GENESIS, ~A~%"
3043           (if core-file-name
3044             ;; Note: This output summarizing what we're doing is
3045             ;; somewhat telegraphic in style, not meant to imply that
3046             ;; we're not e.g. also creating a header file when we
3047             ;; create a core.
3048             (format nil "creating core ~S" core-file-name)
3049             (format nil "creating headers in ~S" c-header-dir-name)))
3050   
3051   (let ((*cold-foreign-symbol-table* (make-hash-table :test 'equal)))
3052
3053     (when core-file-name
3054       (if symbol-table-file-name
3055           (load-cold-foreign-symbol-table symbol-table-file-name)
3056           (error "can't output a core file without symbol table file input")))
3057
3058     ;; Now that we've successfully read our only input file (by
3059     ;; loading the symbol table, if any), it's a good time to ensure
3060     ;; that there'll be someplace for our output files to go when
3061     ;; we're done.
3062     (flet ((frob (filename)
3063              (when filename
3064                (ensure-directories-exist filename :verbose t))))
3065       (frob core-file-name)
3066       (frob map-file-name))
3067
3068     ;; (This shouldn't matter in normal use, since GENESIS normally
3069     ;; only runs once in any given Lisp image, but it could reduce
3070     ;; confusion if we ever experiment with running, tweaking, and
3071     ;; rerunning genesis interactively.)
3072     (do-all-symbols (sym)
3073       (remprop sym 'cold-intern-info))
3074
3075     (let* ((*foreign-symbol-placeholder-value* (if core-file-name nil 0))
3076            (*load-time-value-counter* 0)
3077            (*cold-fdefn-objects* (make-hash-table :test 'equal))
3078            (*cold-symbols* (make-hash-table :test 'equal))
3079            (*cold-package-symbols* nil)
3080            (*read-only* (make-gspace :read-only
3081                                      read-only-core-space-id
3082                                      sb!vm:read-only-space-start))
3083            (*static*    (make-gspace :static
3084                                      static-core-space-id
3085                                      sb!vm:static-space-start))
3086            (*dynamic*   (make-gspace :dynamic
3087                                      dynamic-core-space-id
3088                                      #!+gencgc sb!vm:dynamic-space-start
3089                                      #!-gencgc sb!vm:dynamic-0-space-start))
3090            (*nil-descriptor* (make-nil-descriptor))
3091            (*current-reversed-cold-toplevels* *nil-descriptor*)
3092            (*unbound-marker* (make-other-immediate-descriptor
3093                               0
3094                               sb!vm:unbound-marker-widetag))
3095            *cold-assembler-fixups*
3096            *cold-assembler-routines*
3097            #!+(or x86 x86-64) *load-time-code-fixups*)
3098
3099       ;; Prepare for cold load.
3100       (initialize-non-nil-symbols)
3101       (initialize-layouts)
3102       (initialize-static-fns)
3103
3104       ;; Initialize the *COLD-SYMBOLS* system with the information
3105       ;; from package-data-list.lisp-expr and
3106       ;; common-lisp-exports.lisp-expr.
3107       ;;
3108       ;; Why do things this way? Historically, the *COLD-SYMBOLS*
3109       ;; machinery was designed and implemented in CMU CL long before
3110       ;; I (WHN) ever heard of CMU CL. It dumped symbols and packages
3111       ;; iff they were used in the cold image. When I added the
3112       ;; package-data-list.lisp-expr mechanism, the idea was to
3113       ;; centralize all information about packages and exports. Thus,
3114       ;; it was the natural place for information even about packages
3115       ;; (such as SB!PCL and SB!WALKER) which aren't used much until
3116       ;; after cold load. This didn't quite match the CMU CL approach
3117       ;; of filling *COLD-SYMBOLS* with symbols which appear in the
3118       ;; cold image and then dumping only those symbols. By explicitly
3119       ;; putting all the symbols from package-data-list.lisp-expr and
3120       ;; from common-lisp-exports.lisp-expr into *COLD-SYMBOLS* here,
3121       ;; we feed our centralized symbol information into the old CMU
3122       ;; CL code without having to change the old CMU CL code too
3123       ;; much. (And the old CMU CL code is still useful for making
3124       ;; sure that the appropriate keywords and internal symbols end
3125       ;; up interned in the target Lisp, which is good, e.g. in order
3126       ;; to make &KEY arguments work right and in order to make
3127       ;; BACKTRACEs into target Lisp system code be legible.)
3128       (dolist (exported-name
3129                (sb-cold:read-from-file "common-lisp-exports.lisp-expr"))
3130         (cold-intern (intern exported-name *cl-package*)))
3131       (dolist (pd (sb-cold:read-from-file "package-data-list.lisp-expr"))
3132         (declare (type sb-cold:package-data pd))
3133         (let ((package (find-package (sb-cold:package-data-name pd))))
3134           (labels (;; Call FN on every node of the TREE.
3135                    (mapc-on-tree (fn tree)
3136                                  (declare (type function fn))
3137                                  (typecase tree
3138                                    (cons (mapc-on-tree fn (car tree))
3139                                          (mapc-on-tree fn (cdr tree)))
3140                                    (t (funcall fn tree)
3141                                       (values))))
3142                    ;; Make sure that information about the association
3143                    ;; between PACKAGE and the symbol named NAME gets
3144                    ;; recorded in the cold-intern system or (as a
3145                    ;; convenience when dealing with the tree structure
3146                    ;; allowed in the PACKAGE-DATA-EXPORTS slot) do
3147                    ;; nothing if NAME is NIL.
3148                    (chill (name)
3149                      (when name
3150                        (cold-intern (intern name package) package))))
3151             (mapc-on-tree #'chill (sb-cold:package-data-export pd))
3152             (mapc #'chill (sb-cold:package-data-reexport pd))
3153             (dolist (sublist (sb-cold:package-data-import-from pd))
3154               (destructuring-bind (package-name &rest symbol-names) sublist
3155                 (declare (ignore package-name))
3156                 (mapc #'chill symbol-names))))))
3157
3158       ;; Cold load.
3159       (dolist (file-name object-file-names)
3160         (write-line (namestring file-name))
3161         (cold-load file-name))
3162
3163       ;; Tidy up loose ends left by cold loading. ("Postpare from cold load?")
3164       (resolve-assembler-fixups)
3165       #!+(or x86 x86-64) (output-load-time-code-fixups)
3166       (foreign-symbols-to-core)
3167       (finish-symbols)
3168       (/show "back from FINISH-SYMBOLS")
3169       (finalize-load-time-value-noise)
3170
3171       ;; Tell the target Lisp how much stuff we've allocated.
3172       (cold-set 'sb!vm:*read-only-space-free-pointer*
3173                 (allocate-cold-descriptor *read-only*
3174                                           0
3175                                           sb!vm:even-fixnum-lowtag))
3176       (cold-set 'sb!vm:*static-space-free-pointer*
3177                 (allocate-cold-descriptor *static*
3178                                           0
3179                                           sb!vm:even-fixnum-lowtag))
3180       (cold-set 'sb!vm:*initial-dynamic-space-free-pointer*
3181                 (allocate-cold-descriptor *dynamic*
3182                                           0
3183                                           sb!vm:even-fixnum-lowtag))
3184       (/show "done setting free pointers")
3185
3186       ;; Write results to files.
3187       ;;
3188       ;; FIXME: I dislike this approach of redefining
3189       ;; *STANDARD-OUTPUT* instead of putting the new stream in a
3190       ;; lexical variable, and it's annoying to have WRITE-MAP (to
3191       ;; *STANDARD-OUTPUT*) not be parallel to WRITE-INITIAL-CORE-FILE
3192       ;; (to a stream explicitly passed as an argument).
3193       (macrolet ((out-to (name &body body)
3194                    `(let ((fn (format nil "~A/~A.h" c-header-dir-name ,name)))
3195                      (ensure-directories-exist fn)
3196                      (with-open-file (*standard-output* fn  
3197                                       :if-exists :supersede :direction :output)
3198                        (write-boilerplate)
3199                        (let ((n (substitute #\_ #\- (string-upcase ,name))))
3200                          (format 
3201                           t
3202                           "#ifndef SBCL_GENESIS_~A~%#define SBCL_GENESIS_~A 1~%"
3203                           n n))
3204                        ,@body
3205                        (format t
3206                         "#endif /* SBCL_GENESIS_~A */~%"
3207                         (string-upcase ,name))))))
3208       (when map-file-name
3209         (with-open-file (*standard-output* map-file-name
3210                                            :direction :output
3211                                            :if-exists :supersede)
3212           (write-map)))
3213         (out-to "config" (write-config-h))
3214         (out-to "constants" (write-constants-h))
3215         (let ((structs (sort (copy-list sb!vm:*primitive-objects*) #'string<
3216                              :key (lambda (obj)
3217                                     (symbol-name
3218                                      (sb!vm:primitive-object-name obj))))))
3219           (dolist (obj structs)
3220             (out-to
3221              (string-downcase (string (sb!vm:primitive-object-name obj)))
3222              (write-primitive-object obj)))
3223           (out-to "primitive-objects"
3224                   (dolist (obj structs)
3225                     (format t "~&#include \"~A.h\"~%"
3226                             (string-downcase 
3227                              (string (sb!vm:primitive-object-name obj)))))))
3228         (out-to "static-symbols" (write-static-symbols))
3229         
3230       (when core-file-name
3231           (write-initial-core-file core-file-name))))))