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