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