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