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