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