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