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