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