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