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