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