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