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