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