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