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